check_expr.cpp 365 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451
  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. gb_internal bool is_exact_value_zero(ExactValue const &v);
  107. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node);
  108. enum LoadDirectiveResult {
  109. LoadDirective_Success = 0,
  110. LoadDirective_Error = 1,
  111. LoadDirective_NotFound = 2,
  112. };
  113. gb_internal bool is_load_directive_call(Ast *call) {
  114. call = unparen_expr(call);
  115. if (call->kind != Ast_CallExpr) {
  116. return false;
  117. }
  118. ast_node(ce, CallExpr, call);
  119. if (ce->proc->kind != Ast_BasicDirective) {
  120. return false;
  121. }
  122. ast_node(bd, BasicDirective, ce->proc);
  123. String name = bd->name.string;
  124. return name == "load";
  125. }
  126. gb_internal LoadDirectiveResult check_load_directive(CheckerContext *c, Operand *operand, Ast *call, Type *type_hint, bool err_on_not_found);
  127. gb_internal void check_did_you_mean_print(DidYouMeanAnswers *d, char const *prefix = "") {
  128. auto results = did_you_mean_results(d);
  129. if (results.count != 0) {
  130. error_line("\tSuggestion: Did you mean?\n");
  131. for (auto const &result : results) {
  132. String const &target = result.target;
  133. error_line("\t\t%s%.*s\n", prefix, LIT(target));
  134. // error_line("\t\t%.*s %td\n", LIT(target), results[i].distance);
  135. }
  136. }
  137. }
  138. gb_internal void populate_check_did_you_mean_objc_entity(StringSet *set, Entity *e, bool is_type) {
  139. if (e->kind != Entity_TypeName) {
  140. return;
  141. }
  142. if (e->TypeName.objc_metadata == nullptr) {
  143. return;
  144. }
  145. TypeNameObjCMetadata *objc_metadata = e->TypeName.objc_metadata;
  146. Type *t = base_type(e->type);
  147. GB_ASSERT(t->kind == Type_Struct);
  148. if (is_type) {
  149. for (auto const &entry : objc_metadata->type_entries) {
  150. string_set_add(set, entry.name);
  151. }
  152. } else {
  153. for (auto const &entry : objc_metadata->value_entries) {
  154. string_set_add(set, entry.name);
  155. }
  156. }
  157. for (Entity *f : t->Struct.fields) {
  158. if (f->flags & EntityFlag_Using && f->type != nullptr) {
  159. if (f->type->kind == Type_Named && f->type->Named.type_name) {
  160. populate_check_did_you_mean_objc_entity(set, f->type->Named.type_name, is_type);
  161. }
  162. }
  163. }
  164. }
  165. gb_internal void check_did_you_mean_objc_entity(String const &name, Entity *e, bool is_type, char const *prefix = "") {
  166. if (build_context.terse_errors) { return; }
  167. ERROR_BLOCK();
  168. GB_ASSERT(e->kind == Entity_TypeName);
  169. GB_ASSERT(e->TypeName.objc_metadata != nullptr);
  170. auto *objc_metadata = e->TypeName.objc_metadata;
  171. MUTEX_GUARD(objc_metadata->mutex);
  172. StringSet set = {};
  173. defer (string_set_destroy(&set));
  174. populate_check_did_you_mean_objc_entity(&set, e, is_type);
  175. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), set.entries.count, name);
  176. defer (did_you_mean_destroy(&d));
  177. for (String const &target : set) {
  178. did_you_mean_append(&d, target);
  179. }
  180. check_did_you_mean_print(&d, prefix);
  181. }
  182. gb_internal void check_did_you_mean_type(String const &name, Array<Entity *> const &fields, char const *prefix = "") {
  183. if (build_context.terse_errors) { return; }
  184. ERROR_BLOCK();
  185. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  186. defer (did_you_mean_destroy(&d));
  187. for (Entity *e : fields) {
  188. did_you_mean_append(&d, e->token.string);
  189. }
  190. check_did_you_mean_print(&d, prefix);
  191. }
  192. gb_internal void check_did_you_mean_type(String const &name, Slice<Entity *> const &fields, char const *prefix = "") {
  193. if (build_context.terse_errors) { return; }
  194. ERROR_BLOCK();
  195. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), fields.count, name);
  196. defer (did_you_mean_destroy(&d));
  197. for (Entity *e : fields) {
  198. did_you_mean_append(&d, e->token.string);
  199. }
  200. check_did_you_mean_print(&d, prefix);
  201. }
  202. gb_internal void check_did_you_mean_scope(String const &name, Scope *scope, char const *prefix = "") {
  203. if (build_context.terse_errors) { return; }
  204. ERROR_BLOCK();
  205. DidYouMeanAnswers d = did_you_mean_make(heap_allocator(), scope->elements.count, name);
  206. defer (did_you_mean_destroy(&d));
  207. rw_mutex_shared_lock(&scope->mutex);
  208. for (auto const &entry : scope->elements) {
  209. Entity *e = entry.value;
  210. did_you_mean_append(&d, e->token.string);
  211. }
  212. rw_mutex_shared_unlock(&scope->mutex);
  213. check_did_you_mean_print(&d, prefix);
  214. }
  215. gb_internal Entity *entity_from_expr(Ast *expr) {
  216. expr = unparen_expr(expr);
  217. if (expr == nullptr) {
  218. return nullptr;
  219. }
  220. switch (expr->kind) {
  221. case Ast_Ident:
  222. return expr->Ident.entity;
  223. case Ast_SelectorExpr:
  224. return entity_from_expr(expr->SelectorExpr.selector);
  225. }
  226. return nullptr;
  227. }
  228. gb_internal void error_operand_not_expression(Operand *o) {
  229. if (o->mode == Addressing_Type) {
  230. gbString err = expr_to_string(o->expr);
  231. error(o->expr, "'%s' is not an expression but a type", err);
  232. gb_string_free(err);
  233. o->mode = Addressing_Invalid;
  234. }
  235. }
  236. gb_internal void error_operand_no_value(Operand *o) {
  237. if (o->mode == Addressing_NoValue) {
  238. Ast *x = unparen_expr(o->expr);
  239. if (x != nullptr && x->kind == Ast_CallExpr) {
  240. Ast *p = unparen_expr(x->CallExpr.proc);
  241. if (p->kind == Ast_BasicDirective) {
  242. String tag = p->BasicDirective.name.string;
  243. if (tag == "panic" ||
  244. tag == "assert") {
  245. return;
  246. }
  247. }
  248. }
  249. gbString err = expr_to_string(o->expr);
  250. if (x != nullptr && x->kind == Ast_CallExpr) {
  251. error(o->expr, "'%s' call does not return a value and cannot be used as a value", err);
  252. } else {
  253. error(o->expr, "'%s' used as a value", err);
  254. }
  255. gb_string_free(err);
  256. o->mode = Addressing_Invalid;
  257. }
  258. }
  259. gb_internal void add_map_get_dependencies(CheckerContext *c) {
  260. if (build_context.dynamic_map_calls) {
  261. add_package_dependency(c, "runtime", "__dynamic_map_get");
  262. } else {
  263. add_package_dependency(c, "runtime", "map_desired_position");
  264. add_package_dependency(c, "runtime", "map_probe_distance");
  265. }
  266. }
  267. gb_internal void add_map_set_dependencies(CheckerContext *c) {
  268. init_core_source_code_location(c->checker);
  269. if (t_map_set_proc == nullptr) {
  270. Type *map_set_args[5] = {/*map*/t_rawptr, /*hash*/t_uintptr, /*key*/t_rawptr, /*value*/t_rawptr, /*#caller_location*/t_source_code_location};
  271. t_map_set_proc = alloc_type_proc_from_types(map_set_args, gb_count_of(map_set_args), t_rawptr, false, ProcCC_Odin);
  272. }
  273. if (build_context.dynamic_map_calls) {
  274. add_package_dependency(c, "runtime", "__dynamic_map_set");
  275. } else {
  276. add_package_dependency(c, "runtime", "__dynamic_map_check_grow");
  277. add_package_dependency(c, "runtime", "map_insert_hash_dynamic");
  278. }
  279. }
  280. gb_internal void add_map_reserve_dependencies(CheckerContext *c) {
  281. init_core_source_code_location(c->checker);
  282. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  283. }
  284. gb_internal void check_scope_decls(CheckerContext *c, Slice<Ast *> const &nodes, isize reserve_size) {
  285. Scope *s = c->scope;
  286. check_collect_entities(c, nodes);
  287. for (auto const &entry : s->elements) {
  288. Entity *e = entry.value;\
  289. switch (e->kind) {
  290. case Entity_Constant:
  291. case Entity_TypeName:
  292. case Entity_Procedure:
  293. break;
  294. default:
  295. continue;
  296. }
  297. DeclInfo *d = decl_info_of_entity(e);
  298. if (d != nullptr) {
  299. check_entity_decl(c, e, d, nullptr);
  300. }
  301. }
  302. }
  303. gb_internal bool find_or_generate_polymorphic_procedure(CheckerContext *old_c, Entity *base_entity, Type *type,
  304. Array<Operand> const *param_operands, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  305. ///////////////////////////////////////////////////////////////////////////////
  306. // //
  307. // TODO CLEANUP(bill): This procedure is very messy and hacky. Clean this!!! //
  308. // //
  309. ///////////////////////////////////////////////////////////////////////////////
  310. CheckerInfo *info = old_c->info;
  311. if (base_entity == nullptr) {
  312. return false;
  313. }
  314. if (!is_type_proc(base_entity->type)) {
  315. return false;
  316. }
  317. if (base_entity->flags & EntityFlag_Disabled) {
  318. return false;
  319. }
  320. String name = base_entity->token.string;
  321. Type *src = base_type(base_entity->type);
  322. Type *dst = nullptr;
  323. if (type != nullptr) {
  324. dst = base_type(type);
  325. }
  326. if (param_operands == nullptr) {
  327. GB_ASSERT(dst != nullptr);
  328. }
  329. if (param_operands != nullptr) {
  330. GB_ASSERT(dst == nullptr);
  331. }
  332. if (!src->Proc.is_polymorphic || src->Proc.is_poly_specialized) {
  333. return false;
  334. }
  335. if (dst != nullptr) {
  336. if (dst->Proc.is_polymorphic) {
  337. return false;
  338. }
  339. if (dst->Proc.param_count != src->Proc.param_count ||
  340. dst->Proc.result_count != src->Proc.result_count) {
  341. return false;
  342. }
  343. }
  344. DeclInfo *old_decl = decl_info_of_entity(base_entity);
  345. if (old_decl == nullptr) {
  346. return false;
  347. }
  348. gbAllocator a = heap_allocator();
  349. Array<Operand> operands = {};
  350. if (param_operands) {
  351. operands = *param_operands;
  352. } else {
  353. operands = array_make<Operand>(a, 0, dst->Proc.param_count);
  354. for (isize i = 0; i < dst->Proc.param_count; i++) {
  355. Entity *param = dst->Proc.params->Tuple.variables[i];
  356. Operand o = {Addressing_Value};
  357. o.type = param->type;
  358. array_add(&operands, o);
  359. }
  360. }
  361. defer (if (param_operands == nullptr) {
  362. array_free(&operands);
  363. });
  364. CheckerContext nctx = *old_c;
  365. Scope *scope = create_scope(info, base_entity->scope);
  366. scope->flags |= ScopeFlag_Proc;
  367. nctx.scope = scope;
  368. nctx.allow_polymorphic_types = true;
  369. if (nctx.polymorphic_scope == nullptr) {
  370. nctx.polymorphic_scope = scope;
  371. }
  372. auto *pt = &src->Proc;
  373. // NOTE(bill): This is slightly memory leaking if the type already exists
  374. // Maybe it's better to check with the previous types first?
  375. Type *final_proc_type = alloc_type_proc(scope, nullptr, 0, nullptr, 0, false, pt->calling_convention);
  376. bool success = check_procedure_type(&nctx, final_proc_type, pt->node, &operands);
  377. if (!success) {
  378. return false;
  379. }
  380. GenProcsData *gen_procs = nullptr;
  381. GB_ASSERT(base_entity->identifier.load()->kind == Ast_Ident);
  382. GB_ASSERT(base_entity->kind == Entity_Procedure);
  383. mutex_lock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  384. gen_procs = base_entity->Procedure.gen_procs;
  385. if (gen_procs) {
  386. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  387. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  388. for (Entity *other : gen_procs->procs) {
  389. Type *pt = base_type(other->type);
  390. if (are_types_identical(pt, final_proc_type)) {
  391. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  392. if (poly_proc_data) {
  393. poly_proc_data->gen_entity = other;
  394. }
  395. return true;
  396. }
  397. }
  398. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  399. } else {
  400. gen_procs = gb_alloc_item(permanent_allocator(), GenProcsData);
  401. gen_procs->procs.allocator = heap_allocator();
  402. base_entity->Procedure.gen_procs = gen_procs;
  403. mutex_unlock(&base_entity->Procedure.gen_procs_mutex); // @entity-mutex
  404. }
  405. {
  406. // LEAK NOTE(bill): This is technically a memory leak as it has to generate the type twice
  407. bool prev_no_polymorphic_errors = nctx.no_polymorphic_errors;
  408. defer (nctx.no_polymorphic_errors = prev_no_polymorphic_errors);
  409. nctx.no_polymorphic_errors = false;
  410. // NOTE(bill): Reset scope from the failed procedure type
  411. scope->head_child.store(nullptr, std::memory_order_relaxed);
  412. string_map_clear(&scope->elements);
  413. ptr_set_clear(&scope->imported);
  414. // LEAK NOTE(bill): Cloning this AST may be leaky but this is not really an issue due to arena-based allocation
  415. Ast *cloned_proc_type_node = clone_ast(pt->node);
  416. success = check_procedure_type(&nctx, final_proc_type, cloned_proc_type_node, &operands);
  417. if (!success) {
  418. return false;
  419. }
  420. rw_mutex_shared_lock(&gen_procs->mutex); // @local-mutex
  421. for (Entity *other : gen_procs->procs) {
  422. Type *pt = base_type(other->type);
  423. if (are_types_identical(pt, final_proc_type)) {
  424. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  425. if (poly_proc_data) {
  426. poly_proc_data->gen_entity = other;
  427. }
  428. DeclInfo *decl = other->decl_info;
  429. if (decl->proc_checked_state != ProcCheckedState_Checked) {
  430. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  431. proc_info->file = other->file;
  432. proc_info->token = other->token;
  433. proc_info->decl = decl;
  434. proc_info->type = other->type;
  435. proc_info->body = decl->proc_lit->ProcLit.body;
  436. proc_info->tags = other->Procedure.tags;;
  437. proc_info->generated_from_polymorphic = true;
  438. proc_info->poly_def_node = poly_def_node;
  439. check_procedure_later(nctx.checker, proc_info);
  440. }
  441. return true;
  442. }
  443. }
  444. rw_mutex_shared_unlock(&gen_procs->mutex); // @local-mutex
  445. }
  446. Ast *proc_lit = clone_ast(old_decl->proc_lit);
  447. ast_node(pl, ProcLit, proc_lit);
  448. // NOTE(bill): Associate the scope declared above withinth this procedure declaration's type
  449. add_scope(&nctx, pl->type, final_proc_type->Proc.scope);
  450. final_proc_type->Proc.is_poly_specialized = true;
  451. final_proc_type->Proc.is_polymorphic = true;
  452. final_proc_type->Proc.variadic = src->Proc.variadic;
  453. final_proc_type->Proc.require_results = src->Proc.require_results;
  454. final_proc_type->Proc.c_vararg = src->Proc.c_vararg;
  455. final_proc_type->Proc.has_named_results = src->Proc.has_named_results;
  456. final_proc_type->Proc.diverging = src->Proc.diverging;
  457. final_proc_type->Proc.return_by_pointer = src->Proc.return_by_pointer;
  458. final_proc_type->Proc.optional_ok = src->Proc.optional_ok;
  459. final_proc_type->Proc.enable_target_feature = src->Proc.enable_target_feature;
  460. final_proc_type->Proc.require_target_feature = src->Proc.require_target_feature;
  461. for (isize i = 0; i < operands.count; i++) {
  462. Operand o = operands[i];
  463. if (final_proc_type == o.type ||
  464. base_entity->type == o.type) {
  465. // NOTE(bill): Cycle
  466. final_proc_type->Proc.is_poly_specialized = false;
  467. break;
  468. }
  469. }
  470. u64 tags = base_entity->Procedure.tags;
  471. Ast *ident = clone_ast(base_entity->identifier);
  472. Token token = ident->Ident.token;
  473. DeclInfo *d = make_decl_info(scope, old_decl->parent);
  474. d->gen_proc_type = final_proc_type;
  475. d->type_expr = pl->type;
  476. d->proc_lit = proc_lit;
  477. d->proc_checked_state = ProcCheckedState_Unchecked;
  478. d->defer_use_checked = false;
  479. Entity *entity = alloc_entity_procedure(nullptr, token, final_proc_type, tags);
  480. entity->state.store(EntityState_Resolved);
  481. entity->identifier = ident;
  482. add_entity_and_decl_info(&nctx, ident, entity, d);
  483. // NOTE(bill): Set the scope afterwards as this is not real overloading
  484. entity->scope = scope->parent;
  485. entity->file = base_entity->file;
  486. entity->pkg = base_entity->pkg;
  487. entity->flags = 0;
  488. entity->Procedure.optimization_mode = base_entity->Procedure.optimization_mode;
  489. if (base_entity->flags & EntityFlag_Cold) {
  490. entity->flags |= EntityFlag_Cold;
  491. }
  492. if (base_entity->flags & EntityFlag_Disabled) {
  493. entity->flags |= EntityFlag_Disabled;
  494. }
  495. d->entity = entity;
  496. AstFile *file = nullptr;
  497. {
  498. Scope *s = entity->scope;
  499. while (s != nullptr && s->file == nullptr) {
  500. file = s->file;
  501. s = s->parent;
  502. }
  503. }
  504. rw_mutex_lock(&gen_procs->mutex); // @local-mutex
  505. array_add(&gen_procs->procs, entity);
  506. rw_mutex_unlock(&gen_procs->mutex); // @local-mutex
  507. ProcInfo *proc_info = gb_alloc_item(permanent_allocator(), ProcInfo);
  508. proc_info->file = file;
  509. proc_info->token = token;
  510. proc_info->decl = d;
  511. proc_info->type = final_proc_type;
  512. proc_info->body = pl->body;
  513. proc_info->tags = tags;
  514. proc_info->generated_from_polymorphic = true;
  515. proc_info->poly_def_node = poly_def_node;
  516. if (poly_proc_data) {
  517. poly_proc_data->gen_entity = entity;
  518. poly_proc_data->proc_info = proc_info;
  519. entity->Procedure.generated_from_polymorphic = proc_info->generated_from_polymorphic;
  520. }
  521. // NOTE(bill): Check the newly generated procedure body
  522. check_procedure_later(nctx.checker, proc_info);
  523. return true;
  524. }
  525. gb_internal bool check_polymorphic_procedure_assignment(CheckerContext *c, Operand *operand, Type *type, Ast *poly_def_node, PolyProcData *poly_proc_data) {
  526. if (operand->expr == nullptr) return false;
  527. Entity *base_entity = entity_from_expr(operand->expr);
  528. if (base_entity == nullptr) return false;
  529. return find_or_generate_polymorphic_procedure(c, base_entity, type, nullptr, poly_def_node, poly_proc_data);
  530. }
  531. 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) {
  532. return find_or_generate_polymorphic_procedure(c, base_entity, nullptr, operands, poly_def_node, poly_proc_data);
  533. }
  534. gb_internal bool check_type_specialization_to(CheckerContext *c, Type *specialization, Type *type, bool compound, bool modify_type);
  535. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type);
  536. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type);
  537. #define MAXIMUM_TYPE_DISTANCE 10
  538. gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming) {
  539. if (c == nullptr) {
  540. GB_ASSERT(operand->mode == Addressing_Value);
  541. GB_ASSERT(is_type_typed(operand->type));
  542. }
  543. if (operand->mode == Addressing_Invalid ||
  544. type == t_invalid) {
  545. return -1;
  546. }
  547. if (operand->mode == Addressing_Builtin) {
  548. return -1;
  549. }
  550. if (operand->mode == Addressing_Type) {
  551. if (is_type_typeid(type)) {
  552. if (is_type_polymorphic(operand->type)) {
  553. return -1;
  554. }
  555. add_type_info_type(c, operand->type);
  556. return 4;
  557. }
  558. return -1;
  559. }
  560. if (operand->mode == Addressing_ProcGroup && !is_type_proc(type)) {
  561. return -1;
  562. }
  563. Type *s = operand->type;
  564. if (are_types_identical(s, type)) {
  565. return 0;
  566. }
  567. Type *src = base_type(s);
  568. Type *dst = base_type(type);
  569. if (is_type_untyped_uninit(src)) {
  570. return 1;
  571. }
  572. if (is_type_untyped_nil(src)) {
  573. if (type_has_nil(dst)) {
  574. return 1;
  575. }
  576. return -1;
  577. }
  578. if (is_type_untyped(src)) {
  579. if (is_type_any(dst)) {
  580. // NOTE(bill): Anything can cast to 'Any'
  581. add_type_info_type(c, s);
  582. return MAXIMUM_TYPE_DISTANCE;
  583. }
  584. if (dst->kind == Type_Basic) {
  585. if (operand->mode == Addressing_Constant) {
  586. if (check_representable_as_constant(c, operand->value, dst, nullptr)) {
  587. if (is_type_typed(dst) && src->kind == Type_Basic) {
  588. switch (src->Basic.kind) {
  589. case Basic_UntypedBool:
  590. if (is_type_boolean(dst)) {
  591. return 1;
  592. }
  593. break;
  594. case Basic_UntypedRune:
  595. if (is_type_integer(dst) || is_type_rune(dst)) {
  596. return 1;
  597. }
  598. break;
  599. case Basic_UntypedInteger:
  600. if (is_type_integer(dst) || is_type_rune(dst)) {
  601. return 1;
  602. }
  603. break;
  604. case Basic_UntypedString:
  605. if (is_type_string(dst)) {
  606. return 1;
  607. }
  608. break;
  609. case Basic_UntypedFloat:
  610. if (is_type_float(dst)) {
  611. return 1;
  612. }
  613. break;
  614. case Basic_UntypedComplex:
  615. if (is_type_complex(dst)) {
  616. return 1;
  617. }
  618. if (is_type_quaternion(dst)) {
  619. return 2;
  620. }
  621. break;
  622. case Basic_UntypedQuaternion:
  623. if (is_type_quaternion(dst)) {
  624. return 1;
  625. }
  626. break;
  627. }
  628. }
  629. return 2;
  630. }
  631. return -1;
  632. }
  633. if (src->kind == Type_Basic) {
  634. Type *d = base_array_type(dst);
  635. i64 score = -1;
  636. switch (src->Basic.kind) {
  637. case Basic_UntypedBool:
  638. if (is_type_boolean(d)) {
  639. score = 1;
  640. }
  641. break;
  642. case Basic_UntypedRune:
  643. if (is_type_integer(d) || is_type_rune(d)) {
  644. score = 1;
  645. }
  646. break;
  647. case Basic_UntypedInteger:
  648. if (is_type_integer(d) || is_type_rune(d)) {
  649. score = 1;
  650. }
  651. break;
  652. case Basic_UntypedString:
  653. if (is_type_string(d)) {
  654. score = 1;
  655. }
  656. break;
  657. case Basic_UntypedFloat:
  658. if (is_type_float(d)) {
  659. score = 1;
  660. }
  661. break;
  662. case Basic_UntypedComplex:
  663. if (is_type_complex(d)) {
  664. score = 1;
  665. }
  666. if (is_type_quaternion(d)) {
  667. score = 2;
  668. }
  669. break;
  670. case Basic_UntypedQuaternion:
  671. if (is_type_quaternion(d)) {
  672. score = 1;
  673. }
  674. break;
  675. }
  676. if (score > 0) {
  677. if (is_type_typed(d)) {
  678. score += 1;
  679. }
  680. if (d != dst) {
  681. score += 6;
  682. }
  683. }
  684. return score;
  685. }
  686. }
  687. }
  688. if (is_type_enum(dst) && are_types_identical(dst->Enum.base_type, operand->type)) {
  689. if (c->in_enum_type) {
  690. return 3;
  691. }
  692. }
  693. {
  694. isize subtype_level = check_is_assignable_to_using_subtype(operand->type, type);
  695. if (subtype_level > 0) {
  696. return 4 + subtype_level;
  697. }
  698. }
  699. // rawptr <- ^T
  700. if (are_types_identical(type, t_rawptr) && is_type_pointer(src)) {
  701. return 5;
  702. }
  703. // rawptr <- [^]T
  704. if (are_types_identical(type, t_rawptr) && is_type_multi_pointer(src)) {
  705. return 5;
  706. }
  707. // ^T <- [^]T
  708. if (dst->kind == Type_Pointer && src->kind == Type_MultiPointer) {
  709. if (are_types_identical(dst->Pointer.elem, src->MultiPointer.elem)) {
  710. return 4;
  711. }
  712. }
  713. // [^]T <- ^T
  714. if (dst->kind == Type_MultiPointer && src->kind == Type_Pointer) {
  715. if (are_types_identical(dst->MultiPointer.elem, src->Pointer.elem)) {
  716. return 4;
  717. }
  718. }
  719. if (is_type_polymorphic(dst) && !is_type_polymorphic(src)) {
  720. bool modify_type = !c->no_polymorphic_errors;
  721. if (is_polymorphic_type_assignable(c, type, s, false, modify_type)) {
  722. return 2;
  723. }
  724. }
  725. if (is_type_union(dst)) {
  726. for (Type *vt : dst->Union.variants) {
  727. if (are_types_identical(vt, s)) {
  728. return 1;
  729. }
  730. if (is_type_proc(vt)) {
  731. if (are_types_identical(base_type(vt), src)) {
  732. return 1;
  733. }
  734. }
  735. }
  736. if (dst->Union.variants.count == 1) {
  737. Type *vt = dst->Union.variants[0];
  738. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  739. if (score >= 0) {
  740. return score+2;
  741. }
  742. } else if (is_type_untyped(src)) {
  743. i64 prev_lowest_score = -1;
  744. i64 lowest_score = -1;
  745. for (Type *vt : dst->Union.variants) {
  746. i64 score = check_distance_between_types(c, operand, vt, allow_array_programming);
  747. if (score >= 0) {
  748. if (lowest_score < 0) {
  749. lowest_score = score;
  750. } else {
  751. if (prev_lowest_score < 0) {
  752. prev_lowest_score = lowest_score;
  753. } else {
  754. prev_lowest_score = gb_min(prev_lowest_score, lowest_score);
  755. }
  756. lowest_score = gb_min(lowest_score, score);
  757. }
  758. }
  759. }
  760. if (lowest_score >= 0) {
  761. if (prev_lowest_score != lowest_score) { // remove possible ambiguities
  762. return lowest_score+2;
  763. }
  764. }
  765. }
  766. }
  767. if (is_type_proc(dst)) {
  768. if (are_types_identical(src, dst)) {
  769. return 3;
  770. }
  771. PolyProcData poly_proc_data = {};
  772. if (check_polymorphic_procedure_assignment(c, operand, type, operand->expr, &poly_proc_data)) {
  773. Entity *e = poly_proc_data.gen_entity;
  774. add_type_and_value(c, operand->expr, Addressing_Value, e->type, {});
  775. add_entity_use(c, operand->expr, e);
  776. return 4;
  777. }
  778. }
  779. if (is_type_complex_or_quaternion(dst)) {
  780. Type *elem = base_complex_elem_type(dst);
  781. if (are_types_identical(elem, base_type(src))) {
  782. return 5;
  783. }
  784. }
  785. if (allow_array_programming) {
  786. if (is_type_array(dst)) {
  787. Type *elem = base_array_type(dst);
  788. i64 distance = check_distance_between_types(c, operand, elem, allow_array_programming);
  789. if (distance >= 0) {
  790. return distance + 6;
  791. }
  792. }
  793. if (is_type_simd_vector(dst)) {
  794. Type *dst_elem = base_array_type(dst);
  795. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  796. if (distance >= 0) {
  797. return distance + 6;
  798. }
  799. }
  800. }
  801. if (is_type_matrix(dst)) {
  802. if (are_types_identical(src, dst)) {
  803. return 5;
  804. }
  805. if (dst->Matrix.row_count == dst->Matrix.column_count) {
  806. Type *dst_elem = base_array_type(dst);
  807. i64 distance = check_distance_between_types(c, operand, dst_elem, allow_array_programming);
  808. if (distance >= 0) {
  809. return distance + 7;
  810. }
  811. }
  812. }
  813. if (is_type_any(dst)) {
  814. if (!is_type_polymorphic(src)) {
  815. if (operand->mode == Addressing_Context && operand->type == t_context) {
  816. return -1;
  817. } else {
  818. // NOTE(bill): Anything can cast to 'Any'
  819. add_type_info_type(c, s);
  820. return MAXIMUM_TYPE_DISTANCE;
  821. }
  822. }
  823. }
  824. Ast *expr = unparen_expr(operand->expr);
  825. if (expr != nullptr) {
  826. if (expr->kind == Ast_AutoCast) {
  827. Operand x = *operand;
  828. x.expr = expr->AutoCast.expr;
  829. if (check_cast_internal(c, &x, type)) {
  830. return MAXIMUM_TYPE_DISTANCE;
  831. }
  832. }
  833. }
  834. return -1;
  835. }
  836. gb_internal i64 assign_score_function(i64 distance, bool is_variadic=false) {
  837. // 3*x^2 + 1 > x^2 + x + 1 (for positive x)
  838. i64 const c = 3*MAXIMUM_TYPE_DISTANCE*MAXIMUM_TYPE_DISTANCE + 1;
  839. // TODO(bill): A decent score function
  840. i64 d = distance*distance; // x^2
  841. if (is_variadic && d >= 0) {
  842. d += distance + 1; // x^2 + x + 1
  843. }
  844. return gb_max(c - d, 0);
  845. }
  846. 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) {
  847. if (c == nullptr) {
  848. GB_ASSERT(operand->mode == Addressing_Value);
  849. GB_ASSERT(is_type_typed(operand->type));
  850. }
  851. if (operand->mode == Addressing_Invalid || type == t_invalid) {
  852. if (score_) *score_ = 0;
  853. return false;
  854. }
  855. // Handle polymorphic procedure used as default parameter
  856. if (operand->mode == Addressing_Value && is_type_proc(type) && is_type_proc(operand->type)) {
  857. Entity *e = entity_from_expr(operand->expr);
  858. if (e != nullptr && e->kind == Entity_Procedure && is_type_polymorphic(e->type) && !is_type_polymorphic(type)) {
  859. // Special case: Allow a polymorphic procedure to be used as default value for concrete proc type
  860. // during the initial check. It will be properly instantiated when actually used.
  861. if (score_) *score_ = assign_score_function(1);
  862. return true;
  863. }
  864. }
  865. i64 score = check_distance_between_types(c, operand, type, allow_array_programming);
  866. if (score >= 0) {
  867. if (score_) *score_ = assign_score_function(score, is_variadic);
  868. return true;
  869. }
  870. if (score_) *score_ = 0;
  871. return false;
  872. }
  873. gb_internal bool check_is_assignable_to(CheckerContext *c, Operand *operand, Type *type, bool allow_array_programming=true) {
  874. i64 score = 0;
  875. return check_is_assignable_to_with_score(c, operand, type, &score, /*is_variadic*/false, allow_array_programming);
  876. }
  877. gb_internal bool internal_check_is_assignable_to(Type *src, Type *dst) {
  878. Operand x = {};
  879. x.type = src;
  880. x.mode = Addressing_Value;
  881. return check_is_assignable_to(nullptr, &x, dst);
  882. }
  883. gb_internal AstPackage *get_package_of_type(Type *type) {
  884. for (;;) {
  885. if (type == nullptr) {
  886. return nullptr;
  887. }
  888. switch (type->kind) {
  889. case Type_Basic:
  890. return builtin_pkg;
  891. case Type_Named:
  892. if (type->Named.type_name != nullptr) {
  893. return type->Named.type_name->pkg;
  894. }
  895. return nullptr;
  896. case Type_Pointer:
  897. type = type->Pointer.elem;
  898. continue;
  899. case Type_Array:
  900. type = type->Array.elem;
  901. continue;
  902. case Type_Slice:
  903. type = type->Slice.elem;
  904. continue;
  905. case Type_DynamicArray:
  906. type = type->DynamicArray.elem;
  907. continue;
  908. }
  909. return nullptr;
  910. }
  911. }
  912. // NOTE(bill): 'context_name' is for debugging and error messages
  913. gb_internal void check_assignment(CheckerContext *c, Operand *operand, Type *type, String context_name) {
  914. check_not_tuple(c, operand);
  915. if (operand->mode == Addressing_Invalid) {
  916. return;
  917. }
  918. // Grab definite or indefinite article matching `context_name`, or "" if not found.
  919. String article = error_article(context_name);
  920. if (is_type_untyped(operand->type)) {
  921. Type *target_type = type;
  922. if (type == nullptr || is_type_any(type)) {
  923. if (type == nullptr && is_type_untyped_uninit(operand->type)) {
  924. error(operand->expr, "Use of --- in %.*s%.*s", LIT(article), LIT(context_name));
  925. operand->mode = Addressing_Invalid;
  926. return;
  927. }
  928. if (type == nullptr && is_type_untyped_nil(operand->type)) {
  929. error(operand->expr, "Use of untyped nil in %.*s%.*s", LIT(article), LIT(context_name));
  930. operand->mode = Addressing_Invalid;
  931. return;
  932. }
  933. target_type = default_type(operand->type);
  934. if (type != nullptr && !is_type_any(type)) {
  935. GB_ASSERT_MSG(is_type_typed(target_type), "%s", type_to_string(type));
  936. }
  937. add_type_info_type(c, type);
  938. add_type_info_type(c, target_type);
  939. }
  940. convert_to_typed(c, operand, target_type);
  941. if (operand->mode == Addressing_Invalid) {
  942. return;
  943. }
  944. }
  945. if (type == nullptr) {
  946. return;
  947. }
  948. if (operand->mode == Addressing_ProcGroup) {
  949. bool good = false;
  950. if (type != nullptr && is_type_proc(type)) {
  951. Array<Entity *> procs = proc_group_entities(c, *operand);
  952. // NOTE(bill): These should be done
  953. for (Entity *e : procs) {
  954. Type *t = base_type(e->type);
  955. if (t == t_invalid) {
  956. continue;
  957. }
  958. Operand x = {};
  959. x.mode = Addressing_Value;
  960. x.type = t;
  961. if (check_is_assignable_to(c, &x, type)) {
  962. add_entity_use(c, operand->expr, e);
  963. good = true;
  964. break;
  965. }
  966. }
  967. }
  968. if (!good) {
  969. gbString expr_str = expr_to_string(operand->expr);
  970. gbString op_type_str = type_to_string(operand->type);
  971. gbString type_str = type_to_string(type);
  972. defer (gb_string_free(type_str));
  973. defer (gb_string_free(op_type_str));
  974. defer (gb_string_free(expr_str));
  975. // TODO(bill): is this a good enough error message?
  976. error(operand->expr,
  977. "Cannot assign overloaded procedure group '%s' to '%s' in %.*s%.*s",
  978. expr_str,
  979. op_type_str,
  980. LIT(article),
  981. LIT(context_name));
  982. operand->mode = Addressing_Invalid;
  983. }
  984. convert_to_typed(c, operand, type);
  985. return;
  986. }
  987. if (check_is_assignable_to(c, operand, type)) {
  988. if (operand->mode == Addressing_Type && is_type_typeid(type)) {
  989. add_type_info_type(c, operand->type);
  990. add_type_and_value(c, operand->expr, Addressing_Value, type, exact_value_typeid(operand->type));
  991. }
  992. } else {
  993. gbString expr_str = expr_to_string(operand->expr);
  994. gbString op_type_str = type_to_string(operand->type);
  995. gbString type_str = type_to_string(type);
  996. defer (gb_string_free(type_str));
  997. defer (gb_string_free(op_type_str));
  998. defer (gb_string_free(expr_str));
  999. switch (operand->mode) {
  1000. case Addressing_Builtin:
  1001. error(operand->expr,
  1002. "Cannot assign built-in procedure '%s' to %.*s%.*s",
  1003. expr_str,
  1004. LIT(article),
  1005. LIT(context_name));
  1006. break;
  1007. case Addressing_Type:
  1008. if (is_type_polymorphic(operand->type)) {
  1009. error(operand->expr,
  1010. "Cannot assign '%s', a polymorphic type, to %.*s%.*s",
  1011. op_type_str,
  1012. LIT(article),
  1013. LIT(context_name));
  1014. } else {
  1015. ERROR_BLOCK();
  1016. error(operand->expr,
  1017. "Cannot assign '%s', a type, to %.*s%.*s",
  1018. op_type_str,
  1019. LIT(article),
  1020. LIT(context_name));
  1021. if (type && are_types_identical(type, t_any)) {
  1022. error_line("\tSuggestion: 'typeid_of(%s)'", expr_str);
  1023. }
  1024. }
  1025. break;
  1026. default:
  1027. // TODO(bill): is this a good enough error message?
  1028. {
  1029. gbString op_type_extra = gb_string_make(heap_allocator(), "");
  1030. gbString type_extra = gb_string_make(heap_allocator(), "");
  1031. defer (gb_string_free(op_type_extra));
  1032. defer (gb_string_free(type_extra));
  1033. isize on = gb_string_length(op_type_str);
  1034. isize tn = gb_string_length(type_str);
  1035. if (on == tn && gb_strncmp(op_type_str, type_str, on) == 0) {
  1036. AstPackage *op_pkg = get_package_of_type(operand->type);
  1037. AstPackage *type_pkg = get_package_of_type(type);
  1038. if (op_pkg != nullptr) {
  1039. op_type_extra = gb_string_append_fmt(op_type_extra, " (package %.*s)", LIT(op_pkg->name));
  1040. }
  1041. if (type_pkg != nullptr) {
  1042. type_extra = gb_string_append_fmt(type_extra, " (package %.*s)", LIT(type_pkg->name));
  1043. }
  1044. }
  1045. ERROR_BLOCK();
  1046. error(operand->expr,
  1047. "Cannot assign value '%s' of type '%s%s' to '%s%s' in %.*s%.*s",
  1048. expr_str,
  1049. op_type_str, op_type_extra,
  1050. type_str, type_extra,
  1051. LIT(article),
  1052. LIT(context_name));
  1053. check_assignment_error_suggestion(c, operand, type);
  1054. Type *src = base_type(operand->type);
  1055. Type *dst = base_type(type);
  1056. if (context_name == "procedure argument") {
  1057. if (is_type_slice(src) && are_types_identical(src->Slice.elem, dst)) {
  1058. gbString a = expr_to_string(operand->expr);
  1059. error_line("\tSuggestion: Did you mean to pass the slice into the variadic parameter with ..%s?\n\n", a);
  1060. gb_string_free(a);
  1061. }
  1062. }
  1063. if (src->kind == dst->kind && src->kind == Type_Proc) {
  1064. Type *x = src;
  1065. Type *y = dst;
  1066. bool same_inputs = are_types_identical_internal(x->Proc.params, y->Proc.params, false);
  1067. bool same_outputs = are_types_identical_internal(x->Proc.results, y->Proc.results, false);
  1068. if (same_inputs && same_outputs &&
  1069. x->Proc.calling_convention != y->Proc.calling_convention) {
  1070. gbString s_expected = type_to_string(y);
  1071. gbString s_got = type_to_string(x);
  1072. error_line("\tNote: The calling conventions differ between the procedure signature types\n");
  1073. error_line("\t Expected \"%s\", got \"%s\"\n",
  1074. proc_calling_convention_strings[y->Proc.calling_convention],
  1075. proc_calling_convention_strings[x->Proc.calling_convention]);
  1076. error_line("\t Expected: %s\n", s_expected);
  1077. error_line("\t Got: %s\n", s_got);
  1078. gb_string_free(s_got);
  1079. gb_string_free(s_expected);
  1080. } else if (same_inputs && same_outputs &&
  1081. x->Proc.diverging != y->Proc.diverging) {
  1082. gbString s_expected = type_to_string(y);
  1083. if (y->Proc.diverging) {
  1084. s_expected = gb_string_appendc(s_expected, " -> !");
  1085. }
  1086. gbString s_got = type_to_string(x);
  1087. if (x->Proc.diverging) {
  1088. s_got = gb_string_appendc(s_got, " -> !");
  1089. }
  1090. error_line("\tNote: One of the procedures is diverging while the other isn't\n");
  1091. error_line("\t Expected: %s\n", s_expected);
  1092. error_line("\t Got: %s\n", s_got);
  1093. gb_string_free(s_got);
  1094. gb_string_free(s_expected);
  1095. } else if (same_inputs && !same_outputs) {
  1096. gbString s_expected = type_to_string(y->Proc.results);
  1097. gbString s_got = type_to_string(x->Proc.results);
  1098. error_line("\tNote: The return types differ between the procedure signature types\n");
  1099. error_line("\t Expected: %s\n", s_expected);
  1100. error_line("\t Got: %s\n", s_got);
  1101. gb_string_free(s_got);
  1102. gb_string_free(s_expected);
  1103. } else if (!same_inputs && same_outputs) {
  1104. gbString s_expected = type_to_string(y->Proc.params);
  1105. gbString s_got = type_to_string(x->Proc.params);
  1106. error_line("\tNote: The input parameter types differ between the procedure signature types\n");
  1107. error_line("\t Expected: %s\n", s_expected);
  1108. error_line("\t Got: %s\n", s_got);
  1109. gb_string_free(s_got);
  1110. gb_string_free(s_expected);
  1111. } else {
  1112. gbString s_expected = type_to_string(y);
  1113. gbString s_got = type_to_string(x);
  1114. error_line("\tNote: The signature type do not match whatsoever\n");
  1115. error_line("\t Expected: %s\n", s_expected);
  1116. error_line("\t Got: %s\n", s_got);
  1117. gb_string_free(s_got);
  1118. gb_string_free(s_expected);
  1119. }
  1120. }
  1121. }
  1122. break;
  1123. }
  1124. operand->mode = Addressing_Invalid;
  1125. return;
  1126. }
  1127. }
  1128. gb_internal bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) {
  1129. Type *gt = *gt_;
  1130. GB_ASSERT(gt->kind == Type_Generic);
  1131. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1132. GB_ASSERT(e != nullptr);
  1133. if (e->kind == Entity_TypeName) {
  1134. *gt_ = nullptr;
  1135. *dst_count = source_count;
  1136. e->kind = Entity_Constant;
  1137. e->Constant.value = exact_value_i64(source_count);
  1138. e->type = t_untyped_integer;
  1139. return true;
  1140. } else if (e->kind == Entity_Constant) {
  1141. *gt_ = nullptr;
  1142. if (e->Constant.value.kind != ExactValue_Integer) {
  1143. return false;
  1144. }
  1145. i64 count = big_int_to_i64(&e->Constant.value.value_integer);
  1146. if (count != source_count) {
  1147. return false;
  1148. }
  1149. *dst_count = source_count;
  1150. return true;
  1151. }
  1152. return false;
  1153. }
  1154. gb_internal bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) {
  1155. Operand o = {Addressing_Value};
  1156. o.type = source;
  1157. switch (poly->kind) {
  1158. case Type_Basic:
  1159. if (compound) return are_types_identical(poly, source);
  1160. return check_is_assignable_to(c, &o, poly);
  1161. case Type_Named: {
  1162. if (check_type_specialization_to(c, poly, source, compound, modify_type)) {
  1163. return true;
  1164. }
  1165. if (compound || !is_type_generic(poly)) {
  1166. return are_types_identical(poly, source);
  1167. }
  1168. return check_is_assignable_to(c, &o, poly);
  1169. }
  1170. case Type_Generic: {
  1171. if (poly->Generic.specialized != nullptr) {
  1172. Type *s = poly->Generic.specialized;
  1173. if (!check_type_specialization_to(c, s, source, compound, modify_type)) {
  1174. return false;
  1175. }
  1176. }
  1177. if (modify_type) {
  1178. Type *ds = default_type(source);
  1179. gb_memmove(poly, ds, gb_size_of(Type));
  1180. }
  1181. return true;
  1182. }
  1183. case Type_Pointer:
  1184. if (source->kind == Type_Pointer) {
  1185. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->Pointer.elem, /*level*/0, /*src_is_ptr*/false, /*allow_polymorphic*/true);
  1186. if (level > 0) {
  1187. return true;
  1188. }
  1189. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->Pointer.elem, true, modify_type);
  1190. } else if (source->kind == Type_MultiPointer) {
  1191. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->Pointer.elem);
  1192. if (level > 0) {
  1193. return true;
  1194. }
  1195. return is_polymorphic_type_assignable(c, poly->Pointer.elem, source->MultiPointer.elem, true, modify_type);
  1196. }
  1197. return false;
  1198. case Type_MultiPointer:
  1199. if (source->kind == Type_MultiPointer) {
  1200. isize level = check_is_assignable_to_using_subtype(source->MultiPointer.elem, poly->MultiPointer.elem);
  1201. if (level > 0) {
  1202. return true;
  1203. }
  1204. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->MultiPointer.elem, true, modify_type);
  1205. } else if (source->kind == Type_Pointer) {
  1206. isize level = check_is_assignable_to_using_subtype(source->Pointer.elem, poly->MultiPointer.elem);
  1207. if (level > 0) {
  1208. return true;
  1209. }
  1210. return is_polymorphic_type_assignable(c, poly->MultiPointer.elem, source->Pointer.elem, true, modify_type);
  1211. }
  1212. return false;
  1213. case Type_Array:
  1214. if (source->kind == Type_Array) {
  1215. if (poly->Array.generic_count != nullptr) {
  1216. if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) {
  1217. return false;
  1218. }
  1219. }
  1220. if (poly->Array.count == source->Array.count) {
  1221. return is_polymorphic_type_assignable(c, poly->Array.elem, source->Array.elem, true, modify_type);
  1222. }
  1223. } else if (source->kind == Type_EnumeratedArray) {
  1224. if (poly->Array.generic_count != nullptr) {
  1225. Type *gt = poly->Array.generic_count;
  1226. GB_ASSERT(gt->kind == Type_Generic);
  1227. Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name);
  1228. GB_ASSERT(e != nullptr);
  1229. if (e->kind == Entity_TypeName) {
  1230. Type *index = source->EnumeratedArray.index;
  1231. Type *it = base_type(index);
  1232. if (it->kind != Type_Enum) {
  1233. return false;
  1234. }
  1235. poly->kind = Type_EnumeratedArray;
  1236. poly->cached_size = -1;
  1237. poly->cached_align = -1;
  1238. poly->flags.exchange(source->flags);
  1239. poly->failure = false;
  1240. poly->EnumeratedArray.elem = source->EnumeratedArray.elem;
  1241. poly->EnumeratedArray.index = source->EnumeratedArray.index;
  1242. poly->EnumeratedArray.min_value = source->EnumeratedArray.min_value;
  1243. poly->EnumeratedArray.max_value = source->EnumeratedArray.max_value;
  1244. poly->EnumeratedArray.count = source->EnumeratedArray.count;
  1245. poly->EnumeratedArray.op = source->EnumeratedArray.op;
  1246. e->kind = Entity_TypeName;
  1247. e->TypeName.is_type_alias = true;
  1248. e->type = index;
  1249. if (poly->EnumeratedArray.count == source->EnumeratedArray.count) {
  1250. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1251. }
  1252. }
  1253. }
  1254. }
  1255. return false;
  1256. case Type_EnumeratedArray:
  1257. if (source->kind == Type_EnumeratedArray) {
  1258. if (poly->EnumeratedArray.op != source->EnumeratedArray.op) {
  1259. return false;
  1260. }
  1261. if (poly->EnumeratedArray.op) {
  1262. if (poly->EnumeratedArray.count != source->EnumeratedArray.count) {
  1263. return false;
  1264. }
  1265. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.min_value, *source->EnumeratedArray.min_value)) {
  1266. return false;
  1267. }
  1268. if (compare_exact_values(Token_NotEq, *poly->EnumeratedArray.max_value, *source->EnumeratedArray.max_value)) {
  1269. return false;
  1270. }
  1271. return is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1272. }
  1273. bool index = is_polymorphic_type_assignable(c, poly->EnumeratedArray.index, source->EnumeratedArray.index, true, modify_type);
  1274. bool elem = is_polymorphic_type_assignable(c, poly->EnumeratedArray.elem, source->EnumeratedArray.elem, true, modify_type);
  1275. return index || elem;
  1276. }
  1277. return false;
  1278. case Type_DynamicArray:
  1279. if (source->kind == Type_DynamicArray) {
  1280. return is_polymorphic_type_assignable(c, poly->DynamicArray.elem, source->DynamicArray.elem, true, modify_type);
  1281. }
  1282. return false;
  1283. case Type_Slice:
  1284. if (source->kind == Type_Slice) {
  1285. return is_polymorphic_type_assignable(c, poly->Slice.elem, source->Slice.elem, true, modify_type);
  1286. }
  1287. return false;
  1288. case Type_Enum:
  1289. return false;
  1290. case Type_BitSet:
  1291. if (source->kind == Type_BitSet) {
  1292. if (!is_polymorphic_type_assignable(c, poly->BitSet.elem, source->BitSet.elem, true, modify_type)) {
  1293. return false;
  1294. }
  1295. // For generic types like bit_set[$T] the upper and lower of the poly type will be zeroes since
  1296. // it could not figure that stuff out when the poly type was created.
  1297. if (poly->BitSet.upper == 0 && modify_type) {
  1298. poly->BitSet.upper = source->BitSet.upper;
  1299. }
  1300. if (poly->BitSet.lower == 0 && modify_type) {
  1301. poly->BitSet.lower = source->BitSet.lower;
  1302. }
  1303. if (poly->BitSet.underlying == nullptr) {
  1304. if (modify_type) {
  1305. poly->BitSet.underlying = source->BitSet.underlying;
  1306. }
  1307. } else if (!is_polymorphic_type_assignable(c, poly->BitSet.underlying, source->BitSet.underlying, true, modify_type)) {
  1308. return false;
  1309. }
  1310. return true;
  1311. }
  1312. return false;
  1313. case Type_Union:
  1314. if (source->kind == Type_Union) {
  1315. TypeUnion *x = &poly->Union;
  1316. TypeUnion *y = &source->Union;
  1317. if (x->variants.count != y->variants.count) {
  1318. return false;
  1319. }
  1320. for_array(i, x->variants) {
  1321. Type *a = x->variants[i];
  1322. Type *b = y->variants[i];
  1323. bool ok = is_polymorphic_type_assignable(c, a, b, false, modify_type);
  1324. if (!ok) return false;
  1325. }
  1326. return true;
  1327. }
  1328. return false;
  1329. case Type_Struct:
  1330. if (source->kind == Type_Struct) {
  1331. if (poly->Struct.soa_kind == source->Struct.soa_kind &&
  1332. poly->Struct.soa_kind != StructSoa_None) {
  1333. bool ok = is_polymorphic_type_assignable(c, poly->Struct.soa_elem, source->Struct.soa_elem, true, modify_type);
  1334. if (ok) switch (source->Struct.soa_kind) {
  1335. case StructSoa_None:
  1336. default:
  1337. GB_PANIC("Unhandled SOA Kind");
  1338. break;
  1339. case StructSoa_Fixed:
  1340. if (modify_type) {
  1341. Type *type = make_soa_struct_fixed(c, nullptr, poly->Struct.node, poly->Struct.soa_elem, poly->Struct.soa_count, nullptr);
  1342. gb_memmove(poly, type, gb_size_of(*type));
  1343. }
  1344. break;
  1345. case StructSoa_Slice:
  1346. if (modify_type) {
  1347. Type *type = make_soa_struct_slice(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1348. gb_memmove(poly, type, gb_size_of(*type));
  1349. }
  1350. break;
  1351. case StructSoa_Dynamic:
  1352. if (modify_type) {
  1353. Type *type = make_soa_struct_dynamic_array(c, nullptr, poly->Struct.node, poly->Struct.soa_elem);
  1354. gb_memmove(poly, type, gb_size_of(*type));
  1355. }
  1356. break;
  1357. }
  1358. return ok;
  1359. }
  1360. // NOTE(bill): Check for subtypes of
  1361. // return check_is_assignable_to(c, &o, poly); // && is_type_subtype_of_and_allow_polymorphic(o.type, poly);
  1362. }
  1363. return false;
  1364. case Type_BitField:
  1365. if (source->kind == Type_BitField) {
  1366. return is_polymorphic_type_assignable(c, poly->BitField.backing_type, source->BitField.backing_type, true, modify_type);
  1367. }
  1368. return false;
  1369. case Type_Tuple:
  1370. GB_PANIC("This should never happen");
  1371. return false;
  1372. case Type_Proc:
  1373. if (source->kind == Type_Proc) {
  1374. TypeProc *x = &poly->Proc;
  1375. TypeProc *y = &source->Proc;
  1376. if (x->calling_convention != y->calling_convention) {
  1377. return false;
  1378. }
  1379. if (x->c_vararg != y->c_vararg) {
  1380. return false;
  1381. }
  1382. if (x->variadic != y->variadic) {
  1383. return false;
  1384. }
  1385. if (x->param_count != y->param_count) {
  1386. return false;
  1387. }
  1388. if (x->result_count != y->result_count) {
  1389. return false;
  1390. }
  1391. for (isize i = 0; i < x->param_count; i++) {
  1392. Entity *a = x->params->Tuple.variables[i];
  1393. Entity *b = y->params->Tuple.variables[i];
  1394. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1395. if (!ok) return false;
  1396. }
  1397. for (isize i = 0; i < x->result_count; i++) {
  1398. Entity *a = x->results->Tuple.variables[i];
  1399. Entity *b = y->results->Tuple.variables[i];
  1400. bool ok = is_polymorphic_type_assignable(c, a->type, b->type, false, modify_type);
  1401. if (!ok) return false;
  1402. }
  1403. return true;
  1404. }
  1405. return false;
  1406. case Type_Map:
  1407. if (source->kind == Type_Map) {
  1408. bool key = is_polymorphic_type_assignable(c, poly->Map.key, source->Map.key, true, modify_type);
  1409. bool value = is_polymorphic_type_assignable(c, poly->Map.value, source->Map.value, true, modify_type);
  1410. if (key || value) {
  1411. poly->Map.lookup_result_type = nullptr;
  1412. init_map_internal_types(poly);
  1413. return true;
  1414. }
  1415. }
  1416. return false;
  1417. case Type_Matrix:
  1418. if (source->kind == Type_Matrix) {
  1419. if (poly->Matrix.generic_row_count != nullptr) {
  1420. poly->Matrix.stride_in_bytes = 0;
  1421. if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) {
  1422. return false;
  1423. }
  1424. }
  1425. if (poly->Matrix.generic_column_count != nullptr) {
  1426. poly->Matrix.stride_in_bytes = 0;
  1427. if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) {
  1428. return false;
  1429. }
  1430. }
  1431. if (poly->Matrix.row_count == source->Matrix.row_count &&
  1432. poly->Matrix.column_count == source->Matrix.column_count) {
  1433. return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type);
  1434. }
  1435. }
  1436. return false;
  1437. case Type_SimdVector:
  1438. if (source->kind == Type_SimdVector) {
  1439. if (poly->SimdVector.generic_count != nullptr) {
  1440. if (!polymorphic_assign_index(&poly->SimdVector.generic_count, &poly->SimdVector.count, source->SimdVector.count)) {
  1441. return false;
  1442. }
  1443. }
  1444. if (poly->SimdVector.count == source->SimdVector.count) {
  1445. return is_polymorphic_type_assignable(c, poly->SimdVector.elem, source->SimdVector.elem, true, modify_type);
  1446. }
  1447. }
  1448. return false;
  1449. }
  1450. return false;
  1451. }
  1452. gb_internal bool check_cycle(CheckerContext *c, Entity *curr, bool report) {
  1453. if (curr->state != EntityState_InProgress) {
  1454. return false;
  1455. }
  1456. for_array(i, *c->type_path) {
  1457. Entity *prev = c->type_path->data[i];
  1458. if (prev == curr) {
  1459. if (report) {
  1460. error(curr->token, "Illegal declaration cycle of `%.*s`", LIT(curr->token.string));
  1461. for (isize j = i; j < c->type_path->count; j++) {
  1462. Entity *curr = (*c->type_path)[j];
  1463. error(curr->token, "\t%.*s refers to", LIT(curr->token.string));
  1464. }
  1465. error(curr->token, "\t%.*s", LIT(curr->token.string));
  1466. curr->type = t_invalid;
  1467. }
  1468. return true;
  1469. }
  1470. }
  1471. return false;
  1472. }
  1473. struct CIdentSuggestion {
  1474. String name;
  1475. String msg;
  1476. };
  1477. // NOTE(bill): this linear look-up table might be slow but because it's an error case, it should be fine
  1478. gb_internal CIdentSuggestion const c_ident_suggestions[] = {
  1479. {str_lit("while"), str_lit("'for'? Odin only has one loop construct: 'for'")},
  1480. {str_lit("sizeof"), str_lit("'size_of'?")},
  1481. {str_lit("alignof"), str_lit("'align_of'?")},
  1482. {str_lit("offsetof"), str_lit("'offset_of'?")},
  1483. {str_lit("_Bool"), str_lit("'bool'?")},
  1484. {str_lit("char"), str_lit("'u8', 'i8', or 'c.char' (which is part of 'core:c')?")},
  1485. {str_lit("short"), str_lit("'i16' or 'c.short' (which is part of 'core:c')?")},
  1486. {str_lit("long"), str_lit("'c.long' (which is part of 'core:c')?")},
  1487. {str_lit("float"), str_lit("'f32'?")},
  1488. {str_lit("double"), str_lit("'f64'?")},
  1489. {str_lit("unsigned"), str_lit("'c.uint' (which is part of 'core:c')?")},
  1490. {str_lit("signed"), str_lit("'c.int' (which is part of 'core:c')?")},
  1491. {str_lit("size_t"), str_lit("'uint', or 'c.size_t' (which is part of 'core:c')?")},
  1492. {str_lit("ssize_t"), str_lit("'int', or 'c.ssize_t' (which is part of 'core:c')?")},
  1493. {str_lit("uintptr_t"), str_lit("'uintptr'?")},
  1494. {str_lit("intptr_t"), str_lit("'uintptr' or `int` or something else?")},
  1495. {str_lit("ptrdiff_t"), str_lit("'int' or 'c.ptrdiff_t' (which is part of 'core:c')?")},
  1496. {str_lit("intmax_t"), str_lit("'c.intmax_t' (which is part of 'core:c')?")},
  1497. {str_lit("uintmax_t"), str_lit("'c.uintmax_t' (which is part of 'core:c')?")},
  1498. {str_lit("uint8_t"), str_lit("'u8'?")},
  1499. {str_lit("int8_t"), str_lit("'i8'?")},
  1500. {str_lit("uint16_t"), str_lit("'u16'?")},
  1501. {str_lit("int16_t"), str_lit("'i16'?")},
  1502. {str_lit("uint32_t"), str_lit("'u32'?")},
  1503. {str_lit("int32_t"), str_lit("'i32'?")},
  1504. {str_lit("uint64_t"), str_lit("'u64'?")},
  1505. {str_lit("int64_t"), str_lit("'i64'?")},
  1506. {str_lit("uint128_t"), str_lit("'u128'?")},
  1507. {str_lit("int128_t"), str_lit("'i128'?")},
  1508. {str_lit("float32"), str_lit("'f32'?")},
  1509. {str_lit("float64"), str_lit("'f64'?")},
  1510. {str_lit("float32_t"), str_lit("'f32'?")},
  1511. {str_lit("float64_t"), str_lit("'f64'?")},
  1512. };
  1513. gb_internal Entity *check_ident(CheckerContext *c, Operand *o, Ast *n, Type *named_type, Type *type_hint, bool allow_import_name) {
  1514. GB_ASSERT(n->kind == Ast_Ident);
  1515. o->mode = Addressing_Invalid;
  1516. o->expr = n;
  1517. String name = n->Ident.token.string;
  1518. Entity *e = scope_lookup(c->scope, name);
  1519. if (e == nullptr) {
  1520. if (is_blank_ident(name)) {
  1521. error(n, "'_' cannot be used as a value");
  1522. } else {
  1523. ERROR_BLOCK();
  1524. error(n, "Undeclared name: %.*s", LIT(name));
  1525. // NOTE(bill): Loads of checks for C programmers
  1526. for (CIdentSuggestion const &suggestion : c_ident_suggestions) {
  1527. if (name == suggestion.name) {
  1528. error_line("\tSuggestion: Did you mean %.*s\n", LIT(suggestion.msg));
  1529. }
  1530. }
  1531. }
  1532. o->type = t_invalid;
  1533. o->mode = Addressing_Invalid;
  1534. if (named_type != nullptr) {
  1535. set_base_type(named_type, t_invalid);
  1536. }
  1537. return nullptr;
  1538. }
  1539. GB_ASSERT((e->flags & EntityFlag_Overridden) == 0);
  1540. if (e->parent_proc_decl != nullptr &&
  1541. e->parent_proc_decl != c->curr_proc_decl) {
  1542. if (e->kind == Entity_Variable) {
  1543. if ((e->flags & EntityFlag_Static) == 0) {
  1544. error(n, "Nested procedures do not capture its parent's variables: %.*s", LIT(name));
  1545. return nullptr;
  1546. }
  1547. } else if (e->kind == Entity_Label) {
  1548. error(n, "Nested procedures do not capture its parent's labels: %.*s", LIT(name));
  1549. return nullptr;
  1550. }
  1551. }
  1552. if (e->kind == Entity_ProcGroup) {
  1553. auto *pge = &e->ProcGroup;
  1554. DeclInfo *d = decl_info_of_entity(e);
  1555. check_entity_decl(c, e, d, nullptr);
  1556. Array<Entity *> procs = pge->entities;
  1557. bool skip = false;
  1558. if (type_hint != nullptr && is_type_proc(type_hint)) {
  1559. // NOTE(bill): These should be done
  1560. for (Entity *proc : procs) {
  1561. Type *t = base_type(proc->type);
  1562. if (t == t_invalid) {
  1563. continue;
  1564. }
  1565. Operand x = {};
  1566. x.mode = Addressing_Value;
  1567. x.type = t;
  1568. if (check_is_assignable_to(c, &x, type_hint)) {
  1569. e = proc;
  1570. add_entity_use(c, n, e);
  1571. skip = true;
  1572. break;
  1573. }
  1574. }
  1575. }
  1576. if (!skip) {
  1577. o->mode = Addressing_ProcGroup;
  1578. o->type = t_invalid;
  1579. o->proc_group = e;
  1580. return nullptr;
  1581. }
  1582. }
  1583. add_entity_use(c, n, e);
  1584. if (e->state == EntityState_Unresolved) {
  1585. check_entity_decl(c, e, nullptr, named_type);
  1586. }
  1587. if (e->type == nullptr) {
  1588. // TODO(bill): Which is correct? return or compiler_error?
  1589. // compiler_error("How did this happen? type: %s; identifier: %.*s\n", type_to_string(e->type), LIT(name));
  1590. return nullptr;
  1591. }
  1592. e->flags |= EntityFlag_Used;
  1593. Type *type = e->type;
  1594. o->type = type;
  1595. switch (e->kind) {
  1596. case Entity_Constant:
  1597. if (type == t_invalid) {
  1598. o->type = t_invalid;
  1599. return e;
  1600. }
  1601. o->value = e->Constant.value;
  1602. if (o->value.kind == ExactValue_Invalid) {
  1603. return e;
  1604. }
  1605. if (o->value.kind == ExactValue_Procedure) {
  1606. Entity *proc = strip_entity_wrapping(o->value.value_procedure);
  1607. if (proc != nullptr) {
  1608. o->mode = Addressing_Value;
  1609. o->type = proc->type;
  1610. return proc;
  1611. }
  1612. }
  1613. o->mode = Addressing_Constant;
  1614. break;
  1615. case Entity_Variable:
  1616. e->flags |= EntityFlag_Used;
  1617. if (type == t_invalid) {
  1618. o->type = t_invalid;
  1619. return e;
  1620. }
  1621. o->mode = Addressing_Variable;
  1622. if (e->flags & EntityFlag_Value) {
  1623. o->mode = Addressing_Value;
  1624. }
  1625. break;
  1626. case Entity_Procedure:
  1627. o->mode = Addressing_Value;
  1628. o->value = exact_value_procedure(n);
  1629. break;
  1630. case Entity_Builtin:
  1631. o->builtin_id = cast(BuiltinProcId)e->Builtin.id;
  1632. o->mode = Addressing_Builtin;
  1633. break;
  1634. case Entity_TypeName:
  1635. o->mode = Addressing_Type;
  1636. if (check_cycle(c, e, true)) {
  1637. o->type = t_invalid;
  1638. }
  1639. if (o->type != nullptr && o->type->kind == Type_Named && o->type->Named.type_name->TypeName.is_type_alias) {
  1640. Type *bt = base_type(o->type);
  1641. if (bt != nullptr) {
  1642. o->type = bt;
  1643. }
  1644. }
  1645. break;
  1646. case Entity_ImportName:
  1647. if (!allow_import_name) {
  1648. error(n, "Use of import name '%.*s' not in the form of 'x.y'", LIT(name));
  1649. }
  1650. return e;
  1651. case Entity_LibraryName:
  1652. if (!allow_import_name) {
  1653. error(n, "Use of library '%.*s' not in foreign block", LIT(name));
  1654. }
  1655. return e;
  1656. case Entity_Label:
  1657. o->mode = Addressing_NoValue;
  1658. break;
  1659. case Entity_Nil:
  1660. o->mode = Addressing_Value;
  1661. break;
  1662. default:
  1663. compiler_error("Unknown EntityKind %.*s", LIT(entity_strings[e->kind]));
  1664. break;
  1665. }
  1666. return e;
  1667. }
  1668. gb_internal bool check_unary_op(CheckerContext *c, Operand *o, Token op) {
  1669. if (o->type == nullptr) {
  1670. gbString str = expr_to_string(o->expr);
  1671. error(o->expr, "Expression has no value '%s'", str);
  1672. gb_string_free(str);
  1673. return false;
  1674. }
  1675. if (o->mode == Addressing_Type) {
  1676. gbString str = type_to_string(o->type);
  1677. error(o->expr, "Expected an expression for operator '%.*s', got type '%s'", LIT(op.string), str);
  1678. gb_string_free(str);
  1679. return false;
  1680. }
  1681. Type *type = base_type(core_array_type(o->type));
  1682. gbString str = nullptr;
  1683. switch (op.kind) {
  1684. case Token_Add:
  1685. case Token_Sub:
  1686. if (!is_type_numeric(type)) {
  1687. str = expr_to_string(o->expr);
  1688. error(op, "Operator '%.*s' is not allowed with '%s'", LIT(op.string), str);
  1689. gb_string_free(str);
  1690. }
  1691. break;
  1692. case Token_Xor:
  1693. if (!is_type_integer(type) && !is_type_boolean(type) && !is_type_bit_set(type)) {
  1694. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1695. }
  1696. break;
  1697. case Token_Not:
  1698. if (!is_type_boolean(type) || is_type_array_like(o->type)) {
  1699. ERROR_BLOCK();
  1700. error(op, "Operator '%.*s' is only allowed on boolean expressions", LIT(op.string));
  1701. if (is_type_integer(type)) {
  1702. str = expr_to_string(o->expr);
  1703. error_line("\tSuggestion: Did you mean to do one of the following?\n");
  1704. error_line("\t\t'%s == 0'?\n", str);
  1705. error_line("\t\tUse of the bitwise not operator '~'?\n");
  1706. gb_string_free(str);
  1707. }
  1708. } else {
  1709. o->type = t_untyped_bool;
  1710. }
  1711. break;
  1712. case Token_Mul:
  1713. {
  1714. ERROR_BLOCK();
  1715. error(op, "Operator '%.*s' is not a valid unary operator in Odin", LIT(op.string));
  1716. if (is_type_pointer(o->type)) {
  1717. str = expr_to_string(o->expr);
  1718. error_line("\tSuggestion: Did you mean '%s^'?\n", str);
  1719. o->type = type_deref(o->type);
  1720. } else if (is_type_multi_pointer(o->type)) {
  1721. str = expr_to_string(o->expr);
  1722. error_line("\tSuggestion: The value is a multi-pointer, did you mean '%s[0]'?\n", str);
  1723. o->type = type_deref(o->type, true);
  1724. }
  1725. }
  1726. break;
  1727. default:
  1728. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1729. return false;
  1730. }
  1731. return true;
  1732. }
  1733. gb_internal bool check_binary_op(CheckerContext *c, Operand *o, Token op) {
  1734. Type *main_type = o->type;
  1735. Type *type = base_type(core_array_type(main_type));
  1736. Type *ct = core_type(type);
  1737. switch (op.kind) {
  1738. case Token_Sub:
  1739. case Token_SubEq:
  1740. if (is_type_bit_set(type)) {
  1741. return true;
  1742. } else if (!is_type_numeric(type)) {
  1743. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1744. return false;
  1745. }
  1746. break;
  1747. case Token_Quo:
  1748. case Token_QuoEq:
  1749. if (is_type_matrix(main_type)) {
  1750. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1751. return false;
  1752. } else if (is_type_simd_vector(main_type) && is_type_integer(type)) {
  1753. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1754. return false;
  1755. }
  1756. /*fallthrough*/
  1757. case Token_Mul:
  1758. case Token_MulEq:
  1759. case Token_AddEq:
  1760. if (is_type_bit_set(type)) {
  1761. return true;
  1762. } else if (!is_type_numeric(type)) {
  1763. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1764. return false;
  1765. }
  1766. break;
  1767. case Token_Add:
  1768. if (is_type_string(type)) {
  1769. if (o->mode == Addressing_Constant) {
  1770. return true;
  1771. }
  1772. error(op, "String concatenation is only allowed with constant strings");
  1773. return false;
  1774. } else if (is_type_bit_set(type)) {
  1775. return true;
  1776. } else if (!is_type_numeric(type)) {
  1777. error(op, "Operator '%.*s' is only allowed with numeric expressions", LIT(op.string));
  1778. return false;
  1779. }
  1780. break;
  1781. case Token_And:
  1782. case Token_Or:
  1783. case Token_AndEq:
  1784. case Token_OrEq:
  1785. case Token_Xor:
  1786. case Token_XorEq:
  1787. if (!is_type_integer(ct) && !is_type_boolean(ct) && !is_type_bit_set(ct)) {
  1788. error(op, "Operator '%.*s' is only allowed with integers, booleans, or bit sets", LIT(op.string));
  1789. return false;
  1790. }
  1791. break;
  1792. case Token_Mod:
  1793. case Token_ModMod:
  1794. case Token_ModEq:
  1795. case Token_ModModEq:
  1796. if (is_type_matrix(main_type)) {
  1797. error(op, "Operator '%.*s' is not allowed with matrix types", LIT(op.string));
  1798. return false;
  1799. }
  1800. if (!is_type_integer(type)) {
  1801. error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string));
  1802. return false;
  1803. } else if (is_type_simd_vector(main_type)) {
  1804. error(op, "Operator '%.*s' is not allowed with #simd types with integer elements", LIT(op.string));
  1805. return false;
  1806. }
  1807. break;
  1808. case Token_AndNot:
  1809. case Token_AndNotEq:
  1810. if (!is_type_integer(ct) && !is_type_bit_set(ct)) {
  1811. error(op, "Operator '%.*s' is only allowed with integers and bit sets", LIT(op.string));
  1812. return false;
  1813. }
  1814. break;
  1815. case Token_CmpAnd:
  1816. case Token_CmpOr:
  1817. case Token_CmpAndEq:
  1818. case Token_CmpOrEq:
  1819. if (!is_type_boolean(type)) {
  1820. error(op, "Operator '%.*s' is only allowed with boolean expressions", LIT(op.string));
  1821. return false;
  1822. }
  1823. break;
  1824. default:
  1825. error(op, "Unknown operator '%.*s'", LIT(op.string));
  1826. return false;
  1827. }
  1828. return true;
  1829. }
  1830. gb_internal bool check_representable_as_constant(CheckerContext *c, ExactValue in_value, Type *type, ExactValue *out_value) {
  1831. if (in_value.kind == ExactValue_Invalid) {
  1832. // NOTE(bill): There's already been an error
  1833. return true;
  1834. }
  1835. type = core_type(type);
  1836. if (type == t_invalid) {
  1837. return false;
  1838. } else if (is_type_boolean(type)) {
  1839. return in_value.kind == ExactValue_Bool;
  1840. } else if (is_type_string(type)) {
  1841. if (in_value.kind == ExactValue_String16) {
  1842. return is_type_string16(type) || is_type_cstring16(type);
  1843. }
  1844. return in_value.kind == ExactValue_String;
  1845. } else if (is_type_integer(type) || is_type_rune(type)) {
  1846. if (in_value.kind == ExactValue_Bool) {
  1847. return false;
  1848. }
  1849. ExactValue v = exact_value_to_integer(in_value);
  1850. if (v.kind != ExactValue_Integer) {
  1851. return false;
  1852. }
  1853. if (out_value) *out_value = v;
  1854. if (is_type_untyped(type)) {
  1855. return true;
  1856. }
  1857. BigInt i = v.value_integer;
  1858. i64 byte_size = type_size_of(type);
  1859. BigInt umax = {};
  1860. BigInt imin = {};
  1861. BigInt imax = {};
  1862. if (c->bit_field_bit_size > 0) {
  1863. i64 bit_size = gb_min(cast(i64)(8*byte_size), cast(i64)c->bit_field_bit_size);
  1864. big_int_from_u64(&umax, 1);
  1865. big_int_from_i64(&imin, 1);
  1866. big_int_from_i64(&imax, 1);
  1867. BigInt bu = {};
  1868. BigInt bi = {};
  1869. big_int_from_i64(&bu, bit_size);
  1870. big_int_from_i64(&bi, bit_size-1);
  1871. big_int_shl_eq(&umax, &bu);
  1872. mp_decr(&umax);
  1873. big_int_shl_eq(&imin, &bi);
  1874. big_int_neg(&imin, &imin);
  1875. big_int_shl_eq(&imax, &bi);
  1876. mp_decr(&imax);
  1877. } else {
  1878. if (byte_size < 16) {
  1879. big_int_from_u64(&umax, unsigned_integer_maxs[byte_size]);
  1880. big_int_from_i64(&imin, signed_integer_mins[byte_size]);
  1881. big_int_from_i64(&imax, signed_integer_maxs[byte_size]);
  1882. } else {
  1883. big_int_from_u64(&umax, 1);
  1884. big_int_from_i64(&imin, 1);
  1885. big_int_from_i64(&imax, 1);
  1886. BigInt bi128 = {};
  1887. BigInt bi127 = {};
  1888. big_int_from_i64(&bi128, 128);
  1889. big_int_from_i64(&bi127, 127);
  1890. big_int_shl_eq(&umax, &bi128);
  1891. mp_decr(&umax);
  1892. big_int_shl_eq(&imin, &bi127);
  1893. big_int_neg(&imin, &imin);
  1894. big_int_shl_eq(&imax, &bi127);
  1895. mp_decr(&imax);
  1896. }
  1897. }
  1898. switch (type->Basic.kind) {
  1899. case Basic_rune:
  1900. case Basic_i8:
  1901. case Basic_i16:
  1902. case Basic_i32:
  1903. case Basic_i64:
  1904. case Basic_i128:
  1905. case Basic_int:
  1906. case Basic_i16le:
  1907. case Basic_i32le:
  1908. case Basic_i64le:
  1909. case Basic_i128le:
  1910. case Basic_i16be:
  1911. case Basic_i32be:
  1912. case Basic_i64be:
  1913. case Basic_i128be:
  1914. {
  1915. // return imin <= i && i <= imax;
  1916. int a = big_int_cmp(&imin, &i);
  1917. int b = big_int_cmp(&i, &imax);
  1918. return (a <= 0) && (b <= 0);
  1919. }
  1920. case Basic_u8:
  1921. case Basic_u16:
  1922. case Basic_u32:
  1923. case Basic_u64:
  1924. case Basic_u128:
  1925. case Basic_uint:
  1926. case Basic_uintptr:
  1927. case Basic_u16le:
  1928. case Basic_u32le:
  1929. case Basic_u64le:
  1930. case Basic_u128le:
  1931. case Basic_u16be:
  1932. case Basic_u32be:
  1933. case Basic_u64be:
  1934. case Basic_u128be:
  1935. {
  1936. // return 0ull <= i && i <= umax;
  1937. int b = big_int_cmp(&i, &umax);
  1938. return !i.sign && (b <= 0);
  1939. }
  1940. case Basic_UntypedInteger:
  1941. return true;
  1942. default: GB_PANIC("Compiler error: Unknown integer type!"); break;
  1943. }
  1944. } else if (is_type_float(type)) {
  1945. ExactValue v = exact_value_to_float(in_value);
  1946. if (v.kind != ExactValue_Float) {
  1947. return false;
  1948. }
  1949. if (out_value) *out_value = v;
  1950. switch (type->Basic.kind) {
  1951. case Basic_f16:
  1952. case Basic_f32:
  1953. case Basic_f64:
  1954. return true;
  1955. case Basic_f16le:
  1956. case Basic_f16be:
  1957. case Basic_f32le:
  1958. case Basic_f32be:
  1959. case Basic_f64le:
  1960. case Basic_f64be:
  1961. return true;
  1962. case Basic_UntypedFloat:
  1963. return true;
  1964. default: GB_PANIC("Compiler error: Unknown float type!"); break;
  1965. }
  1966. } else if (is_type_complex(type)) {
  1967. ExactValue v = exact_value_to_complex(in_value);
  1968. if (v.kind != ExactValue_Complex) {
  1969. return false;
  1970. }
  1971. switch (type->Basic.kind) {
  1972. case Basic_complex32:
  1973. case Basic_complex64:
  1974. case Basic_complex128: {
  1975. ExactValue real = exact_value_real(v);
  1976. ExactValue imag = exact_value_imag(v);
  1977. if (real.kind != ExactValue_Invalid &&
  1978. imag.kind != ExactValue_Invalid) {
  1979. if (out_value) *out_value = exact_value_complex(exact_value_to_f64(real), exact_value_to_f64(imag));
  1980. return true;
  1981. }
  1982. break;
  1983. }
  1984. case Basic_UntypedComplex:
  1985. return true;
  1986. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  1987. }
  1988. return false;
  1989. } else if (is_type_quaternion(type)) {
  1990. ExactValue v = exact_value_to_quaternion(in_value);
  1991. if (v.kind != ExactValue_Quaternion) {
  1992. return false;
  1993. }
  1994. switch (type->Basic.kind) {
  1995. case Basic_quaternion64:
  1996. case Basic_quaternion128:
  1997. case Basic_quaternion256: {
  1998. ExactValue real = exact_value_real(v);
  1999. ExactValue imag = exact_value_imag(v);
  2000. ExactValue jmag = exact_value_jmag(v);
  2001. ExactValue kmag = exact_value_kmag(v);
  2002. if (real.kind != ExactValue_Invalid &&
  2003. imag.kind != ExactValue_Invalid) {
  2004. 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));
  2005. return true;
  2006. }
  2007. break;
  2008. }
  2009. case Basic_UntypedComplex:
  2010. if (out_value) *out_value = exact_value_to_quaternion(*out_value);
  2011. return true;
  2012. case Basic_UntypedQuaternion:
  2013. return true;
  2014. default: GB_PANIC("Compiler error: Unknown complex type!"); break;
  2015. }
  2016. return false;
  2017. } else if (is_type_pointer(type)) {
  2018. if (in_value.kind == ExactValue_Pointer) {
  2019. return true;
  2020. }
  2021. if (in_value.kind == ExactValue_Integer) {
  2022. return false;
  2023. // return true;
  2024. }
  2025. if (in_value.kind == ExactValue_String) {
  2026. return false;
  2027. }
  2028. if (in_value.kind == ExactValue_String16) {
  2029. return false;
  2030. }
  2031. if (out_value) *out_value = in_value;
  2032. } else if (is_type_bit_set(type)) {
  2033. if (in_value.kind == ExactValue_Integer) {
  2034. return true;
  2035. }
  2036. }
  2037. return false;
  2038. }
  2039. gb_internal bool check_integer_exceed_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size=0) {
  2040. if (is_type_integer(type) && o->value.kind == ExactValue_Integer) {
  2041. gbString b = type_to_string(type);
  2042. defer (gb_string_free(b));
  2043. if (is_type_enum(o->type)) {
  2044. if (check_is_castable_to(c, o, type)) {
  2045. gbString ot = type_to_string(o->type);
  2046. error_line("\tSuggestion: Try casting the '%s' expression to '%s'", ot, b);
  2047. gb_string_free(ot);
  2048. }
  2049. return true;
  2050. }
  2051. i64 sz = type_size_of(type);
  2052. i64 bit_size = 8*sz;
  2053. bool size_changed = false;
  2054. if (max_bit_size > 0) {
  2055. size_changed = (bit_size != max_bit_size);
  2056. bit_size = gb_min(bit_size, max_bit_size);
  2057. }
  2058. BigInt *bi = &o->value.value_integer;
  2059. if (is_type_unsigned(type)) {
  2060. BigInt one = big_int_make_u64(1);
  2061. BigInt max_size = big_int_make_u64(1);
  2062. BigInt bits = big_int_make_i64(bit_size);
  2063. big_int_shl_eq(&max_size, &bits);
  2064. big_int_sub_eq(&max_size, &one);
  2065. if (big_int_is_neg(bi)) {
  2066. error_line("\tA negative value cannot be represented by the unsigned integer type '%s'\n", b);
  2067. BigInt dst = {};
  2068. big_int_neg(&dst, bi);
  2069. if (big_int_cmp(&dst, &max_size) < 0) {
  2070. big_int_sub_eq(&dst, &one);
  2071. String dst_str = big_int_to_string(temporary_allocator(), &dst);
  2072. gbString t = type_to_string(type);
  2073. error_line("\tSuggestion: ~%s(%.*s)\n", t, LIT(dst_str));
  2074. gb_string_free(t);
  2075. }
  2076. } else {
  2077. String max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2078. if (size_changed) {
  2079. 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));
  2080. } else {
  2081. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2082. }
  2083. }
  2084. } else {
  2085. BigInt zero = big_int_make_u64(0);
  2086. BigInt one = big_int_make_u64(1);
  2087. BigInt max_size = big_int_make_u64(1);
  2088. BigInt bits = big_int_make_i64(bit_size - 1);
  2089. big_int_shl_eq(&max_size, &bits);
  2090. String max_size_str = {};
  2091. if (big_int_is_neg(bi)) {
  2092. big_int_neg(&max_size, &max_size);
  2093. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2094. } else {
  2095. big_int_sub_eq(&max_size, &one);
  2096. max_size_str = big_int_to_string(temporary_allocator(), &max_size);
  2097. }
  2098. if (size_changed) {
  2099. 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));
  2100. } else {
  2101. error_line("\tThe maximum value that can be represented by '%s' is '%.*s'\n", b, LIT(max_size_str));
  2102. }
  2103. }
  2104. return true;
  2105. }
  2106. return false;
  2107. }
  2108. gb_internal void check_assignment_error_suggestion(CheckerContext *c, Operand *o, Type *type, i64 max_bit_size) {
  2109. gbString a = expr_to_string(o->expr);
  2110. gbString b = type_to_string(type);
  2111. defer(
  2112. gb_string_free(b);
  2113. gb_string_free(a);
  2114. );
  2115. Type *src = base_type(o->type);
  2116. Type *dst = base_type(type);
  2117. if (is_type_array(src) && is_type_slice(dst)) {
  2118. Type *s = src->Array.elem;
  2119. Type *d = dst->Slice.elem;
  2120. if (are_types_identical(s, d)) {
  2121. error_line("\tSuggestion: The array expression may be sliced with %s[:]\n", a);
  2122. }
  2123. } else if (is_type_dynamic_array(src) && is_type_slice(dst)) {
  2124. Type *s = src->DynamicArray.elem;
  2125. Type *d = dst->Slice.elem;
  2126. if (are_types_identical(s, d)) {
  2127. error_line("\tSuggestion: The dynamic array expression may be sliced with %s[:]\n", a);
  2128. }
  2129. }else if (are_types_identical(src, dst) && !are_types_identical(o->type, type)) {
  2130. error_line("\tSuggestion: The expression may be directly casted to type %s\n", b);
  2131. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2132. error_line("\tSuggestion: A string may be transmuted to %s\n", b);
  2133. error_line("\t This is an UNSAFE operation as string data is assumed to be immutable,\n");
  2134. error_line("\t whereas slices in general are assumed to be mutable.\n");
  2135. } else if (is_type_u8_slice(src) && are_types_identical(dst, t_string) && o->mode != Addressing_Constant) {
  2136. error_line("\tSuggestion: The expression may be casted to %s\n", b);
  2137. } else if (check_integer_exceed_suggestion(c, o, type, max_bit_size)) {
  2138. return;
  2139. } else if (is_expr_inferred_fixed_array(c->type_hint_expr) && is_type_array_like(type) && is_type_array_like(o->type)) {
  2140. gbString s = expr_to_string(c->type_hint_expr);
  2141. error_line("\tSuggestion: Make sure that `%s` is attached to the compound literal directly\n", s);
  2142. gb_string_free(s);
  2143. } else if (is_type_pointer(type) &&
  2144. o->mode == Addressing_Variable &&
  2145. are_types_identical(type_deref(type), o->type)) {
  2146. gbString s = expr_to_string(o->expr);
  2147. error_line("\tSuggestion: Did you mean `&%s`\n", s);
  2148. gb_string_free(s);
  2149. } else if (is_type_pointer(o->type) &&
  2150. are_types_identical(type_deref(o->type), type)) {
  2151. gbString s = expr_to_string(o->expr);
  2152. error_line("\tSuggestion: Did you mean `%s^`\n", s);
  2153. gb_string_free(s);
  2154. }
  2155. }
  2156. gb_internal void check_cast_error_suggestion(CheckerContext *c, Operand *o, Type *type) {
  2157. gbString a = expr_to_string(o->expr);
  2158. gbString b = type_to_string(type);
  2159. defer(
  2160. gb_string_free(b);
  2161. gb_string_free(a);
  2162. );
  2163. Type *src = base_type(o->type);
  2164. Type *dst = base_type(type);
  2165. if (is_type_array(src) && is_type_slice(dst)) {
  2166. Type *s = src->Array.elem;
  2167. Type *d = dst->Slice.elem;
  2168. if (are_types_identical(s, d)) {
  2169. error_line("\tSuggestion: the array expression may be sliced with %s[:]\n", a);
  2170. }
  2171. } else if (is_type_pointer(o->type) && is_type_integer(type)) {
  2172. if (is_type_uintptr(type)) {
  2173. error_line("\tSuggestion: a pointer may be directly casted to %s\n", b);
  2174. } else {
  2175. error_line("\tSuggestion: for a pointer to be casted to an integer, it must be converted to 'uintptr' first\n");
  2176. i64 x = type_size_of(o->type);
  2177. i64 y = type_size_of(type);
  2178. if (x != y) {
  2179. 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);
  2180. }
  2181. }
  2182. } else if (is_type_integer(o->type) && is_type_pointer(type)) {
  2183. if (is_type_uintptr(o->type)) {
  2184. error_line("\tSuggestion: %a may be directly casted to %s\n", a, b);
  2185. } else {
  2186. error_line("\tSuggestion: for an integer to be casted to a pointer, it must be converted to 'uintptr' first\n");
  2187. }
  2188. } else if (are_types_identical(src, t_string) && is_type_u8_slice(dst)) {
  2189. error_line("\tSuggestion: a string may be transmuted to %s\n", b);
  2190. } else if (check_integer_exceed_suggestion(c, o, type)) {
  2191. return;
  2192. }
  2193. }
  2194. gb_internal bool check_is_expressible(CheckerContext *ctx, Operand *o, Type *type) {
  2195. GB_ASSERT(o->mode == Addressing_Constant);
  2196. ExactValue out_value = o->value;
  2197. if (is_type_constant_type(type) && check_representable_as_constant(ctx, o->value, type, &out_value)) {
  2198. o->value = out_value;
  2199. return true;
  2200. } else {
  2201. o->value = out_value;
  2202. gbString a = expr_to_string(o->expr);
  2203. gbString b = type_to_string(type);
  2204. gbString c = type_to_string(o->type);
  2205. gbString s = exact_value_to_string(o->value);
  2206. defer(
  2207. gb_string_free(s);
  2208. gb_string_free(c);
  2209. gb_string_free(b);
  2210. gb_string_free(a);
  2211. o->mode = Addressing_Invalid;
  2212. );
  2213. ERROR_BLOCK();
  2214. if (is_type_numeric(o->type) && is_type_numeric(type)) {
  2215. if (!is_type_integer(o->type) && is_type_integer(type)) {
  2216. error(o->expr, "'%s' truncated to '%s', got %s", a, b, s);
  2217. } else {
  2218. i64 max_bit_size = 0;
  2219. if (ctx->bit_field_bit_size) {
  2220. max_bit_size = ctx->bit_field_bit_size;
  2221. }
  2222. if (are_types_identical(o->type, type)) {
  2223. error(o->expr, "Numeric value '%s' from '%s' cannot be represented by '%s'", s, a, b);
  2224. } else {
  2225. error(o->expr, "Cannot convert numeric value '%s' from '%s' to '%s' from '%s'", s, a, b, c);
  2226. }
  2227. check_assignment_error_suggestion(ctx, o, type, max_bit_size);
  2228. }
  2229. } else {
  2230. error(o->expr, "Cannot convert '%s' to '%s' from '%s', got %s", a, b, c, s);
  2231. check_assignment_error_suggestion(ctx, o, type);
  2232. }
  2233. return false;
  2234. }
  2235. }
  2236. gb_internal bool check_is_not_addressable(CheckerContext *c, Operand *o) {
  2237. if (o->expr && o->expr->kind == Ast_SelectorExpr) {
  2238. if (o->expr->SelectorExpr.is_bit_field) {
  2239. return true;
  2240. }
  2241. }
  2242. if (o->mode == Addressing_OptionalOk) {
  2243. Ast *expr = unselector_expr(o->expr);
  2244. if (expr->kind != Ast_TypeAssertion) {
  2245. return true;
  2246. }
  2247. ast_node(ta, TypeAssertion, expr);
  2248. TypeAndValue tv = ta->expr->tav;
  2249. if (is_type_pointer(tv.type)) {
  2250. return false;
  2251. }
  2252. if (is_type_union(tv.type) && tv.mode == Addressing_Variable) {
  2253. return false;
  2254. }
  2255. if (is_type_any(tv.type)) {
  2256. return false;
  2257. }
  2258. return true;
  2259. }
  2260. if (o->mode == Addressing_MapIndex) {
  2261. return false;
  2262. }
  2263. Ast *expr = unparen_expr(o->expr);
  2264. if (expr->kind == Ast_CompoundLit) {
  2265. return false;
  2266. }
  2267. return o->mode != Addressing_Variable && o->mode != Addressing_SoaVariable;
  2268. }
  2269. gb_internal ExactValue exact_bit_set_all_set_mask(Type *type) {
  2270. type = base_type(type);
  2271. GB_ASSERT(type->kind == Type_BitSet);
  2272. i64 lower = type->BitSet.lower;
  2273. i64 upper = type->BitSet.upper;
  2274. Type *elem = type->BitSet.elem;
  2275. Type *underlying = type->BitSet.underlying;
  2276. bool is_backed = underlying != nullptr;
  2277. gb_unused(is_backed);
  2278. BigInt b_lower = {};
  2279. BigInt b_upper = {};
  2280. big_int_from_i64(&b_lower, lower);
  2281. big_int_from_i64(&b_upper, upper);
  2282. BigInt one = {};
  2283. big_int_from_u64(&one, 1);
  2284. BigInt mask = {};
  2285. if (elem == nullptr) {
  2286. big_int_from_i64(&mask, -1);
  2287. } else if (is_type_enum(elem)) {
  2288. Type *e = base_type(elem);
  2289. GB_ASSERT(e->kind == Type_Enum);
  2290. gb_unused(e);
  2291. if ((big_int_cmp(&e->Enum.min_value->value_integer, &b_lower) == 0 || is_backed) &&
  2292. big_int_cmp(&e->Enum.max_value->value_integer, &b_upper) == 0) {
  2293. i64 lower_base = is_backed ? gb_min(0, lower) : lower;
  2294. BigInt b_lower_base = {};
  2295. big_int_from_i64(&b_lower_base, lower_base);
  2296. for (Entity *f : e->Enum.fields) {
  2297. if (f->kind != Entity_Constant) {
  2298. continue;
  2299. }
  2300. if (f->Constant.value.kind != ExactValue_Integer) {
  2301. continue;
  2302. }
  2303. BigInt shift_amount = {};
  2304. big_int_sub(&shift_amount, &f->Constant.value.value_integer, &b_lower_base);
  2305. BigInt value = {};
  2306. big_int_shl(&value, &one, &shift_amount);
  2307. big_int_or(&mask, &mask, &value);
  2308. }
  2309. } else {
  2310. // TODO(bill): enum range based");
  2311. big_int_from_i64(&mask, -1);
  2312. }
  2313. } else {
  2314. i64 lower_base = lower;
  2315. for (i64 x = lower; x <= upper; x++) {
  2316. BigInt shift_amount = {};
  2317. big_int_from_i64(&shift_amount, x - lower_base);
  2318. BigInt value = {};
  2319. big_int_shl(&value, &one, &shift_amount);
  2320. big_int_or(&mask, &mask, &value);
  2321. }
  2322. }
  2323. ExactValue res = {};
  2324. res.kind = ExactValue_Integer;
  2325. res.value_integer = mask;
  2326. return res;
  2327. }
  2328. gb_internal void check_unary_expr(CheckerContext *c, Operand *o, Token op, Ast *node) {
  2329. switch (op.kind) {
  2330. case Token_And: { // Pointer address
  2331. if (check_is_not_addressable(c, o)) {
  2332. if (ast_node_expect(node, Ast_UnaryExpr)) {
  2333. ast_node(ue, UnaryExpr, node);
  2334. gbString str = expr_to_string(ue->expr);
  2335. defer (gb_string_free(str));
  2336. Entity *e = entity_of_node(ue->expr);
  2337. if (e != nullptr && (e->flags & EntityFlag_Param) != 0) {
  2338. error(op, "Cannot take the pointer address of '%s' which is a procedure parameter", str);
  2339. } else if (e != nullptr && (e->flags & EntityFlag_BitFieldField) != 0) {
  2340. error(op, "Cannot take the pointer address of '%s' which is a bit_field's field", str);
  2341. } else {
  2342. switch (o->mode) {
  2343. case Addressing_Constant:
  2344. error(op, "Cannot take the pointer address of '%s' which is a constant", str);
  2345. break;
  2346. case Addressing_SwizzleValue:
  2347. case Addressing_SwizzleVariable:
  2348. error(op, "Cannot take the pointer address of '%s' which is a swizzle intermediate array value", str);
  2349. break;
  2350. default:
  2351. {
  2352. ERROR_BLOCK();
  2353. error(op, "Cannot take the pointer address of '%s'", str);
  2354. if (e == nullptr) {
  2355. break;
  2356. }
  2357. if ((e->flags & EntityFlag_ForValue) != 0) {
  2358. Type *parent_type = type_deref(e->Variable.for_loop_parent_type);
  2359. if (parent_type != nullptr && is_type_string(parent_type)) {
  2360. error_line("\tSuggestion: Iterating over a string produces an intermediate 'rune' value which cannot be addressed.\n");
  2361. } else if (parent_type != nullptr && is_type_tuple(parent_type)) {
  2362. error_line("\tSuggestion: Iterating over a procedure does not produce values which are addressable.\n");
  2363. } else {
  2364. error_line("\tSuggestion: Did you want to pass the iterable value to the for statement by pointer to get addressable semantics?\n");
  2365. }
  2366. if (parent_type != nullptr && is_type_map(parent_type)) {
  2367. error_line("\t Prefer doing 'for key, &%.*s in ...'\n", LIT(e->token.string));
  2368. } else {
  2369. error_line("\t Prefer doing 'for &%.*s in ...'\n", LIT(e->token.string));
  2370. }
  2371. }
  2372. if ((e->flags & EntityFlag_SwitchValue) != 0) {
  2373. error_line("\tSuggestion: Did you want to pass the value to the switch statement by pointer to get addressable semantics?\n");
  2374. error_line("\t Prefer doing 'switch &%.*s in ...'\n", LIT(e->token.string));
  2375. }
  2376. }
  2377. break;
  2378. }
  2379. }
  2380. }
  2381. o->mode = Addressing_Invalid;
  2382. return;
  2383. }
  2384. if (o->mode == Addressing_SoaVariable) {
  2385. ast_node(ue, UnaryExpr, node);
  2386. if (ast_node_expect(ue->expr, Ast_IndexExpr)) {
  2387. ast_node(ie, IndexExpr, ue->expr);
  2388. Type *soa_type = type_deref(type_of_expr(ie->expr));
  2389. GB_ASSERT(is_type_soa_struct(soa_type));
  2390. o->type = alloc_type_soa_pointer(soa_type);
  2391. } else {
  2392. o->type = alloc_type_pointer(o->type);
  2393. }
  2394. } else {
  2395. o->type = alloc_type_pointer(o->type);
  2396. }
  2397. switch (o->mode) {
  2398. case Addressing_OptionalOk:
  2399. case Addressing_MapIndex:
  2400. o->mode = Addressing_OptionalOkPtr;
  2401. break;
  2402. default:
  2403. o->mode = Addressing_Value;
  2404. break;
  2405. }
  2406. return;
  2407. }
  2408. }
  2409. if (!check_unary_op(c, o, op)) {
  2410. o->mode = Addressing_Invalid;
  2411. return;
  2412. }
  2413. if (o->mode == Addressing_Constant) {
  2414. Type *type = base_type(o->type);
  2415. if (!is_type_constant_type(o->type)) {
  2416. if (is_type_array_like(o->type)) {
  2417. o->mode = Addressing_Value;
  2418. return;
  2419. }
  2420. gbString xt = type_to_string(o->type);
  2421. gbString err_str = expr_to_string(node);
  2422. error(op, "Invalid type, '%s', for constant unary expression '%s'", xt, err_str);
  2423. gb_string_free(err_str);
  2424. gb_string_free(xt);
  2425. o->mode = Addressing_Invalid;
  2426. return;
  2427. }
  2428. if (op.kind == Token_Xor && is_type_untyped(type)) {
  2429. gbString err_str = expr_to_string(node);
  2430. error(op, "Bitwise not cannot be applied to untyped constants '%s'", err_str);
  2431. gb_string_free(err_str);
  2432. o->mode = Addressing_Invalid;
  2433. return;
  2434. }
  2435. if (op.kind == Token_Sub && is_type_unsigned(type)) {
  2436. gbString err_str = expr_to_string(node);
  2437. error(op, "A unsigned constant cannot be negated '%s'", err_str);
  2438. gb_string_free(err_str);
  2439. o->mode = Addressing_Invalid;
  2440. return;
  2441. }
  2442. i32 precision = 0;
  2443. if (is_type_typed(type)) {
  2444. precision = cast(i32)(8 * type_size_of(type));
  2445. }
  2446. bool is_unsigned = is_type_unsigned(type);
  2447. if (is_type_rune(type)) {
  2448. GB_ASSERT(!is_unsigned);
  2449. }
  2450. o->value = exact_unary_operator_value(op.kind, o->value, precision, is_unsigned);
  2451. if (op.kind == Token_Xor && is_type_bit_set(type)) {
  2452. ExactValue mask = exact_bit_set_all_set_mask(type);
  2453. o->value = exact_binary_operator_value(Token_And, o->value, mask);
  2454. }
  2455. if (is_type_typed(type)) {
  2456. if (node != nullptr) {
  2457. o->expr = node;
  2458. }
  2459. check_is_expressible(c, o, type);
  2460. }
  2461. return;
  2462. }
  2463. o->mode = Addressing_Value;
  2464. }
  2465. gb_internal void add_comparison_procedures_for_fields(CheckerContext *c, Type *t) {
  2466. if (t == nullptr) {
  2467. return;
  2468. }
  2469. t = base_type(t);
  2470. if (!is_type_comparable(t)) {
  2471. return;
  2472. }
  2473. switch (t->kind) {
  2474. case Type_Basic:
  2475. switch (t->Basic.kind) {
  2476. case Basic_complex32:
  2477. add_package_dependency(c, "runtime", "complex32_eq");
  2478. add_package_dependency(c, "runtime", "complex32_ne");
  2479. break;
  2480. case Basic_complex64:
  2481. add_package_dependency(c, "runtime", "complex64_eq");
  2482. add_package_dependency(c, "runtime", "complex64_ne");
  2483. break;
  2484. case Basic_complex128:
  2485. add_package_dependency(c, "runtime", "complex128_eq");
  2486. add_package_dependency(c, "runtime", "complex128_ne");
  2487. break;
  2488. case Basic_quaternion64:
  2489. add_package_dependency(c, "runtime", "quaternion64_eq");
  2490. add_package_dependency(c, "runtime", "quaternion64_ne");
  2491. break;
  2492. case Basic_quaternion128:
  2493. add_package_dependency(c, "runtime", "quaternion128_eq");
  2494. add_package_dependency(c, "runtime", "quaternion128_ne");
  2495. break;
  2496. case Basic_quaternion256:
  2497. add_package_dependency(c, "runtime", "quaternion256_eq");
  2498. add_package_dependency(c, "runtime", "quaternion256_ne");
  2499. break;
  2500. case Basic_cstring:
  2501. add_package_dependency(c, "runtime", "cstring_eq");
  2502. add_package_dependency(c, "runtime", "cstring_ne");
  2503. break;
  2504. case Basic_string:
  2505. add_package_dependency(c, "runtime", "string_eq");
  2506. add_package_dependency(c, "runtime", "string_ne");
  2507. break;
  2508. case Basic_cstring16:
  2509. add_package_dependency(c, "runtime", "cstring16_eq");
  2510. add_package_dependency(c, "runtime", "cstring16_ne");
  2511. break;
  2512. case Basic_string16:
  2513. add_package_dependency(c, "runtime", "string16_eq");
  2514. add_package_dependency(c, "runtime", "string16_ne");
  2515. break;
  2516. }
  2517. break;
  2518. case Type_Struct:
  2519. for (Entity *field : t->Struct.fields) {
  2520. add_comparison_procedures_for_fields(c, field->type);
  2521. }
  2522. break;
  2523. }
  2524. }
  2525. gb_internal void check_comparison(CheckerContext *c, Ast *node, Operand *x, Operand *y, TokenKind op) {
  2526. if (x->mode == Addressing_Type && y->mode == Addressing_Type) {
  2527. bool comp = are_types_identical(x->type, y->type);
  2528. switch (op) {
  2529. case Token_CmpEq: /* comp = comp; */ break;
  2530. case Token_NotEq: comp = !comp; break;
  2531. }
  2532. x->mode = Addressing_Constant;
  2533. x->type = t_untyped_bool;
  2534. x->value = exact_value_bool(comp);
  2535. return;
  2536. }
  2537. if (x->mode == Addressing_Type && is_type_typeid(y->type)) {
  2538. add_type_info_type(c, x->type);
  2539. add_type_info_type(c, y->type);
  2540. add_type_and_value(c, x->expr, Addressing_Value, y->type, exact_value_typeid(x->type));
  2541. x->mode = Addressing_Value;
  2542. x->type = t_untyped_bool;
  2543. return;
  2544. } else if (is_type_typeid(x->type) && y->mode == Addressing_Type) {
  2545. add_type_info_type(c, x->type);
  2546. add_type_info_type(c, y->type);
  2547. add_type_and_value(c, y->expr, Addressing_Value, x->type, exact_value_typeid(y->type));
  2548. x->mode = Addressing_Value;
  2549. x->type = t_untyped_bool;
  2550. return;
  2551. }
  2552. TEMPORARY_ALLOCATOR_GUARD();
  2553. gbString err_str = nullptr;
  2554. if (check_is_assignable_to(c, x, y->type) ||
  2555. check_is_assignable_to(c, y, x->type)) {
  2556. Type *err_type = x->type;
  2557. bool defined = false;
  2558. switch (op) {
  2559. case Token_CmpEq:
  2560. case Token_NotEq:
  2561. defined = (is_type_comparable(x->type) && is_type_comparable(y->type)) ||
  2562. (is_operand_nil(*x) && type_has_nil(y->type)) ||
  2563. (is_operand_nil(*y) && type_has_nil(x->type));
  2564. break;
  2565. case Token_Lt:
  2566. case Token_Gt:
  2567. case Token_LtEq:
  2568. case Token_GtEq:
  2569. if (are_types_identical(x->type, y->type) && is_type_bit_set(x->type)) {
  2570. defined = true;
  2571. } else {
  2572. defined = is_type_ordered(x->type) && is_type_ordered(y->type);
  2573. }
  2574. break;
  2575. }
  2576. if (!defined) {
  2577. gbString xs = type_to_string(x->type, temporary_allocator());
  2578. gbString ys = type_to_string(y->type, temporary_allocator());
  2579. if (!is_type_comparable(x->type)) {
  2580. err_str = gb_string_make(temporary_allocator(),
  2581. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", xs, LIT(token_strings[op]))
  2582. );
  2583. } else if (!is_type_comparable(y->type)) {
  2584. err_str = gb_string_make(temporary_allocator(),
  2585. gb_bprintf("Type '%s' is not simply comparable, so operator '%.*s' is not defined for it", ys, LIT(token_strings[op]))
  2586. );
  2587. } else {
  2588. err_str = gb_string_make(temporary_allocator(),
  2589. gb_bprintf("Operator '%.*s' not defined between the types '%s' and '%s'", LIT(token_strings[op]), xs, ys)
  2590. );
  2591. }
  2592. } else {
  2593. Type *comparison_type = x->type;
  2594. if (x->type == err_type && is_operand_nil(*x)) {
  2595. comparison_type = y->type;
  2596. }
  2597. add_comparison_procedures_for_fields(c, comparison_type);
  2598. }
  2599. } else {
  2600. gbString xt, yt;
  2601. if (x->mode == Addressing_ProcGroup) {
  2602. xt = gb_string_make(temporary_allocator(), "procedure group");
  2603. } else {
  2604. xt = type_to_string(x->type);
  2605. }
  2606. if (y->mode == Addressing_ProcGroup) {
  2607. yt = gb_string_make(temporary_allocator(), "procedure group");
  2608. } else {
  2609. yt = type_to_string(y->type);
  2610. }
  2611. err_str = gb_string_make(temporary_allocator(), gb_bprintf("Mismatched types '%s' and '%s'", xt, yt));
  2612. }
  2613. if (err_str != nullptr) {
  2614. error(node, "Cannot compare expression. %s.", err_str);
  2615. x->type = t_untyped_bool;
  2616. } else {
  2617. if (x->mode == Addressing_Constant &&
  2618. y->mode == Addressing_Constant) {
  2619. if (is_type_constant_type(x->type)) {
  2620. if (is_type_bit_set(x->type)) {
  2621. switch (op) {
  2622. case Token_CmpEq:
  2623. case Token_NotEq:
  2624. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2625. break;
  2626. case Token_Lt:
  2627. case Token_LtEq:
  2628. {
  2629. ExactValue lhs = x->value;
  2630. ExactValue rhs = y->value;
  2631. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2632. res = exact_value_bool(compare_exact_values(op, res, lhs));
  2633. if (op == Token_Lt) {
  2634. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2635. }
  2636. x->value = res;
  2637. break;
  2638. }
  2639. case Token_Gt:
  2640. case Token_GtEq:
  2641. {
  2642. ExactValue lhs = x->value;
  2643. ExactValue rhs = y->value;
  2644. ExactValue res = exact_binary_operator_value(Token_And, lhs, rhs);
  2645. res = exact_value_bool(compare_exact_values(op, res, rhs));
  2646. if (op == Token_Gt) {
  2647. res = exact_binary_operator_value(Token_And, res, exact_value_bool(compare_exact_values(op, lhs, rhs)));
  2648. }
  2649. x->value = res;
  2650. break;
  2651. }
  2652. }
  2653. } else {
  2654. x->value = exact_value_bool(compare_exact_values(op, x->value, y->value));
  2655. }
  2656. } else {
  2657. x->mode = Addressing_Value;
  2658. }
  2659. } else {
  2660. x->mode = Addressing_Value;
  2661. update_untyped_expr_type(c, x->expr, default_type(x->type), true);
  2662. update_untyped_expr_type(c, y->expr, default_type(y->type), true);
  2663. i64 size = 0;
  2664. if (!is_type_untyped(x->type)) size = gb_max(size, type_size_of(x->type));
  2665. if (!is_type_untyped(y->type)) size = gb_max(size, type_size_of(y->type));
  2666. if (is_type_cstring(x->type) && is_type_cstring(y->type)) {
  2667. switch (op) {
  2668. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring_eq"); break;
  2669. case Token_NotEq: add_package_dependency(c, "runtime", "cstring_ne"); break;
  2670. case Token_Lt: add_package_dependency(c, "runtime", "cstring_lt"); break;
  2671. case Token_Gt: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2672. case Token_LtEq: add_package_dependency(c, "runtime", "cstring_le"); break;
  2673. case Token_GtEq: add_package_dependency(c, "runtime", "cstring_gt"); break;
  2674. }
  2675. } else if (is_type_cstring16(x->type) && is_type_cstring16(y->type)) {
  2676. switch (op) {
  2677. case Token_CmpEq: add_package_dependency(c, "runtime", "cstring16_eq"); break;
  2678. case Token_NotEq: add_package_dependency(c, "runtime", "cstring16_ne"); break;
  2679. case Token_Lt: add_package_dependency(c, "runtime", "cstring16_lt"); break;
  2680. case Token_Gt: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2681. case Token_LtEq: add_package_dependency(c, "runtime", "cstring16_le"); break;
  2682. case Token_GtEq: add_package_dependency(c, "runtime", "cstring16_gt"); break;
  2683. }
  2684. } else if (is_type_string16(x->type) || is_type_string16(y->type)) {
  2685. switch (op) {
  2686. case Token_CmpEq: add_package_dependency(c, "runtime", "string16_eq"); break;
  2687. case Token_NotEq: add_package_dependency(c, "runtime", "string16_ne"); break;
  2688. case Token_Lt: add_package_dependency(c, "runtime", "string16_lt"); break;
  2689. case Token_Gt: add_package_dependency(c, "runtime", "string16_gt"); break;
  2690. case Token_LtEq: add_package_dependency(c, "runtime", "string16_le"); break;
  2691. case Token_GtEq: add_package_dependency(c, "runtime", "string16_gt"); break;
  2692. }
  2693. } else if (is_type_string(x->type) || is_type_string(y->type)) {
  2694. switch (op) {
  2695. case Token_CmpEq: add_package_dependency(c, "runtime", "string_eq"); break;
  2696. case Token_NotEq: add_package_dependency(c, "runtime", "string_ne"); break;
  2697. case Token_Lt: add_package_dependency(c, "runtime", "string_lt"); break;
  2698. case Token_Gt: add_package_dependency(c, "runtime", "string_gt"); break;
  2699. case Token_LtEq: add_package_dependency(c, "runtime", "string_le"); break;
  2700. case Token_GtEq: add_package_dependency(c, "runtime", "string_gt"); break;
  2701. }
  2702. } else if (is_type_complex(x->type) || is_type_complex(y->type)) {
  2703. switch (op) {
  2704. case Token_CmpEq:
  2705. switch (8*size) {
  2706. case 64: add_package_dependency(c, "runtime", "complex64_eq"); break;
  2707. case 128: add_package_dependency(c, "runtime", "complex128_eq"); break;
  2708. }
  2709. break;
  2710. case Token_NotEq:
  2711. switch (8*size) {
  2712. case 64: add_package_dependency(c, "runtime", "complex64_ne"); break;
  2713. case 128: add_package_dependency(c, "runtime", "complex128_ne"); break;
  2714. }
  2715. break;
  2716. }
  2717. } else if (is_type_quaternion(x->type) || is_type_quaternion(y->type)) {
  2718. switch (op) {
  2719. case Token_CmpEq:
  2720. switch (8*size) {
  2721. case 128: add_package_dependency(c, "runtime", "quaternion128_eq"); break;
  2722. case 256: add_package_dependency(c, "runtime", "quaternion256_eq"); break;
  2723. }
  2724. break;
  2725. case Token_NotEq:
  2726. switch (8*size) {
  2727. case 128: add_package_dependency(c, "runtime", "quaternion128_ne"); break;
  2728. case 256: add_package_dependency(c, "runtime", "quaternion256_ne"); break;
  2729. }
  2730. break;
  2731. }
  2732. }
  2733. }
  2734. x->type = t_untyped_bool;
  2735. }
  2736. }
  2737. gb_internal void check_shift(CheckerContext *c, Operand *x, Operand *y, Ast *node, Type *type_hint) {
  2738. GB_ASSERT(node->kind == Ast_BinaryExpr);
  2739. ast_node(be, BinaryExpr, node);
  2740. bool y_is_untyped = is_type_untyped(y->type);
  2741. if (y_is_untyped) {
  2742. convert_to_typed(c, y, t_untyped_integer);
  2743. if (y->mode == Addressing_Invalid) {
  2744. x->mode = Addressing_Invalid;
  2745. return;
  2746. }
  2747. } else if (!is_type_unsigned(y->type)) {
  2748. gbString y_str = expr_to_string(y->expr);
  2749. error(y->expr, "Shift amount '%s' must be an unsigned integer", y_str);
  2750. gb_string_free(y_str);
  2751. x->mode = Addressing_Invalid;
  2752. return;
  2753. }
  2754. bool x_is_untyped = is_type_untyped(x->type);
  2755. if (!(x_is_untyped || is_type_integer(x->type))) {
  2756. gbString x_str = expr_to_string(x->expr);
  2757. error(x->expr, "Shifted operand '%s' must be an integer", x_str);
  2758. gb_string_free(x_str);
  2759. x->mode = Addressing_Invalid;
  2760. return;
  2761. }
  2762. if (y->mode == Addressing_Constant) {
  2763. if (big_int_is_neg(&y->value.value_integer)) {
  2764. gbString y_str = expr_to_string(y->expr);
  2765. error(y->expr, "Shift amount '%s' cannot be negative", y_str);
  2766. gb_string_free(y_str);
  2767. x->mode = Addressing_Invalid;
  2768. return;
  2769. }
  2770. BigInt max_shift = {};
  2771. big_int_from_u64(&max_shift, MAX_BIG_INT_SHIFT);
  2772. if (big_int_cmp(&y->value.value_integer, &max_shift) > 0) {
  2773. gbString y_str = expr_to_string(y->expr);
  2774. error(y->expr, "Shift amount '%s' must be <= %u", y_str, MAX_BIG_INT_SHIFT);
  2775. gb_string_free(y_str);
  2776. x->mode = Addressing_Invalid;
  2777. return;
  2778. }
  2779. if (x->mode == Addressing_Constant) {
  2780. if (x_is_untyped) {
  2781. convert_to_typed(c, x, t_untyped_integer);
  2782. if (x->mode == Addressing_Invalid) {
  2783. return;
  2784. }
  2785. x->expr = node;
  2786. x->value = exact_value_shift(be->op.kind, exact_value_to_integer(x->value), exact_value_to_integer(y->value));
  2787. return;
  2788. }
  2789. x->expr = node;
  2790. x->value = exact_value_shift(be->op.kind, x->value, y->value);
  2791. check_is_expressible(c, x, x->type);
  2792. return;
  2793. }
  2794. if (y_is_untyped) {
  2795. convert_to_typed(c, y, t_uint);
  2796. }
  2797. return;
  2798. }
  2799. if (x->mode == Addressing_Constant) {
  2800. if (x_is_untyped) {
  2801. if (type_hint) {
  2802. if (is_type_integer(type_hint)) {
  2803. convert_to_typed(c, x, type_hint);
  2804. } else if (is_type_any(type_hint)) {
  2805. convert_to_typed(c, x, default_type(t_untyped_integer));
  2806. } else {
  2807. gbString x_str = expr_to_string(x->expr);
  2808. gbString type_str = type_to_string(type_hint);
  2809. error(x->expr, "Shifted operand '%s' cannot convert to non-integer type '%s'", x_str, type_str);
  2810. gb_string_free(x_str);
  2811. gb_string_free(type_str);
  2812. x->mode = Addressing_Invalid;
  2813. return;
  2814. }
  2815. } else {
  2816. check_is_expressible(c, x, default_type(t_untyped_integer));
  2817. }
  2818. if (x->mode == Addressing_Invalid) {
  2819. return;
  2820. }
  2821. }
  2822. x->mode = Addressing_Value;
  2823. }
  2824. }
  2825. gb_internal bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) {
  2826. if (check_is_assignable_to(c, operand, y)) {
  2827. return true;
  2828. }
  2829. bool is_constant = operand->mode == Addressing_Constant;
  2830. Type *x = operand->type;
  2831. Type *src = core_type(x);
  2832. Type *dst = core_type(y);
  2833. if (are_types_identical(src, dst)) {
  2834. return true;
  2835. }
  2836. // if (is_type_tuple(src)) {
  2837. // Ast *expr = unparen_expr(operand->expr);
  2838. // if (expr && expr->kind == Ast_CallExpr) {
  2839. // // NOTE(bill, 2021-04-19): Allow casting procedure calls with #optional_ok
  2840. // ast_node(ce, CallExpr, expr);
  2841. // Type *pt = base_type(type_of_expr(ce->proc));
  2842. // if (pt->kind == Type_Proc && pt->Proc.optional_ok) {
  2843. // if (pt->Proc.result_count > 0) {
  2844. // Operand op = *operand;
  2845. // op.type = pt->Proc.results->Tuple.variables[0]->type;
  2846. // bool ok = check_is_castable_to(c, &op, y);
  2847. // if (ok) {
  2848. // ce->optional_ok_one = true;
  2849. // }
  2850. // return ok;
  2851. // }
  2852. // }
  2853. // }
  2854. // }
  2855. if (is_constant && is_type_untyped(src) && is_type_string(src)) {
  2856. if (is_type_u8_array(dst)) {
  2857. String s = operand->value.value_string;
  2858. return s.len == dst->Array.count;
  2859. }
  2860. if (is_type_rune_array(dst)) {
  2861. String s = operand->value.value_string;
  2862. return gb_utf8_strnlen(s.text, s.len) == dst->Array.count;
  2863. }
  2864. }
  2865. if (dst->kind == Type_Array && src->kind == Type_Array) {
  2866. if (are_types_identical(dst->Array.elem, src->Array.elem)) {
  2867. return dst->Array.count == src->Array.count;
  2868. }
  2869. }
  2870. if (dst->kind == Type_Slice && src->kind == Type_Slice) {
  2871. return are_types_identical(dst->Slice.elem, src->Slice.elem);
  2872. }
  2873. // Cast between booleans and integers
  2874. if (is_type_boolean(src) || is_type_integer(src)) {
  2875. if (is_type_boolean(dst) || is_type_integer(dst)) {
  2876. return true;
  2877. }
  2878. }
  2879. // Cast between numbers
  2880. if (is_type_integer(src) || is_type_float(src)) {
  2881. if (is_type_integer(dst) || is_type_float(dst)) {
  2882. return true;
  2883. }
  2884. }
  2885. if (is_type_bit_field(src)) {
  2886. return are_types_identical(core_type(src->BitField.backing_type), dst);
  2887. }
  2888. if (is_type_bit_field(dst)) {
  2889. return are_types_identical(src, core_type(dst->BitField.backing_type));
  2890. }
  2891. if (is_type_integer(src) && is_type_rune(dst)) {
  2892. return true;
  2893. }
  2894. if (is_type_rune(src) && is_type_integer(dst)) {
  2895. return true;
  2896. }
  2897. if (is_type_complex(src) && is_type_complex(dst)) {
  2898. return true;
  2899. }
  2900. if (is_type_float(src) && is_type_complex(dst)) {
  2901. return true;
  2902. }
  2903. if (is_type_float(src) && is_type_quaternion(dst)) {
  2904. return true;
  2905. }
  2906. if (is_type_complex(src) && is_type_quaternion(dst)) {
  2907. return true;
  2908. }
  2909. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  2910. return true;
  2911. }
  2912. if (is_type_matrix(src) && is_type_matrix(dst)) {
  2913. GB_ASSERT(src->kind == Type_Matrix);
  2914. GB_ASSERT(dst->kind == Type_Matrix);
  2915. Operand op = *operand;
  2916. op.type = src->Matrix.elem;
  2917. if (!check_is_castable_to(c, &op, dst->Matrix.elem)) {
  2918. return false;
  2919. }
  2920. if (src->Matrix.row_count != src->Matrix.column_count) {
  2921. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  2922. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  2923. return src_count == dst_count;
  2924. }
  2925. return is_matrix_square(dst) && is_matrix_square(src);
  2926. }
  2927. // Cast between pointers
  2928. if (is_type_pointer(src) && is_type_pointer(dst)) {
  2929. return true;
  2930. }
  2931. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  2932. return true;
  2933. }
  2934. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  2935. return true;
  2936. }
  2937. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  2938. return true;
  2939. }
  2940. // uintptr <-> pointer
  2941. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  2942. return true;
  2943. }
  2944. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  2945. return true;
  2946. }
  2947. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  2948. return true;
  2949. }
  2950. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  2951. return true;
  2952. }
  2953. // []byte/[]u8 <-> string (not cstring)
  2954. if (is_type_u8_slice(src) && (is_type_string(dst) && !is_type_cstring(dst))) {
  2955. return true;
  2956. }
  2957. // []u16 <-> string16 (not cstring16)
  2958. if (is_type_u16_slice(src) && (is_type_string16(dst) && !is_type_cstring16(dst))) {
  2959. return true;
  2960. }
  2961. // cstring -> string
  2962. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  2963. if (operand->mode != Addressing_Constant) {
  2964. add_package_dependency(c, "runtime", "cstring_to_string");
  2965. }
  2966. return true;
  2967. }
  2968. // cstring16 -> string16
  2969. if (are_types_identical(src, t_cstring16) && are_types_identical(dst, t_string16)) {
  2970. if (operand->mode != Addressing_Constant) {
  2971. add_package_dependency(c, "runtime", "cstring16_to_string16");
  2972. }
  2973. return true;
  2974. }
  2975. // cstring -> ^u8
  2976. if (are_types_identical(src, t_cstring) && is_type_u8_ptr(dst)) {
  2977. return !is_constant;
  2978. }
  2979. // cstring -> [^]u8
  2980. if (are_types_identical(src, t_cstring) && is_type_u8_multi_ptr(dst)) {
  2981. return !is_constant;
  2982. }
  2983. // cstring -> rawptr
  2984. if (are_types_identical(src, t_cstring) && is_type_rawptr(dst)) {
  2985. return !is_constant;
  2986. }
  2987. // ^u8 -> cstring
  2988. if (is_type_u8_ptr(src) && are_types_identical(dst, t_cstring)) {
  2989. return !is_constant;
  2990. }
  2991. // [^]u8 -> cstring
  2992. if (is_type_u8_multi_ptr(src) && are_types_identical(dst, t_cstring)) {
  2993. return !is_constant;
  2994. }
  2995. // rawptr -> cstring
  2996. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring)) {
  2997. return !is_constant;
  2998. }
  2999. // cstring -> ^u16
  3000. if (are_types_identical(src, t_cstring16) && is_type_u16_ptr(dst)) {
  3001. return !is_constant;
  3002. }
  3003. // cstring -> [^]u16
  3004. if (are_types_identical(src, t_cstring16) && is_type_u16_multi_ptr(dst)) {
  3005. return !is_constant;
  3006. }
  3007. // cstring16 -> rawptr
  3008. if (are_types_identical(src, t_cstring16) && is_type_rawptr(dst)) {
  3009. return !is_constant;
  3010. }
  3011. // ^u16 -> cstring16
  3012. if (is_type_u16_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3013. return !is_constant;
  3014. }
  3015. // [^]u16 -> cstring
  3016. if (is_type_u16_multi_ptr(src) && are_types_identical(dst, t_cstring16)) {
  3017. return !is_constant;
  3018. }
  3019. // rawptr -> cstring16
  3020. if (is_type_rawptr(src) && are_types_identical(dst, t_cstring16)) {
  3021. return !is_constant;
  3022. }
  3023. // proc <-> proc
  3024. if (is_type_proc(src) && is_type_proc(dst)) {
  3025. if (is_type_polymorphic(dst)) {
  3026. if (is_type_polymorphic(src) &&
  3027. operand->mode == Addressing_Variable) {
  3028. return true;
  3029. }
  3030. return false;
  3031. }
  3032. return true;
  3033. }
  3034. // proc -> rawptr
  3035. if (is_type_proc(src) && is_type_rawptr(dst)) {
  3036. return true;
  3037. }
  3038. // rawptr -> proc
  3039. if (is_type_rawptr(src) && is_type_proc(dst)) {
  3040. return true;
  3041. }
  3042. if (is_type_array(dst)) {
  3043. Type *elem = base_array_type(dst);
  3044. if (check_is_castable_to(c, operand, elem)) {
  3045. return true;
  3046. }
  3047. }
  3048. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  3049. if (src->SimdVector.count != dst->SimdVector.count) {
  3050. return false;
  3051. }
  3052. Type *elem_src = base_array_type(src);
  3053. Type *elem_dst = base_array_type(dst);
  3054. Operand x = {};
  3055. x.type = elem_src;
  3056. x.mode = Addressing_Value;
  3057. return check_is_castable_to(c, &x, elem_dst);
  3058. }
  3059. if (is_type_simd_vector(dst)) {
  3060. Type *elem = base_array_type(dst);
  3061. if (check_is_castable_to(c, operand, elem)) {
  3062. return true;
  3063. }
  3064. }
  3065. return false;
  3066. }
  3067. gb_internal bool check_cast_internal(CheckerContext *c, Operand *x, Type *type) {
  3068. bool is_const_expr = x->mode == Addressing_Constant;
  3069. Type *bt = base_type(type);
  3070. if (is_const_expr && is_type_constant_type(bt)) {
  3071. if (core_type(bt)->kind == Type_Basic) {
  3072. if (check_representable_as_constant(c, x->value, bt, &x->value)) {
  3073. return true;
  3074. } else if (check_is_castable_to(c, x, type)) {
  3075. if (is_type_pointer(type)) {
  3076. return true;
  3077. }
  3078. }
  3079. } else if (check_is_castable_to(c, x, type)) {
  3080. x->value = {};
  3081. x->mode = Addressing_Value;
  3082. return true;
  3083. }
  3084. } else if (check_is_castable_to(c, x, type)) {
  3085. if (x->mode != Addressing_Constant) {
  3086. x->mode = Addressing_Value;
  3087. } else if (is_type_slice(type) && is_type_string(x->type)) {
  3088. x->mode = Addressing_Value;
  3089. } else if (is_type_union(type)) {
  3090. x->mode = Addressing_Value;
  3091. }
  3092. if (x->mode == Addressing_Value) {
  3093. x->value = {};
  3094. }
  3095. return true;
  3096. }
  3097. return false;
  3098. }
  3099. gb_internal void check_cast(CheckerContext *c, Operand *x, Type *type, bool forbid_identical = false) {
  3100. if (!is_operand_value(*x)) {
  3101. error(x->expr, "Only values can be casted");
  3102. x->mode = Addressing_Invalid;
  3103. return;
  3104. }
  3105. bool is_const_expr = x->mode == Addressing_Constant;
  3106. bool can_convert = check_cast_internal(c, x, type);
  3107. if (!can_convert) {
  3108. TEMPORARY_ALLOCATOR_GUARD();
  3109. gbString expr_str = expr_to_string(x->expr, temporary_allocator());
  3110. gbString to_type = type_to_string(type, temporary_allocator());
  3111. gbString from_type = type_to_string(x->type, temporary_allocator());
  3112. x->mode = Addressing_Invalid;
  3113. ERROR_BLOCK();
  3114. error(x->expr, "Cannot cast '%s' as '%s' from '%s'", expr_str, to_type, from_type);
  3115. if (is_const_expr) {
  3116. gbString val_str = exact_value_to_string(x->value);
  3117. if (is_type_float(x->type) && is_type_integer(type)) {
  3118. error_line("\t%s cannot be represented without truncation/rounding as the type '%s'\n", val_str, to_type);
  3119. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3120. x->mode = Addressing_Constant;
  3121. x->type = type;
  3122. } else {
  3123. error_line("\t'%s' cannot be represented as the type '%s'\n", val_str, to_type);
  3124. if (is_type_numeric(type)) {
  3125. // NOTE(bill): keep the mode and modify the type to minimize errors further on
  3126. x->mode = Addressing_Constant;
  3127. x->type = type;
  3128. }
  3129. }
  3130. gb_string_free(val_str);
  3131. }
  3132. check_cast_error_suggestion(c, x, type);
  3133. return;
  3134. }
  3135. if (is_type_untyped(x->type)) {
  3136. Type *final_type = type;
  3137. if (is_const_expr && !is_type_constant_type(type)) {
  3138. if (is_type_union(type)) {
  3139. convert_to_typed(c, x, type);
  3140. }
  3141. final_type = default_type(x->type);
  3142. }
  3143. update_untyped_expr_type(c, x->expr, final_type, true);
  3144. } else {
  3145. Type *src = core_type(x->type);
  3146. Type *dst = core_type(type);
  3147. if (src != dst) {
  3148. bool const REQUIRE = true;
  3149. if (is_type_integer_128bit(src) && is_type_float(dst)) {
  3150. add_package_dependency(c, "runtime", "floattidf_unsigned", REQUIRE);
  3151. add_package_dependency(c, "runtime", "floattidf", REQUIRE);
  3152. } else if (is_type_integer_128bit(dst) && is_type_float(src)) {
  3153. add_package_dependency(c, "runtime", "fixunsdfti", REQUIRE);
  3154. add_package_dependency(c, "runtime", "fixunsdfdi", REQUIRE);
  3155. } else if (src == t_f16 && is_type_float(dst)) {
  3156. add_package_dependency(c, "runtime", "gnu_h2f_ieee", REQUIRE);
  3157. add_package_dependency(c, "runtime", "extendhfsf2", REQUIRE);
  3158. } else if (is_type_float(dst) && dst == t_f16) {
  3159. add_package_dependency(c, "runtime", "truncsfhf2", REQUIRE);
  3160. add_package_dependency(c, "runtime", "truncdfhf2", REQUIRE);
  3161. add_package_dependency(c, "runtime", "gnu_f2h_ieee", REQUIRE);
  3162. }
  3163. }
  3164. // If we check polymorphic procedures, we risk erring on
  3165. // identical casts that cannot be foreseen or otherwise
  3166. // forbidden, so just skip them.
  3167. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3168. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig))) {
  3169. Type *src_exact = x->type;
  3170. Type *dst_exact = type;
  3171. if (src_exact != nullptr &&
  3172. dst_exact != nullptr &&
  3173. are_types_identical(src_exact, dst_exact)
  3174. ) {
  3175. gbString oper_str = expr_to_string(x->expr);
  3176. gbString to_type = type_to_string(dst_exact);
  3177. error(x->expr, "Unneeded cast of '%s' to identical type '%s'", oper_str, to_type);
  3178. gb_string_free(oper_str);
  3179. gb_string_free(to_type);
  3180. }
  3181. }
  3182. }
  3183. x->type = type;
  3184. }
  3185. gb_internal bool check_transmute(CheckerContext *c, Ast *node, Operand *o, Type *t, bool forbid_identical = false) {
  3186. if (!is_operand_value(*o)) {
  3187. error(o->expr, "'transmute' can only be applied to values");
  3188. o->mode = Addressing_Invalid;
  3189. return false;
  3190. }
  3191. Operand src = *o;
  3192. Type *src_t = o->type;
  3193. Type *dst_t = t;
  3194. Type *src_bt = base_type(src_t);
  3195. Type *dst_bt = base_type(dst_t);
  3196. if (is_type_untyped(src_t)) {
  3197. gbString expr_str = expr_to_string(o->expr);
  3198. error(o->expr, "Cannot transmute untyped expression: '%s'", expr_str);
  3199. gb_string_free(expr_str);
  3200. o->mode = Addressing_Invalid;
  3201. o->expr = node;
  3202. return false;
  3203. }
  3204. if (dst_bt == nullptr || dst_bt == t_invalid) {
  3205. GB_ASSERT(global_error_collector.count != 0);
  3206. o->mode = Addressing_Invalid;
  3207. o->expr = node;
  3208. return false;
  3209. }
  3210. if (src_bt == nullptr || src_bt == t_invalid) {
  3211. // NOTE(bill): this should be an error
  3212. GB_ASSERT(global_error_collector.count != 0);
  3213. o->mode = Addressing_Value;
  3214. o->expr = node;
  3215. o->type = dst_t;
  3216. return true;
  3217. }
  3218. i64 srcz = type_size_of(src_t);
  3219. i64 dstz = type_size_of(dst_t);
  3220. if (srcz != dstz) {
  3221. gbString expr_str = expr_to_string(o->expr);
  3222. gbString type_str = type_to_string(dst_t);
  3223. error(o->expr, "Cannot transmute '%s' to '%s', %lld vs %lld bytes", expr_str, type_str, srcz, dstz);
  3224. gb_string_free(type_str);
  3225. gb_string_free(expr_str);
  3226. o->mode = Addressing_Invalid;
  3227. o->expr = node;
  3228. return false;
  3229. }
  3230. o->expr = node;
  3231. o->type = dst_t;
  3232. if (o->mode == Addressing_Constant) {
  3233. if (are_types_identical(src_bt, dst_bt)) {
  3234. return true;
  3235. }
  3236. if ((is_type_integer(src_t) && is_type_integer(dst_t)) ||
  3237. is_type_integer(src_t) && is_type_bit_set(dst_t)) {
  3238. if (types_have_same_internal_endian(src_t, dst_t)) {
  3239. ExactValue src_v = exact_value_to_integer(o->value);
  3240. GB_ASSERT(src_v.kind == ExactValue_Integer || src_v.kind == ExactValue_Invalid);
  3241. BigInt v = src_v.value_integer;
  3242. BigInt smax = {};
  3243. BigInt umax = {};
  3244. big_int_from_u64(&smax, 0);
  3245. big_int_not(&smax, &smax, cast(i32)(srcz*8 - 1), false);
  3246. big_int_from_u64(&umax, 1);
  3247. BigInt sz_in_bits = big_int_make_i64(srcz*8);
  3248. big_int_shl_eq(&umax, &sz_in_bits);
  3249. if (is_type_unsigned(src_t) && !is_type_unsigned(dst_t)) {
  3250. if (big_int_cmp(&v, &smax) >= 0) {
  3251. big_int_sub_eq(&v, &umax);
  3252. }
  3253. } else if (!is_type_unsigned(src_t) && is_type_unsigned(dst_t)) {
  3254. if (big_int_is_neg(&v)) {
  3255. big_int_add_eq(&v, &umax);
  3256. }
  3257. }
  3258. o->value.kind = ExactValue_Integer;
  3259. o->value.value_integer = v;
  3260. return true;
  3261. }
  3262. }
  3263. } else {
  3264. // If we check polymorphic procedures, we risk erring on
  3265. // identical casts that cannot be foreseen or otherwise
  3266. // forbidden, so just skip them.
  3267. if (forbid_identical && check_vet_flags(c) & VetFlag_Cast &&
  3268. (c->curr_proc_sig == nullptr || !is_type_polymorphic(c->curr_proc_sig)) &&
  3269. check_is_castable_to(c, &src, dst_t)) {
  3270. if (are_types_identical(src_t, dst_t)) {
  3271. gbString oper_str = expr_to_string(o->expr);
  3272. gbString to_type = type_to_string(dst_t);
  3273. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3274. gb_string_free(oper_str);
  3275. gb_string_free(to_type);
  3276. } else if (is_type_internally_pointer_like(src_t) &&
  3277. is_type_internally_pointer_like(dst_t)) {
  3278. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since the types are pointer-like");
  3279. } else if (are_types_identical(src_bt, dst_bt)) {
  3280. gbString oper_str = expr_to_string(o->expr);
  3281. gbString to_type = type_to_string(dst_t);
  3282. error(o->expr, "Unneeded transmute of '%s' to identical type '%s'", oper_str, to_type);
  3283. gb_string_free(oper_str);
  3284. gb_string_free(to_type);
  3285. } else if (is_type_integer(src_t) && is_type_integer(dst_t) &&
  3286. types_have_same_internal_endian(src_t, dst_t) &&
  3287. type_endian_kind_of(src_t) == type_endian_kind_of(dst_t)) {
  3288. gbString oper_type = type_to_string(src_t);
  3289. gbString to_type = type_to_string(dst_t);
  3290. error(o->expr, "Use of 'transmute' where 'cast' would be preferred since both are integers of the same endianness, from '%s' to '%s'", oper_type, to_type);
  3291. gb_string_free(to_type);
  3292. gb_string_free(oper_type);
  3293. }
  3294. }
  3295. }
  3296. o->mode = Addressing_Value;
  3297. o->value = {};
  3298. return true;
  3299. }
  3300. gb_internal bool check_binary_array_expr(CheckerContext *c, Token op, Operand *x, Operand *y) {
  3301. if (is_type_array_like(x->type) || is_type_array_like(y->type)) {
  3302. if (op.kind == Token_CmpAnd || op.kind == Token_CmpOr) {
  3303. error(op, "Array programming is not allowed with the operator '%.*s'", LIT(op.string));
  3304. }
  3305. }
  3306. if (is_type_array(x->type) && !is_type_array(y->type)) {
  3307. if (check_is_assignable_to(c, y, x->type)) {
  3308. if (check_binary_op(c, x, op)) {
  3309. return true;
  3310. }
  3311. }
  3312. }
  3313. if (is_type_simd_vector(x->type) && !is_type_simd_vector(y->type)) {
  3314. if (check_is_assignable_to(c, y, x->type)) {
  3315. if (check_binary_op(c, x, op)) {
  3316. return true;
  3317. }
  3318. }
  3319. }
  3320. return false;
  3321. }
  3322. gb_internal bool is_ise_expr(Ast *node) {
  3323. node = unparen_expr(node);
  3324. return node->kind == Ast_ImplicitSelectorExpr;
  3325. }
  3326. gb_internal bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type) {
  3327. if (use_lhs_as_type_hint) { // RHS in this case
  3328. return other_type != nullptr && other_type != t_invalid && is_type_typed(other_type);
  3329. }
  3330. return false;
  3331. }
  3332. gb_internal Type *check_matrix_type_hint(Type *matrix, Type *type_hint) {
  3333. Type *xt = base_type(matrix);
  3334. if (type_hint != nullptr) {
  3335. Type *th = base_type(type_hint);
  3336. if (are_types_identical(th, xt)) {
  3337. return type_hint;
  3338. } else if (xt->kind == Type_Matrix && th->kind == Type_Matrix) {
  3339. if (!are_types_identical(xt->Matrix.elem, th->Matrix.elem)) {
  3340. // ignore
  3341. } if (xt->Matrix.row_count == th->Matrix.row_count &&
  3342. xt->Matrix.column_count == th->Matrix.column_count) {
  3343. return type_hint;
  3344. }
  3345. } else if (xt->kind == Type_Matrix && th->kind == Type_Array) {
  3346. if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) {
  3347. // ignore
  3348. } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) {
  3349. return type_hint;
  3350. } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) {
  3351. return type_hint;
  3352. }
  3353. }
  3354. }
  3355. return matrix;
  3356. }
  3357. gb_internal void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) {
  3358. if (!check_binary_op(c, x, op)) {
  3359. x->mode = Addressing_Invalid;
  3360. return;
  3361. }
  3362. Type *xt = base_type(x->type);
  3363. Type *yt = base_type(y->type);
  3364. if (is_type_matrix(x->type)) {
  3365. GB_ASSERT(xt->kind == Type_Matrix);
  3366. if (op.kind == Token_Mul) {
  3367. if (yt->kind == Type_Matrix) {
  3368. if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) {
  3369. goto matrix_error;
  3370. }
  3371. if (xt->Matrix.column_count != yt->Matrix.row_count) {
  3372. goto matrix_error;
  3373. }
  3374. if (xt->Matrix.is_row_major != yt->Matrix.is_row_major) {
  3375. goto matrix_error;
  3376. }
  3377. x->mode = Addressing_Value;
  3378. if (are_types_identical(xt, yt)) {
  3379. if (are_types_identical(x->type, y->type)) {
  3380. return;
  3381. }
  3382. if (!is_type_named(x->type) && is_type_named(y->type)) {
  3383. // prefer the named type
  3384. x->type = y->type;
  3385. }
  3386. } else {
  3387. bool is_row_major = xt->Matrix.is_row_major && yt->Matrix.is_row_major;
  3388. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count, nullptr, nullptr, is_row_major);
  3389. }
  3390. goto matrix_success;
  3391. } else if (yt->kind == Type_Array) {
  3392. if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) {
  3393. goto matrix_error;
  3394. }
  3395. if (xt->Matrix.column_count != yt->Array.count) {
  3396. goto matrix_error;
  3397. }
  3398. // Treat arrays as column vectors
  3399. x->mode = Addressing_Value;
  3400. if (xt->Matrix.row_count == yt->Array.count) {
  3401. x->type = y->type;
  3402. } else {
  3403. x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1, nullptr, nullptr, xt->Matrix.is_row_major);
  3404. }
  3405. goto matrix_success;
  3406. }
  3407. }
  3408. if (!are_types_identical(xt, yt)) {
  3409. goto matrix_error;
  3410. }
  3411. x->mode = Addressing_Value;
  3412. x->type = xt;
  3413. goto matrix_success;
  3414. } else {
  3415. GB_ASSERT(!is_type_matrix(xt));
  3416. GB_ASSERT(is_type_matrix(yt));
  3417. if (op.kind == Token_Mul) {
  3418. // NOTE(bill): no need to handle the matrix case here since it should be handled above
  3419. if (xt->kind == Type_Array) {
  3420. if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) {
  3421. goto matrix_error;
  3422. }
  3423. if (xt->Array.count != yt->Matrix.row_count) {
  3424. goto matrix_error;
  3425. }
  3426. // Treat arrays as row vectors
  3427. x->mode = Addressing_Value;
  3428. if (yt->Matrix.column_count == xt->Array.count) {
  3429. x->type = x->type;
  3430. } else {
  3431. x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count, nullptr, nullptr, yt->Matrix.is_row_major);
  3432. }
  3433. goto matrix_success;
  3434. } else if (are_types_identical(yt->Matrix.elem, xt)) {
  3435. x->type = check_matrix_type_hint(y->type, type_hint);
  3436. return;
  3437. }
  3438. }
  3439. if (!are_types_identical(xt, yt)) {
  3440. goto matrix_error;
  3441. }
  3442. x->mode = Addressing_Value;
  3443. x->type = xt;
  3444. goto matrix_success;
  3445. }
  3446. matrix_success:
  3447. x->type = check_matrix_type_hint(x->type, type_hint);
  3448. return;
  3449. matrix_error:
  3450. gbString xts = type_to_string(x->type);
  3451. gbString yts = type_to_string(y->type);
  3452. gbString expr_str = expr_to_string(x->expr);
  3453. error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts);
  3454. gb_string_free(expr_str);
  3455. gb_string_free(yts);
  3456. gb_string_free(xts);
  3457. x->type = t_invalid;
  3458. x->mode = Addressing_Invalid;
  3459. return;
  3460. }
  3461. gb_internal void check_binary_expr_dependency(CheckerContext *c, Token op, Type *bt, bool REQUIRE) {
  3462. if (op.kind == Token_Mod || op.kind == Token_ModEq ||
  3463. op.kind == Token_ModMod || op.kind == Token_ModModEq) {
  3464. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3465. case Basic_u128: add_package_dependency(c, "runtime", "umodti3", REQUIRE); break;
  3466. case Basic_i128: add_package_dependency(c, "runtime", "modti3", REQUIRE); break;
  3467. }
  3468. } else if (op.kind == Token_Quo || op.kind == Token_QuoEq) {
  3469. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3470. case Basic_complex32: add_package_dependency(c, "runtime", "quo_complex32"); break;
  3471. case Basic_complex64: add_package_dependency(c, "runtime", "quo_complex64"); break;
  3472. case Basic_complex128: add_package_dependency(c, "runtime", "quo_complex128"); break;
  3473. case Basic_quaternion64: add_package_dependency(c, "runtime", "quo_quaternion64"); break;
  3474. case Basic_quaternion128: add_package_dependency(c, "runtime", "quo_quaternion128"); break;
  3475. case Basic_quaternion256: add_package_dependency(c, "runtime", "quo_quaternion256"); break;
  3476. case Basic_u128: add_package_dependency(c, "runtime", "udivti3", REQUIRE); break;
  3477. case Basic_i128: add_package_dependency(c, "runtime", "divti3", REQUIRE); break;
  3478. }
  3479. } else if (op.kind == Token_Mul || op.kind == Token_MulEq) {
  3480. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3481. case Basic_quaternion64: add_package_dependency(c, "runtime", "mul_quaternion64"); break;
  3482. case Basic_quaternion128: add_package_dependency(c, "runtime", "mul_quaternion128"); break;
  3483. case Basic_quaternion256: add_package_dependency(c, "runtime", "mul_quaternion256"); break;
  3484. case Basic_u128:
  3485. case Basic_i128:
  3486. if (is_arch_wasm()) {
  3487. add_package_dependency(c, "runtime", "__multi3", REQUIRE);
  3488. }
  3489. break;
  3490. }
  3491. } else if (op.kind == Token_Shl || op.kind == Token_ShlEq) {
  3492. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3493. case Basic_u128:
  3494. case Basic_i128:
  3495. if (is_arch_wasm()) {
  3496. add_package_dependency(c, "runtime", "__ashlti3", REQUIRE);
  3497. }
  3498. break;
  3499. }
  3500. } else if (op.kind == Token_Shr || op.kind == Token_ShrEq) {
  3501. if (bt->kind == Type_Basic) switch (bt->Basic.kind) {
  3502. case Basic_u128:
  3503. case Basic_i128:
  3504. if (is_arch_wasm()) {
  3505. add_package_dependency(c, "runtime", "__lshrti3", REQUIRE);
  3506. }
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. gb_internal void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) {
  3512. GB_ASSERT(node->kind == Ast_BinaryExpr);
  3513. Operand y_ = {}, *y = &y_;
  3514. ast_node(be, BinaryExpr, node);
  3515. defer({
  3516. node->viral_state_flags |= be->left->viral_state_flags;
  3517. node->viral_state_flags |= be->right->viral_state_flags;
  3518. });
  3519. Token op = be->op;
  3520. switch (op.kind) {
  3521. case Token_CmpEq:
  3522. case Token_NotEq: {
  3523. // NOTE(bill): Allow comparisons between types
  3524. if (is_ise_expr(be->left)) {
  3525. // Evalute the right before the left for an '.X' expression
  3526. check_expr_or_type(c, y, be->right, nullptr /* ignore type hint */);
  3527. check_expr_or_type(c, x, be->left, y->type);
  3528. } else {
  3529. check_expr_or_type(c, x, be->left, nullptr /* ignore type hint */);
  3530. check_expr_or_type(c, y, be->right, x->type);
  3531. }
  3532. bool xt = x->mode == Addressing_Type;
  3533. bool yt = y->mode == Addressing_Type;
  3534. // If only one is a type, this is an error
  3535. if (xt ^ yt) {
  3536. GB_ASSERT(xt != yt);
  3537. if (xt) {
  3538. if (!is_type_typeid(y->type)) {
  3539. error_operand_not_expression(x);
  3540. }
  3541. }
  3542. if (yt) {
  3543. if (!is_type_typeid(x->type)) {
  3544. error_operand_not_expression(y);
  3545. }
  3546. }
  3547. }
  3548. break;
  3549. }
  3550. case Token_in:
  3551. case Token_not_in:
  3552. {
  3553. // IMPORTANT NOTE(bill): This uses right-left evaluation in type checking only no in
  3554. check_expr(c, y, be->right);
  3555. Type *rhs_type = type_deref(y->type);
  3556. if (rhs_type == nullptr) {
  3557. error(y->expr, "Cannot use '%.*s' on an expression with no value", LIT(op.string));
  3558. x->mode = Addressing_Invalid;
  3559. x->expr = node;
  3560. return;
  3561. }
  3562. if (is_type_bit_set(rhs_type)) {
  3563. Type *elem = base_type(rhs_type)->BitSet.elem;
  3564. check_expr_with_type_hint(c, x, be->left, elem);
  3565. } else if (is_type_map(rhs_type)) {
  3566. Type *key = base_type(rhs_type)->Map.key;
  3567. check_expr_with_type_hint(c, x, be->left, key);
  3568. } else {
  3569. check_expr(c, x, be->left);
  3570. }
  3571. if (x->mode == Addressing_Invalid) {
  3572. return;
  3573. }
  3574. if (y->mode == Addressing_Invalid) {
  3575. x->mode = Addressing_Invalid;
  3576. x->expr = y->expr;
  3577. return;
  3578. }
  3579. if (is_type_map(rhs_type)) {
  3580. Type *yt = base_type(rhs_type);
  3581. if (op.kind == Token_in) {
  3582. check_assignment(c, x, yt->Map.key, str_lit("map 'in'"));
  3583. } else {
  3584. check_assignment(c, x, yt->Map.key, str_lit("map 'not_in'"));
  3585. }
  3586. add_map_get_dependencies(c);
  3587. } else if (is_type_bit_set(rhs_type)) {
  3588. Type *yt = base_type(rhs_type);
  3589. if (op.kind == Token_in) {
  3590. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'in'"));
  3591. } else {
  3592. check_assignment(c, x, yt->BitSet.elem, str_lit("bit_set 'not_in'"));
  3593. }
  3594. if (x->mode == Addressing_Constant && y->mode == Addressing_Constant) {
  3595. ExactValue k = exact_value_to_integer(x->value);
  3596. ExactValue v = exact_value_to_integer(y->value);
  3597. GB_ASSERT(k.kind == ExactValue_Integer);
  3598. GB_ASSERT(v.kind == ExactValue_Integer);
  3599. i64 key = big_int_to_i64(&k.value_integer);
  3600. i64 lower = yt->BitSet.lower;
  3601. i64 upper = yt->BitSet.upper;
  3602. if (lower <= key && key <= upper) {
  3603. i64 bit = 1ll<<key;
  3604. i64 bits = big_int_to_i64(&v.value_integer);
  3605. x->mode = Addressing_Constant;
  3606. x->type = t_untyped_bool;
  3607. if (op.kind == Token_in) {
  3608. x->value = exact_value_bool((bit & bits) != 0);
  3609. } else {
  3610. x->value = exact_value_bool((bit & bits) == 0);
  3611. }
  3612. x->expr = node;
  3613. return;
  3614. } else {
  3615. error(x->expr, "key '%lld' out of range of bit set, %lld..%lld", key, lower, upper);
  3616. x->mode = Addressing_Invalid;
  3617. }
  3618. }
  3619. } else {
  3620. gbString t = type_to_string(y->type);
  3621. error(x->expr, "expected either a map or bitset for 'in', got %s", t);
  3622. gb_string_free(t);
  3623. x->expr = node;
  3624. x->mode = Addressing_Invalid;
  3625. return;
  3626. }
  3627. if (x->mode != Addressing_Invalid) {
  3628. x->mode = Addressing_Value;
  3629. x->type = t_untyped_bool;
  3630. }
  3631. x->expr = node;
  3632. return;
  3633. }
  3634. default:
  3635. if (is_ise_expr(be->left)) {
  3636. // Evalute the right before the left for an '.X' expression
  3637. check_expr_or_type(c, y, be->right, type_hint);
  3638. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, y->type)) { // RHS in this case
  3639. check_expr_or_type(c, x, be->left, y->type);
  3640. } else {
  3641. check_expr_with_type_hint(c, x, be->left, type_hint);
  3642. }
  3643. } else {
  3644. check_expr_with_type_hint(c, x, be->left, type_hint);
  3645. if (can_use_other_type_as_type_hint(use_lhs_as_type_hint, x->type)) {
  3646. check_expr_with_type_hint(c, y, be->right, x->type);
  3647. } else {
  3648. check_expr_with_type_hint(c, y, be->right, type_hint);
  3649. }
  3650. }
  3651. break;
  3652. }
  3653. if (x->mode == Addressing_Invalid) {
  3654. return;
  3655. }
  3656. if (y->mode == Addressing_Invalid) {
  3657. x->mode = Addressing_Invalid;
  3658. x->expr = y->expr;
  3659. return;
  3660. }
  3661. if (x->mode == Addressing_Builtin) {
  3662. x->mode = Addressing_Invalid;
  3663. error(x->expr, "built-in expression in binary expression");
  3664. return;
  3665. }
  3666. if (y->mode == Addressing_Builtin) {
  3667. x->mode = Addressing_Invalid;
  3668. error(y->expr, "built-in expression in binary expression");
  3669. return;
  3670. }
  3671. if (x->mode == Addressing_ProcGroup) {
  3672. x->mode = Addressing_Invalid;
  3673. if (x->proc_group != nullptr) {
  3674. error(x->expr, "procedure group '%.*s' used in binary expression", LIT(x->proc_group->token.string));
  3675. } else {
  3676. error(x->expr, "procedure group used in binary expression");
  3677. }
  3678. return;
  3679. }
  3680. if (y->mode == Addressing_ProcGroup) {
  3681. x->mode = Addressing_Invalid;
  3682. if (x->proc_group != nullptr) {
  3683. error(y->expr, "procedure group '%.*s' used in binary expression", LIT(y->proc_group->token.string));
  3684. } else {
  3685. error(y->expr, "procedure group used in binary expression");
  3686. }
  3687. return;
  3688. }
  3689. bool REQUIRE = true;
  3690. Type *btx = base_type(x->type);
  3691. Type *bty = base_type(y->type);
  3692. check_binary_expr_dependency(c, op, btx, REQUIRE);
  3693. check_binary_expr_dependency(c, op, bty, REQUIRE);
  3694. if (token_is_shift(op.kind)) {
  3695. check_shift(c, x, y, node, type_hint);
  3696. return;
  3697. }
  3698. switch (op.kind) {
  3699. case Token_Quo:
  3700. case Token_Mod:
  3701. case Token_ModMod:
  3702. case Token_QuoEq:
  3703. case Token_ModEq:
  3704. case Token_ModModEq:
  3705. if (is_type_integer(y->type) && !is_type_untyped(y->type) &&
  3706. is_type_float(x->type) && is_type_untyped(x->type)) {
  3707. char const *suggestion = "\tSuggestion: Try explicitly casting the constant value for clarity";
  3708. gbString t = type_to_string(y->type);
  3709. if (x->value.kind != ExactValue_Invalid) {
  3710. gbString s = exact_value_to_string(x->value);
  3711. warning(node, "Dividing an untyped float '%s' by '%s' will perform integer division\n%s", s, t, suggestion);
  3712. gb_string_free(s);
  3713. } else {
  3714. warning(node, "Dividing an untyped float by '%s' will perform integer division\n%s", t, suggestion);
  3715. }
  3716. gb_string_free(t);
  3717. }
  3718. break;
  3719. }
  3720. convert_to_typed(c, x, y->type);
  3721. if (x->mode == Addressing_Invalid) {
  3722. return;
  3723. }
  3724. convert_to_typed(c, y, x->type);
  3725. if (y->mode == Addressing_Invalid) {
  3726. x->mode = Addressing_Invalid;
  3727. return;
  3728. }
  3729. if (token_is_comparison(op.kind)) {
  3730. check_comparison(c, node, x, y, op.kind);
  3731. return;
  3732. }
  3733. if (check_binary_array_expr(c, op, x, y)) {
  3734. x->mode = Addressing_Value;
  3735. x->type = x->type;
  3736. return;
  3737. }
  3738. if (check_binary_array_expr(c, op, y, x)) {
  3739. x->mode = Addressing_Value;
  3740. x->type = y->type;
  3741. return;
  3742. }
  3743. if (is_type_matrix(x->type) || is_type_matrix(y->type)) {
  3744. check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint);
  3745. x->expr = node;
  3746. return;
  3747. }
  3748. if ((op.kind == Token_CmpAnd || op.kind == Token_CmpOr) &&
  3749. is_type_boolean(x->type) && is_type_boolean(y->type)) {
  3750. // NOTE(bill, 2022-06-26)
  3751. // Allow any boolean types within `&&` and `||`
  3752. // This is an exception to all other binary expressions since the result
  3753. // of a comparison will always be an untyped boolean, and allowing
  3754. // any boolean between these two simplifies a lot of expressions
  3755. } else if (!are_types_identical(x->type, y->type)) {
  3756. if (x->type != t_invalid &&
  3757. y->type != t_invalid) {
  3758. gbString xt = type_to_string(x->type);
  3759. gbString yt = type_to_string(y->type);
  3760. gbString expr_str = expr_to_string(node);
  3761. error(op, "Mismatched types in binary expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  3762. gb_string_free(expr_str);
  3763. gb_string_free(yt);
  3764. gb_string_free(xt);
  3765. }
  3766. x->mode = Addressing_Invalid;
  3767. return;
  3768. }
  3769. if (!check_binary_op(c, x, op)) {
  3770. x->mode = Addressing_Invalid;
  3771. return;
  3772. }
  3773. switch (op.kind) {
  3774. case Token_Quo:
  3775. case Token_Mod:
  3776. case Token_ModMod:
  3777. case Token_QuoEq:
  3778. case Token_ModEq:
  3779. case Token_ModModEq:
  3780. if ((x->mode == Addressing_Constant || is_type_integer(x->type)) &&
  3781. y->mode == Addressing_Constant) {
  3782. bool fail = false;
  3783. switch (y->value.kind) {
  3784. case ExactValue_Integer:
  3785. if (big_int_is_zero(&y->value.value_integer)) {
  3786. fail = true;
  3787. }
  3788. break;
  3789. case ExactValue_Float:
  3790. if (y->value.value_float == 0.0) {
  3791. fail = true;
  3792. }
  3793. break;
  3794. }
  3795. if (fail) {
  3796. if (is_type_integer(x->type) || (x->mode == Addressing_Constant && x->value.kind == ExactValue_Integer)) {
  3797. if (check_for_integer_division_by_zero(c, node) == IntegerDivisionByZero_Zero) {
  3798. // Okay
  3799. break;
  3800. }
  3801. }
  3802. switch (op.kind) {
  3803. case Token_Mod:
  3804. case Token_ModMod:
  3805. case Token_ModEq:
  3806. case Token_ModModEq:
  3807. error(y->expr, "Division by zero through '%.*s' not allowed", LIT(token_strings[op.kind]));
  3808. break;
  3809. case Token_Quo:
  3810. case Token_QuoEq:
  3811. error(y->expr, "Division by zero not allowed");
  3812. break;
  3813. }
  3814. x->mode = Addressing_Invalid;
  3815. return;
  3816. }
  3817. }
  3818. break;
  3819. case Token_CmpAnd:
  3820. case Token_CmpOr:
  3821. if (be->left->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3822. error(be->left, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3823. }
  3824. if (be->right->viral_state_flags & ViralStateFlag_ContainsDeferredProcedure) {
  3825. error(be->right, "Procedure calls that have an associated deferred procedure are not allowed within logical binary expressions");
  3826. }
  3827. break;
  3828. }
  3829. if (x->mode == Addressing_Constant &&
  3830. y->mode == Addressing_Constant) {
  3831. ExactValue a = x->value;
  3832. ExactValue b = y->value;
  3833. if (!is_type_constant_type(x->type)) {
  3834. x->mode = Addressing_Value;
  3835. return;
  3836. }
  3837. if (op.kind == Token_Quo && is_type_integer(x->type)) {
  3838. op.kind = Token_QuoEq; // NOTE(bill): Hack to get division of integers
  3839. }
  3840. if (is_type_bit_set(x->type)) {
  3841. switch (op.kind) {
  3842. case Token_Add: op.kind = Token_Or; break;
  3843. case Token_Sub: op.kind = Token_AndNot; break;
  3844. }
  3845. }
  3846. match_exact_values(&a, &b);
  3847. if (check_for_integer_division_by_zero(c, node) == IntegerDivisionByZero_Zero &&
  3848. b.kind == ExactValue_Integer && big_int_is_zero(&b.value_integer) &&
  3849. (op.kind == Token_QuoEq || op.kind == Token_Mod || op.kind == Token_ModMod)) {
  3850. if (op.kind == Token_QuoEq) {
  3851. // x/0 == 0
  3852. x->value = b;
  3853. } else {
  3854. // x%0 == x
  3855. /*
  3856. NOTE(bill): @integer division by zero rules
  3857. truncated: r = a - b*trunc(a/b)
  3858. floored: r = a - b*floor(a/b)
  3859. IFF a/0 == 0, then (a%0 == a) or (a%%0 == a)
  3860. */
  3861. x->value = a;
  3862. }
  3863. } else {
  3864. x->value = exact_binary_operator_value(op.kind, a, b);
  3865. }
  3866. if (is_type_typed(x->type)) {
  3867. if (node != nullptr) {
  3868. x->expr = node;
  3869. }
  3870. check_is_expressible(c, x, x->type);
  3871. }
  3872. return;
  3873. } else if (is_type_string(x->type)) {
  3874. error(node, "String concatenation is only allowed with constant strings");
  3875. x->mode = Addressing_Invalid;
  3876. return;
  3877. }
  3878. x->mode = Addressing_Value;
  3879. }
  3880. gb_internal Operand make_operand_from_node(Ast *node) {
  3881. GB_ASSERT(node != nullptr);
  3882. Operand x = {};
  3883. x.expr = node;
  3884. x.mode = node->tav.mode;
  3885. x.type = node->tav.type;
  3886. x.value = node->tav.value;
  3887. return x;
  3888. }
  3889. gb_internal void update_untyped_expr_type(CheckerContext *c, Ast *e, Type *type, bool final) {
  3890. GB_ASSERT(e != nullptr);
  3891. ExprInfo *old = check_get_expr_info(c, e);
  3892. if (old == nullptr) {
  3893. if (type != nullptr && type != t_invalid) {
  3894. if (e->tav.type == nullptr || e->tav.type == t_invalid) {
  3895. add_type_and_value(c, e, e->tav.mode, type ? type : e->tav.type, e->tav.value);
  3896. if (e->kind == Ast_TernaryIfExpr) {
  3897. update_untyped_expr_type(c, e->TernaryIfExpr.x, type, final);
  3898. update_untyped_expr_type(c, e->TernaryIfExpr.y, type, final);
  3899. }
  3900. }
  3901. }
  3902. return;
  3903. }
  3904. switch (e->kind) {
  3905. case_ast_node(ue, UnaryExpr, e);
  3906. if (old->value.kind != ExactValue_Invalid) {
  3907. // NOTE(bill): if 'e' is constant, the operands will be constant too.
  3908. // They don't need to be updated as they will be updated later and
  3909. // checked at the end of general checking stage.
  3910. break;
  3911. }
  3912. update_untyped_expr_type(c, ue->expr, type, final);
  3913. case_end;
  3914. case_ast_node(be, BinaryExpr, e);
  3915. if (old->value.kind != ExactValue_Invalid) {
  3916. // See above note in UnaryExpr case
  3917. break;
  3918. }
  3919. if (token_is_comparison(be->op.kind)) {
  3920. // NOTE(bill): Do nothing as the types are fine
  3921. } else if (token_is_shift(be->op.kind)) {
  3922. update_untyped_expr_type(c, be->left, type, final);
  3923. } else {
  3924. update_untyped_expr_type(c, be->left, type, final);
  3925. update_untyped_expr_type(c, be->right, type, final);
  3926. }
  3927. case_end;
  3928. case_ast_node(te, TernaryIfExpr, e);
  3929. if (old->value.kind != ExactValue_Invalid) {
  3930. // See above note in UnaryExpr case
  3931. break;
  3932. }
  3933. // NOTE(bill): This is a bit of a hack to get around the edge cases of ternary if expressions
  3934. // having an untyped value
  3935. Operand x = make_operand_from_node(te->x);
  3936. Operand y = make_operand_from_node(te->y);
  3937. if (x.mode != Addressing_Constant || check_is_expressible(c, &x, type)) {
  3938. update_untyped_expr_type(c, te->x, type, final);
  3939. }
  3940. if (y.mode != Addressing_Constant || check_is_expressible(c, &y, type)) {
  3941. update_untyped_expr_type(c, te->y, type, final);
  3942. }
  3943. case_end;
  3944. case_ast_node(te, TernaryWhenExpr, e);
  3945. if (old->value.kind != ExactValue_Invalid) {
  3946. // See above note in UnaryExpr case
  3947. break;
  3948. }
  3949. update_untyped_expr_type(c, te->x, type, final);
  3950. update_untyped_expr_type(c, te->y, type, final);
  3951. case_end;
  3952. case_ast_node(ore, OrReturnExpr, e);
  3953. if (old->value.kind != ExactValue_Invalid) {
  3954. // See above note in UnaryExpr case
  3955. break;
  3956. }
  3957. update_untyped_expr_type(c, ore->expr, type, final);
  3958. case_end;
  3959. case_ast_node(obe, OrBranchExpr, e);
  3960. if (old->value.kind != ExactValue_Invalid) {
  3961. // See above note in UnaryExpr case
  3962. break;
  3963. }
  3964. update_untyped_expr_type(c, obe->expr, type, final);
  3965. case_end;
  3966. case_ast_node(oee, OrElseExpr, e);
  3967. if (old->value.kind != ExactValue_Invalid) {
  3968. // See above note in UnaryExpr case
  3969. break;
  3970. }
  3971. update_untyped_expr_type(c, oee->x, type, final);
  3972. update_untyped_expr_type(c, oee->y, type, final);
  3973. case_end;
  3974. case_ast_node(pe, ParenExpr, e);
  3975. update_untyped_expr_type(c, pe->expr, type, final);
  3976. case_end;
  3977. }
  3978. if (!final && is_type_untyped(type)) {
  3979. old->type = base_type(type);
  3980. return;
  3981. }
  3982. // We need to remove it and then give it a new one
  3983. check_remove_expr_info(c, e);
  3984. if (old->is_lhs && !is_type_integer(type)) {
  3985. gbString expr_str = expr_to_string(e);
  3986. gbString type_str = type_to_string(type);
  3987. error(e, "Shifted operand %s must be an integer, got %s", expr_str, type_str);
  3988. gb_string_free(type_str);
  3989. gb_string_free(expr_str);
  3990. return;
  3991. }
  3992. add_type_and_value(c, e, old->mode, type, old->value);
  3993. }
  3994. gb_internal void update_untyped_expr_value(CheckerContext *c, Ast *e, ExactValue value) {
  3995. GB_ASSERT(e != nullptr);
  3996. ExprInfo *found = check_get_expr_info(c, e);
  3997. if (found) {
  3998. found->value = value;
  3999. }
  4000. }
  4001. gb_internal void convert_untyped_error(CheckerContext *c, Operand *operand, Type *target_type, bool ignore_error_block=false) {
  4002. gbString expr_str = expr_to_string(operand->expr);
  4003. gbString type_str = type_to_string(target_type);
  4004. gbString from_type_str = type_to_string(operand->type);
  4005. char const *extra_text = "";
  4006. if (operand->mode == Addressing_Constant) {
  4007. if (big_int_is_zero(&operand->value.value_integer)) {
  4008. if (make_string_c(expr_str) != "nil") { // HACK NOTE(bill): Just in case
  4009. // NOTE(bill): Doesn't matter what the type is as it's still zero in the union
  4010. extra_text = " - Did you want 'nil'?";
  4011. }
  4012. }
  4013. }
  4014. if (!ignore_error_block) {
  4015. begin_error_block();
  4016. }
  4017. error(operand->expr, "Cannot convert untyped value '%s' to '%s' from '%s'%s", expr_str, type_str, from_type_str, extra_text);
  4018. if (operand->value.kind == ExactValue_String) {
  4019. String key = operand->value.value_string;
  4020. if (is_type_string(operand->type) && is_type_enum(target_type)) {
  4021. Type *et = base_type(target_type);
  4022. check_did_you_mean_type(key, et->Enum.fields, ".");
  4023. }
  4024. }
  4025. gb_string_free(from_type_str);
  4026. gb_string_free(type_str);
  4027. gb_string_free(expr_str);
  4028. operand->mode = Addressing_Invalid;
  4029. if (!ignore_error_block) {
  4030. end_error_block();
  4031. }
  4032. }
  4033. gb_internal ExactValue convert_exact_value_for_type(ExactValue v, Type *type) {
  4034. Type *t = core_type(type);
  4035. if (is_type_boolean(t)) {
  4036. // v = exact_value_to_boolean(v);
  4037. } else if (is_type_float(t)) {
  4038. v = exact_value_to_float(v);
  4039. } else if (is_type_integer(t)) {
  4040. v = exact_value_to_integer(v);
  4041. } else if (is_type_pointer(t)) {
  4042. v = exact_value_to_integer(v);
  4043. } else if (is_type_complex(t)) {
  4044. v = exact_value_to_complex(v);
  4045. } else if (is_type_quaternion(t)) {
  4046. v = exact_value_to_quaternion(v);
  4047. }
  4048. return v;
  4049. }
  4050. gb_internal void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) {
  4051. // GB_ASSERT_NOT_NULL(target_type);
  4052. if (target_type == nullptr || operand->mode == Addressing_Invalid ||
  4053. operand->mode == Addressing_Type ||
  4054. is_type_typed(operand->type) ||
  4055. target_type == t_invalid) {
  4056. return;
  4057. }
  4058. if (is_type_untyped(target_type)) {
  4059. GB_ASSERT(operand->type->kind == Type_Basic);
  4060. GB_ASSERT(target_type->kind == Type_Basic);
  4061. BasicKind x_kind = operand->type->Basic.kind;
  4062. BasicKind y_kind = target_type->Basic.kind;
  4063. if (is_type_numeric(operand->type) && is_type_numeric(target_type)) {
  4064. if (x_kind < y_kind) {
  4065. operand->type = target_type;
  4066. update_untyped_expr_type(c, operand->expr, target_type, false);
  4067. }
  4068. } else if (x_kind != y_kind) {
  4069. operand->mode = Addressing_Invalid;
  4070. convert_untyped_error(c, operand, target_type);
  4071. return;
  4072. }
  4073. return;
  4074. }
  4075. Type *t = base_type(target_type);
  4076. if (c->in_enum_type) {
  4077. t = core_type(target_type);
  4078. }
  4079. switch (t->kind) {
  4080. case Type_Basic:
  4081. if (operand->mode == Addressing_Constant) {
  4082. check_is_expressible(c, operand, t);
  4083. if (operand->mode == Addressing_Invalid) {
  4084. return;
  4085. }
  4086. update_untyped_expr_value(c, operand->expr, operand->value);
  4087. } else {
  4088. switch (operand->type->Basic.kind) {
  4089. case Basic_UntypedBool:
  4090. if (!is_type_boolean(target_type)) {
  4091. operand->mode = Addressing_Invalid;
  4092. convert_untyped_error(c, operand, target_type);
  4093. return;
  4094. }
  4095. break;
  4096. case Basic_UntypedInteger:
  4097. case Basic_UntypedFloat:
  4098. case Basic_UntypedComplex:
  4099. case Basic_UntypedQuaternion:
  4100. case Basic_UntypedRune:
  4101. if (!is_type_numeric(target_type)) {
  4102. operand->mode = Addressing_Invalid;
  4103. convert_untyped_error(c, operand, target_type);
  4104. return;
  4105. }
  4106. break;
  4107. case Basic_UntypedNil:
  4108. if (is_type_any(target_type)) {
  4109. // target_type = t_untyped_nil;
  4110. } else if (is_type_cstring(target_type)) {
  4111. // target_type = t_untyped_nil;
  4112. } else if (is_type_cstring16(target_type)) {
  4113. // target_type = t_untyped_nil;
  4114. } else if (!type_has_nil(target_type)) {
  4115. operand->mode = Addressing_Invalid;
  4116. convert_untyped_error(c, operand, target_type);
  4117. return;
  4118. }
  4119. break;
  4120. }
  4121. }
  4122. break;
  4123. case Type_Array: {
  4124. Type *elem = base_array_type(t);
  4125. if (check_is_assignable_to(c, operand, elem)) {
  4126. operand->mode = Addressing_Value;
  4127. } else {
  4128. if (operand->value.kind == ExactValue_String) {
  4129. String s = operand->value.value_string;
  4130. if (is_type_u8_array(t)) {
  4131. if (s.len == t->Array.count) {
  4132. break;
  4133. }
  4134. } else if (is_type_rune_array(t)) {
  4135. isize rune_count = gb_utf8_strnlen(s.text, s.len);
  4136. if (rune_count == t->Array.count) {
  4137. break;
  4138. }
  4139. }
  4140. } else if (operand->value.kind == ExactValue_String16) {
  4141. String16 s = operand->value.value_string16;
  4142. if (is_type_u16_array(t)) {
  4143. if (s.len == t->Array.count) {
  4144. break;
  4145. }
  4146. }
  4147. }
  4148. operand->mode = Addressing_Invalid;
  4149. convert_untyped_error(c, operand, target_type);
  4150. return;
  4151. }
  4152. break;
  4153. }
  4154. case Type_SimdVector: {
  4155. Type *elem = base_array_type(t);
  4156. if (check_is_assignable_to(c, operand, elem)) {
  4157. operand->mode = Addressing_Value;
  4158. } else {
  4159. operand->mode = Addressing_Invalid;
  4160. convert_untyped_error(c, operand, target_type);
  4161. return;
  4162. }
  4163. break;
  4164. }
  4165. case Type_Matrix: {
  4166. Type *elem = base_array_type(t);
  4167. if (check_is_assignable_to(c, operand, elem)) {
  4168. if (t->Matrix.row_count != t->Matrix.column_count) {
  4169. operand->mode = Addressing_Invalid;
  4170. ERROR_BLOCK();
  4171. convert_untyped_error(c, operand, target_type, true);
  4172. error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n");
  4173. return;
  4174. } else {
  4175. operand->mode = Addressing_Value;
  4176. }
  4177. } else {
  4178. operand->mode = Addressing_Invalid;
  4179. convert_untyped_error(c, operand, target_type);
  4180. return;
  4181. }
  4182. break;
  4183. }
  4184. case Type_Union:
  4185. // IMPORTANT NOTE HACK(bill): This is just to allow for comparisons against `0` with the `os.Error` type
  4186. // as a kind of transition period
  4187. if (!build_context.strict_style &&
  4188. operand->mode == Addressing_Constant &&
  4189. target_type->kind == Type_Named &&
  4190. (c->pkg == nullptr || c->pkg->name != "os") &&
  4191. target_type->Named.name == "Error") {
  4192. Entity *e = target_type->Named.type_name;
  4193. if (e->pkg && e->pkg->name == "os") {
  4194. if (is_exact_value_zero(operand->value) &&
  4195. (operand->value.kind == ExactValue_Integer ||
  4196. operand->value.kind == ExactValue_Float)) {
  4197. operand->mode = Addressing_Value;
  4198. // target_type = t_untyped_nil;
  4199. operand->value = empty_exact_value;
  4200. update_untyped_expr_value(c, operand->expr, operand->value);
  4201. break;
  4202. }
  4203. }
  4204. }
  4205. // "fallthrough"
  4206. if (!is_operand_nil(*operand) && !is_operand_uninit(*operand)) {
  4207. TEMPORARY_ALLOCATOR_GUARD();
  4208. isize count = t->Union.variants.count;
  4209. ValidIndexAndScore *valids = gb_alloc_array(temporary_allocator(), ValidIndexAndScore, count);
  4210. isize valid_count = 0;
  4211. isize first_success_index = -1;
  4212. for_array(i, t->Union.variants) {
  4213. Type *vt = t->Union.variants[i];
  4214. i64 score = 0;
  4215. if (check_is_assignable_to_with_score(c, operand, vt, &score)) {
  4216. valids[valid_count].index = i;
  4217. valids[valid_count].score = score;
  4218. valid_count += 1;
  4219. if (first_success_index < 0) {
  4220. first_success_index = i;
  4221. }
  4222. }
  4223. }
  4224. if (valid_count > 1) {
  4225. gb_sort_array(valids, valid_count, valid_index_and_score_cmp);
  4226. i64 best_score = valids[0].score;
  4227. for (isize i = 1; i < valid_count; i++) {
  4228. auto v = valids[i];
  4229. if (best_score > v.score) {
  4230. valid_count = i;
  4231. break;
  4232. }
  4233. best_score = v.score;
  4234. }
  4235. first_success_index = valids[0].index;
  4236. }
  4237. gbString type_str = type_to_string(target_type);
  4238. defer (gb_string_free(type_str));
  4239. if (valid_count == 1) {
  4240. Type *new_type = t->Union.variants[first_success_index];
  4241. target_type = new_type;
  4242. if (is_type_union(new_type)) {
  4243. convert_to_typed(c, operand, new_type);
  4244. break;
  4245. }
  4246. operand->type = new_type;
  4247. operand->mode = Addressing_Value;
  4248. break;
  4249. } else if (valid_count > 1) {
  4250. ERROR_BLOCK();
  4251. GB_ASSERT(first_success_index >= 0);
  4252. operand->mode = Addressing_Invalid;
  4253. convert_untyped_error(c, operand, target_type, true);
  4254. error_line("Ambiguous type conversion to '%s', which variant did you mean:\n\t", type_str);
  4255. i32 j = 0;
  4256. for (i32 i = 0; i < valid_count; i++) {
  4257. ValidIndexAndScore valid = valids[i];
  4258. if (j > 0 && valid_count > 2) error_line(", ");
  4259. if (j == valid_count-1) {
  4260. if (valid_count == 2) error_line(" ");
  4261. error_line("or ");
  4262. }
  4263. gbString str = type_to_string(t->Union.variants[valid.index]);
  4264. error_line("'%s'", str);
  4265. gb_string_free(str);
  4266. j++;
  4267. }
  4268. error_line("\n\n");
  4269. return;
  4270. } else if (is_type_untyped_uninit(operand->type)) {
  4271. target_type = t_untyped_uninit;
  4272. } else if (!is_type_untyped_nil(operand->type) || !type_has_nil(target_type)) {
  4273. ERROR_BLOCK();
  4274. operand->mode = Addressing_Invalid;
  4275. convert_untyped_error(c, operand, target_type, true);
  4276. if (count > 0) {
  4277. error_line("'%s' is a union which only excepts the following types:\n", type_str);
  4278. error_line("\t");
  4279. for (i32 i = 0; i < count; i++) {
  4280. Type *v = t->Union.variants[i];
  4281. if (i > 0 && count > 2) error_line(", ");
  4282. if (i == count-1) {
  4283. if (count == 2) error_line(" ");
  4284. if (count > 1) {
  4285. error_line("or ");
  4286. }
  4287. }
  4288. gbString str = type_to_string(v);
  4289. error_line("'%s'", str);
  4290. gb_string_free(str);
  4291. }
  4292. error_line("\n\n");
  4293. }
  4294. return;
  4295. }
  4296. }
  4297. /* fallthrough */
  4298. default:
  4299. if (is_type_untyped_uninit(operand->type)) {
  4300. target_type = t_untyped_uninit;
  4301. } else if (is_type_untyped_nil(operand->type) && type_has_nil(target_type)) {
  4302. target_type = t_untyped_nil;
  4303. } else {
  4304. operand->mode = Addressing_Invalid;
  4305. convert_untyped_error(c, operand, target_type);
  4306. return;
  4307. }
  4308. break;
  4309. }
  4310. if (is_type_any(target_type) && is_type_untyped(operand->type)) {
  4311. if (is_type_untyped_nil(operand->type) && is_type_untyped_uninit(operand->type)) {
  4312. } else {
  4313. target_type = default_type(operand->type);
  4314. }
  4315. }
  4316. update_untyped_expr_type(c, operand->expr, target_type, true);
  4317. operand->type = target_type;
  4318. }
  4319. 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) {
  4320. Operand operand = {Addressing_Invalid};
  4321. check_expr_with_type_hint(c, &operand, index_value, type_hint);
  4322. if (operand.mode == Addressing_Invalid) {
  4323. if (value) *value = 0;
  4324. // NOTE(bill): return true here to propagate the errors better
  4325. return true;
  4326. }
  4327. Type *index_type = t_int;
  4328. if (type_hint != nullptr) {
  4329. index_type = type_hint;
  4330. }
  4331. convert_to_typed(c, &operand, index_type);
  4332. if (operand.mode == Addressing_Invalid) {
  4333. if (value) *value = 0;
  4334. return false;
  4335. }
  4336. if (type_hint != nullptr) {
  4337. if (!check_is_assignable_to(c, &operand, type_hint)) {
  4338. gbString expr_str = expr_to_string(operand.expr);
  4339. gbString index_type_str = type_to_string(type_hint);
  4340. error(operand.expr, "Index '%s' must be an enum of type '%s'", expr_str, index_type_str);
  4341. gb_string_free(index_type_str);
  4342. gb_string_free(expr_str);
  4343. if (value) *value = 0;
  4344. return false;
  4345. }
  4346. } else if (!is_type_integer(operand.type) && !is_type_enum(operand.type)) {
  4347. gbString expr_str = expr_to_string(operand.expr);
  4348. gbString type_str = type_to_string(operand.type);
  4349. error(operand.expr, "Index '%s' must be an integer, got %s", expr_str, type_str);
  4350. gb_string_free(type_str);
  4351. gb_string_free(expr_str);
  4352. if (value) *value = 0;
  4353. return false;
  4354. }
  4355. if (operand.mode == Addressing_Constant &&
  4356. (c->state_flags & StateFlag_no_bounds_check) == 0) {
  4357. BigInt i = exact_value_to_integer(operand.value).value_integer;
  4358. if (i.sign && !is_type_enum(index_type) && !is_type_multi_pointer(main_type)) {
  4359. TEMPORARY_ALLOCATOR_GUARD();
  4360. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4361. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4362. error(operand.expr, "Index '%s' cannot be a negative value, got %.*s", expr_str, LIT(idx_str));
  4363. if (value) *value = 0;
  4364. return false;
  4365. }
  4366. if (max_count >= 0) {
  4367. if (is_type_enum(index_type)) {
  4368. Type *bt = base_type(index_type);
  4369. GB_ASSERT(bt->kind == Type_Enum);
  4370. ExactValue const &lo = *bt->Enum.min_value;
  4371. ExactValue const &hi = *bt->Enum.max_value;
  4372. String lo_str = {};
  4373. String hi_str = {};
  4374. if (bt->Enum.fields.count > 0) {
  4375. isize lo_idx = gb_clamp(bt->Enum.min_value_index, 0, bt->Enum.fields.count - 1);
  4376. isize hi_idx = gb_clamp(bt->Enum.max_value_index, 0, bt->Enum.fields.count - 1);
  4377. lo_str = bt->Enum.fields[lo_idx]->token.string;
  4378. hi_str = bt->Enum.fields[hi_idx]->token.string;
  4379. }
  4380. bool out_of_bounds = false;
  4381. if (compare_exact_values(Token_Lt, operand.value, lo) || compare_exact_values(Token_Gt, operand.value, hi)) {
  4382. out_of_bounds = true;
  4383. }
  4384. if (out_of_bounds) {
  4385. gbString expr_str = expr_to_string(operand.expr);
  4386. if (lo_str.len > 0) {
  4387. error(operand.expr, "Index '%s' is out of bounds range %.*s ..= %.*s", expr_str, LIT(lo_str), LIT(hi_str));
  4388. } else {
  4389. gbString index_type_str = type_to_string(index_type);
  4390. error(operand.expr, "Index '%s' is out of bounds range of enum type %s", expr_str, index_type_str);
  4391. gb_string_free(index_type_str);
  4392. }
  4393. gb_string_free(expr_str);
  4394. return false;
  4395. }
  4396. if (value) *value = exact_value_to_i64(exact_value_sub(operand.value, lo));
  4397. return true;
  4398. } else { // NOTE(bill): Do array bound checking
  4399. i64 v = -1;
  4400. if (i.used <= 1) {
  4401. v = big_int_to_i64(&i);
  4402. }
  4403. if (value) *value = v;
  4404. bool out_of_bounds = false;
  4405. if (v < 0) {
  4406. out_of_bounds = true;
  4407. } else if (open_range) {
  4408. out_of_bounds = v > max_count;
  4409. } else {
  4410. out_of_bounds = v >= max_count;
  4411. }
  4412. if (out_of_bounds) {
  4413. TEMPORARY_ALLOCATOR_GUARD();
  4414. String idx_str = big_int_to_string(temporary_allocator(), &i);
  4415. gbString expr_str = expr_to_string(operand.expr, temporary_allocator());
  4416. error(operand.expr, "Index '%s' is out of bounds range 0..<%lld, got %.*s", expr_str, max_count, LIT(idx_str));
  4417. return false;
  4418. }
  4419. return true;
  4420. }
  4421. } else {
  4422. if (value) *value = exact_value_to_i64(operand.value);
  4423. return true;
  4424. }
  4425. }
  4426. // NOTE(bill): It's alright :D
  4427. if (value) *value = -1;
  4428. return true;
  4429. }
  4430. gb_internal ExactValue get_constant_field_single(CheckerContext *c, ExactValue value, i32 index, bool *success_, bool *finish_) {
  4431. if (value.kind == ExactValue_String) {
  4432. GB_ASSERT(0 <= index && index < value.value_string.len);
  4433. u8 val = value.value_string[index];
  4434. if (success_) *success_ = true;
  4435. if (finish_) *finish_ = true;
  4436. return exact_value_u64(val);
  4437. } else if (value.kind == ExactValue_String16) {
  4438. GB_ASSERT(0 <= index && index < value.value_string.len);
  4439. u16 val = value.value_string16[index];
  4440. if (success_) *success_ = true;
  4441. if (finish_) *finish_ = true;
  4442. return exact_value_u64(val);
  4443. }
  4444. if (value.kind != ExactValue_Compound) {
  4445. if (success_) *success_ = true;
  4446. if (finish_) *finish_ = true;
  4447. return value;
  4448. }
  4449. Ast *node = value.value_compound;
  4450. switch (node->kind) {
  4451. case_ast_node(cl, CompoundLit, node);
  4452. if (cl->elems.count == 0) {
  4453. if (success_) *success_ = true;
  4454. if (finish_) *finish_ = true;
  4455. return empty_exact_value;
  4456. }
  4457. if (cl->elems[0]->kind == Ast_FieldValue) {
  4458. if (is_type_struct(node->tav.type)) {
  4459. bool found = false;
  4460. for (Ast *elem : cl->elems) {
  4461. if (elem->kind != Ast_FieldValue) {
  4462. continue;
  4463. }
  4464. ast_node(fv, FieldValue, elem);
  4465. String name = fv->field->Ident.token.string;
  4466. Selection sub_sel = lookup_field(node->tav.type, name, false);
  4467. defer (array_free(&sub_sel.index));
  4468. if (sub_sel.index.count > 0 &&
  4469. sub_sel.index[0] == index) {
  4470. value = fv->value->tav.value;
  4471. found = true;
  4472. break;
  4473. }
  4474. }
  4475. if (!found) {
  4476. // Use the zero value if it is not found
  4477. value = {};
  4478. }
  4479. } else if (is_type_array(node->tav.type) || is_type_enumerated_array(node->tav.type)) {
  4480. for (Ast *elem : cl->elems) {
  4481. if (elem->kind != Ast_FieldValue) {
  4482. continue;
  4483. }
  4484. ast_node(fv, FieldValue, elem);
  4485. if (is_ast_range(fv->field)) {
  4486. ast_node(ie, BinaryExpr, fv->field);
  4487. TypeAndValue lo_tav = ie->left->tav;
  4488. TypeAndValue hi_tav = ie->right->tav;
  4489. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4490. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4491. TokenKind op = ie->op.kind;
  4492. i64 lo = exact_value_to_i64(lo_tav.value);
  4493. i64 hi = exact_value_to_i64(hi_tav.value);
  4494. i64 corrected_index = index;
  4495. if (is_type_enumerated_array(node->tav.type)) {
  4496. Type *bt = base_type(node->tav.type);
  4497. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4498. corrected_index = index + exact_value_to_i64(*bt->EnumeratedArray.min_value);
  4499. }
  4500. if (op != Token_RangeHalf) {
  4501. if (lo <= corrected_index && corrected_index <= hi) {
  4502. TypeAndValue tav = fv->value->tav;
  4503. if (success_) *success_ = true;
  4504. if (finish_) *finish_ = false;
  4505. return tav.value;
  4506. }
  4507. } else {
  4508. if (lo <= corrected_index && corrected_index < hi) {
  4509. TypeAndValue tav = fv->value->tav;
  4510. if (success_) *success_ = true;
  4511. if (finish_) *finish_ = false;
  4512. return tav.value;
  4513. }
  4514. }
  4515. } else {
  4516. TypeAndValue index_tav = fv->field->tav;
  4517. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4518. ExactValue index_value = index_tav.value;
  4519. if (is_type_enumerated_array(node->tav.type)) {
  4520. Type *bt = base_type(node->tav.type);
  4521. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  4522. index_value = exact_value_sub(index_value, *bt->EnumeratedArray.min_value);
  4523. }
  4524. i64 field_index = exact_value_to_i64(index_value);
  4525. if (index == field_index) {
  4526. TypeAndValue tav = fv->value->tav;
  4527. if (success_) *success_ = true;
  4528. if (finish_) *finish_ = false;
  4529. return tav.value;
  4530. }
  4531. }
  4532. }
  4533. }
  4534. } else {
  4535. i32 count = (i32)cl->elems.count;
  4536. if (count < index) {
  4537. if (success_) *success_ = false;
  4538. if (finish_) *finish_ = true;
  4539. return empty_exact_value;
  4540. }
  4541. if (cl->elems.count <= index) {
  4542. if (success_) *success_ = false;
  4543. if (finish_) *finish_ = false;
  4544. return value;
  4545. }
  4546. TypeAndValue tav = cl->elems[index]->tav;
  4547. if (tav.mode == Addressing_Constant) {
  4548. if (success_) *success_ = true;
  4549. if (finish_) *finish_ = false;
  4550. return tav.value;
  4551. } else if (is_type_proc(tav.type)) {
  4552. if (success_) *success_ = true;
  4553. if (finish_) *finish_ = false;
  4554. return tav.value;
  4555. } else {
  4556. GB_ASSERT_MSG(is_type_untyped_nil(tav.type), "%s", type_to_string(tav.type));
  4557. if (success_) *success_ = true;
  4558. if (finish_) *finish_ = false;
  4559. return tav.value;
  4560. }
  4561. }
  4562. case_end;
  4563. default:
  4564. if (success_) *success_ = true;
  4565. if (finish_) *finish_ = true;
  4566. return empty_exact_value;
  4567. }
  4568. if (finish_) *finish_ = false;
  4569. return value;
  4570. }
  4571. gb_internal ExactValue get_constant_field(CheckerContext *c, Operand const *operand, Selection sel, bool *success_) {
  4572. if (operand->mode != Addressing_Constant) {
  4573. if (success_) *success_ = false;
  4574. return empty_exact_value;
  4575. }
  4576. if (sel.indirect) {
  4577. if (success_) *success_ = false;
  4578. return empty_exact_value;
  4579. }
  4580. if (sel.index.count == 0) {
  4581. if (success_) *success_ = false;
  4582. return empty_exact_value;
  4583. }
  4584. ExactValue value = operand->value;
  4585. if (value.kind == ExactValue_Compound) {
  4586. while (sel.index.count > 0) {
  4587. i32 index = sel.index[0];
  4588. sel = sub_selection(sel, 1);
  4589. bool finish = false;
  4590. value = get_constant_field_single(c, value, index, success_, &finish);
  4591. if (finish) {
  4592. return value;
  4593. }
  4594. }
  4595. if (success_) *success_ = true;
  4596. return value;
  4597. } else if (value.kind == ExactValue_Quaternion) {
  4598. // @QuaternionLayout
  4599. Quaternion256 q = *value.value_quaternion;
  4600. GB_ASSERT(sel.index.count == 1);
  4601. switch (sel.index[0]) {
  4602. case 3: // w
  4603. if (success_) *success_ = true;
  4604. return exact_value_float(q.real);
  4605. case 0: // x
  4606. if (success_) *success_ = true;
  4607. return exact_value_float(q.imag);
  4608. case 1: // y
  4609. if (success_) *success_ = true;
  4610. return exact_value_float(q.jmag);
  4611. case 2: // z
  4612. if (success_) *success_ = true;
  4613. return exact_value_float(q.kmag);
  4614. }
  4615. if (success_) *success_ = false;
  4616. return empty_exact_value;
  4617. } else if (value.kind == ExactValue_Complex) {
  4618. // @QuaternionLayout
  4619. Complex128 c = *value.value_complex;
  4620. GB_ASSERT(sel.index.count == 1);
  4621. switch (sel.index[0]) {
  4622. case 0: // real
  4623. if (success_) *success_ = true;
  4624. return exact_value_float(c.real);
  4625. case 1: // imag
  4626. if (success_) *success_ = true;
  4627. return exact_value_float(c.imag);
  4628. }
  4629. if (success_) *success_ = false;
  4630. return empty_exact_value;
  4631. }
  4632. if (success_) *success_ = true;
  4633. return empty_exact_value;
  4634. }
  4635. gb_internal Type *determine_swizzle_array_type(Type *original_type, Type *type_hint, isize new_count) {
  4636. Type *array_type = base_type(type_deref(original_type));
  4637. GB_ASSERT(array_type->kind == Type_Array || array_type->kind == Type_SimdVector);
  4638. if (array_type->kind == Type_SimdVector) {
  4639. Type *elem_type = array_type->SimdVector.elem;
  4640. return alloc_type_simd_vector(new_count, elem_type);
  4641. }
  4642. Type *elem_type = array_type->Array.elem;
  4643. Type *swizzle_array_type = nullptr;
  4644. Type *bth = base_type(type_deref(type_hint));
  4645. if (bth != nullptr && bth->kind == Type_Array &&
  4646. bth->Array.count == new_count &&
  4647. are_types_identical(bth->Array.elem, elem_type)) {
  4648. swizzle_array_type = type_hint;
  4649. } else {
  4650. i64 max_count = array_type->Array.count;
  4651. if (new_count == max_count) {
  4652. swizzle_array_type = original_type;
  4653. } else {
  4654. swizzle_array_type = alloc_type_array(elem_type, new_count);
  4655. }
  4656. }
  4657. return swizzle_array_type;
  4658. }
  4659. gb_internal bool is_entity_declared_for_selector(Entity *entity, Scope *import_scope, bool *allow_builtin) {
  4660. bool is_declared = entity != nullptr;
  4661. if (is_declared) {
  4662. if (entity->kind == Entity_Builtin) {
  4663. // NOTE(bill): Builtin's are in the universal scope which is part of every scopes hierarchy
  4664. // This means that we should just ignore the found result through it
  4665. *allow_builtin = entity->scope == import_scope ||
  4666. (entity->scope != builtin_pkg->scope && entity->scope != intrinsics_pkg->scope);
  4667. } else if ((entity->scope->flags&ScopeFlag_Global) == ScopeFlag_Global && (import_scope->flags&ScopeFlag_Global) == 0) {
  4668. is_declared = false;
  4669. }
  4670. }
  4671. return is_declared;
  4672. }
  4673. // NOTE(bill, 2022-02-03): see `check_const_decl` for why it exists reasoning
  4674. gb_internal Entity *check_entity_from_ident_or_selector(CheckerContext *c, Ast *node, bool ident_only) {
  4675. if (node == nullptr) {
  4676. return nullptr;
  4677. }
  4678. /*if (node->kind == Ast_TernaryWhenExpr) {
  4679. ast_node(we, TernaryWhenExpr, node);
  4680. if (we->cond == nullptr) {
  4681. return nullptr;
  4682. }
  4683. if (we->cond->tav.mode != Addressing_Constant) {
  4684. return nullptr;
  4685. }
  4686. if (we->cond->tav.value.kind != ExactValue_Bool) {
  4687. return nullptr;
  4688. }
  4689. if (we->cond->tav.value.value_bool) {
  4690. return check_entity_from_ident_or_selector(c, we->x, ident_only);
  4691. } else {
  4692. Entity *e = check_entity_from_ident_or_selector(c, we->y, ident_only);
  4693. return e;
  4694. }
  4695. } else */if (node->kind == Ast_Ident) {
  4696. String name = node->Ident.token.string;
  4697. return scope_lookup(c->scope, name);
  4698. } else if (!ident_only) if (node->kind == Ast_SelectorExpr) {
  4699. ast_node(se, SelectorExpr, node);
  4700. if (se->token.kind == Token_ArrowRight) {
  4701. return nullptr;
  4702. }
  4703. Ast *op_expr = se->expr;
  4704. Ast *selector = unparen_expr(se->selector);
  4705. if (selector == nullptr) {
  4706. return nullptr;
  4707. }
  4708. if (selector->kind != Ast_Ident) {
  4709. return nullptr;
  4710. }
  4711. Entity *entity = nullptr;
  4712. Entity *expr_entity = nullptr;
  4713. bool check_op_expr = true;
  4714. if (op_expr->kind == Ast_Ident) {
  4715. String op_name = op_expr->Ident.token.string;
  4716. Entity *e = scope_lookup(c->scope, op_name);
  4717. if (e == nullptr) {
  4718. return nullptr;
  4719. }
  4720. add_entity_use(c, op_expr, e);
  4721. expr_entity = e;
  4722. if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4723. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4724. // It pretty much needs to be in this order and this way
  4725. // If you can clean this up, please do but be really careful
  4726. String import_name = op_name;
  4727. Scope *import_scope = e->ImportName.scope;
  4728. String entity_name = selector->Ident.token.string;
  4729. check_op_expr = false;
  4730. entity = scope_lookup_current(import_scope, entity_name);
  4731. bool allow_builtin = false;
  4732. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4733. return nullptr;
  4734. }
  4735. check_entity_decl(c, entity, nullptr, nullptr);
  4736. if (entity->kind == Entity_ProcGroup) {
  4737. return entity;
  4738. }
  4739. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4740. }
  4741. }
  4742. Operand operand = {};
  4743. if (check_op_expr) {
  4744. check_expr_base(c, &operand, op_expr, nullptr);
  4745. if (operand.mode == Addressing_Invalid) {
  4746. return nullptr;
  4747. }
  4748. }
  4749. if (entity == nullptr && selector->kind == Ast_Ident) {
  4750. String field_name = selector->Ident.token.string;
  4751. if (is_type_dynamic_array(type_deref(operand.type))) {
  4752. init_mem_allocator(c->checker);
  4753. }
  4754. auto sel = lookup_field(operand.type, field_name, operand.mode == Addressing_Type);
  4755. entity = sel.entity;
  4756. }
  4757. if (entity != nullptr) {
  4758. return entity;
  4759. }
  4760. }
  4761. return nullptr;
  4762. }
  4763. gb_internal Entity *check_selector(CheckerContext *c, Operand *operand, Ast *node, Type *type_hint) {
  4764. ast_node(se, SelectorExpr, node);
  4765. bool check_op_expr = true;
  4766. Entity *expr_entity = nullptr;
  4767. Entity *entity = nullptr;
  4768. Selection sel = {}; // NOTE(bill): Not used if it's an import name
  4769. if (!c->allow_arrow_right_selector_expr && se->token.kind == Token_ArrowRight) {
  4770. ERROR_BLOCK();
  4771. error(node, "Illegal use of -> selector shorthand outside of a call");
  4772. gbString x = expr_to_string(se->expr);
  4773. gbString y = expr_to_string(se->selector);
  4774. error_line("\tSuggestion: Did you mean '%s.%s'?\n", x, y);
  4775. gb_string_free(y);
  4776. gb_string_free(x);
  4777. // TODO(bill): Should this terminate here or propagate onwards?
  4778. // operand->mode = Addressing_Invalid;
  4779. // operand->expr = node;
  4780. // return nullptr;
  4781. }
  4782. operand->expr = node;
  4783. Ast *op_expr = se->expr;
  4784. Ast *selector = unparen_expr(se->selector);
  4785. if (selector == nullptr) {
  4786. operand->mode = Addressing_Invalid;
  4787. operand->expr = node;
  4788. return nullptr;
  4789. }
  4790. if (selector->kind != Ast_Ident) {
  4791. error(selector, "Illegal selector kind: '%.*s'", LIT(ast_strings[selector->kind]));
  4792. operand->mode = Addressing_Invalid;
  4793. operand->expr = node;
  4794. return nullptr;
  4795. }
  4796. if (op_expr->kind == Ast_Ident) {
  4797. String op_name = op_expr->Ident.token.string;
  4798. Entity *e = scope_lookup(c->scope, op_name);
  4799. add_entity_use(c, op_expr, e);
  4800. expr_entity = e;
  4801. if (e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup) && selector->kind == Ast_Ident) {
  4802. gbString sel_str = expr_to_string(selector);
  4803. error(node, "'%s' is not declared by by '%.*s'", sel_str, LIT(e->token.string));
  4804. gb_string_free(sel_str);
  4805. operand->mode = Addressing_Invalid;
  4806. operand->expr = node;
  4807. return nullptr;
  4808. } else if (e != nullptr && e->kind == Entity_ImportName && selector->kind == Ast_Ident) {
  4809. // IMPORTANT NOTE(bill): This is very sloppy code but it's also very fragile
  4810. // It pretty much needs to be in this order and this way
  4811. // If you can clean this up, please do but be really careful
  4812. String import_name = op_name;
  4813. Scope *import_scope = e->ImportName.scope;
  4814. String entity_name = selector->Ident.token.string;
  4815. if (import_scope == nullptr) {
  4816. ERROR_BLOCK();
  4817. error(node, "'%.*s' is not imported in this file, '%.*s' is unavailable", LIT(import_name), LIT(entity_name));
  4818. operand->mode = Addressing_Invalid;
  4819. operand->expr = node;
  4820. return nullptr;
  4821. }
  4822. check_op_expr = false;
  4823. entity = scope_lookup_current(import_scope, entity_name);
  4824. bool allow_builtin = false;
  4825. if (!is_entity_declared_for_selector(entity, import_scope, &allow_builtin)) {
  4826. ERROR_BLOCK();
  4827. error(node, "'%.*s' is not declared by '%.*s'", LIT(entity_name), LIT(import_name));
  4828. operand->mode = Addressing_Invalid;
  4829. operand->expr = node;
  4830. check_did_you_mean_scope(entity_name, import_scope);
  4831. return nullptr;
  4832. }
  4833. if (!is_entity_exported(entity, allow_builtin)) {
  4834. gbString sel_str = expr_to_string(selector);
  4835. error(node, "'%s' is not exported by '%.*s'", sel_str, LIT(import_name));
  4836. gb_string_free(sel_str);
  4837. // NOTE(bill): make the state valid still, even if it's "invalid"
  4838. // operand->mode = Addressing_Invalid;
  4839. // operand->expr = node;
  4840. // return nullptr;
  4841. }
  4842. check_entity_decl(c, entity, nullptr, nullptr);
  4843. if (entity->kind == Entity_ProcGroup) {
  4844. operand->mode = Addressing_ProcGroup;
  4845. operand->proc_group = entity;
  4846. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4847. return entity;
  4848. }
  4849. GB_ASSERT_MSG(entity->type != nullptr, "%.*s (%.*s)", LIT(entity->token.string), LIT(entity_strings[entity->kind]));
  4850. }
  4851. }
  4852. if (check_op_expr) {
  4853. check_expr_base(c, operand, op_expr, nullptr);
  4854. if (operand->mode == Addressing_Invalid) {
  4855. operand->mode = Addressing_Invalid;
  4856. operand->expr = node;
  4857. return nullptr;
  4858. }
  4859. }
  4860. if (operand->type && is_type_soa_struct(type_deref(operand->type))) {
  4861. complete_soa_type(c->checker, type_deref(operand->type), false);
  4862. }
  4863. if (entity == nullptr && selector->kind == Ast_Ident) {
  4864. String field_name = selector->Ident.token.string;
  4865. Type *t = type_deref(operand->type);
  4866. if (t == nullptr) {
  4867. error(operand->expr, "Cannot use a selector expression on 0-value expression");
  4868. } else {
  4869. if (is_type_dynamic_array(t)) {
  4870. init_mem_allocator(c->checker);
  4871. }
  4872. sel = lookup_field(operand->type, field_name, operand->mode == Addressing_Type);
  4873. entity = sel.entity;
  4874. // NOTE(bill): Add type info needed for fields like 'names'
  4875. if (entity != nullptr && (entity->flags&EntityFlag_TypeField)) {
  4876. add_type_info_type(c, operand->type);
  4877. }
  4878. if (is_type_enum(operand->type)) {
  4879. add_type_info_type(c, operand->type);
  4880. }
  4881. }
  4882. }
  4883. if (operand->type && is_type_simd_vector(type_deref(operand->type))) {
  4884. String field_name = selector->Ident.token.string;
  4885. if (field_name.len == 1) {
  4886. error(op_expr, "Extracting an element from a #simd array using .%.*s syntax is disallowed, prefer `simd.extract`", LIT(field_name));
  4887. } else {
  4888. error(op_expr, "Extracting elements from a #simd array using .%.*s syntax is disallowed, prefer `swizzle`", LIT(field_name));
  4889. }
  4890. return nullptr;
  4891. }
  4892. if (entity == nullptr && selector->kind == Ast_Ident && operand->type != nullptr &&
  4893. (is_type_array(type_deref(operand->type)))) {
  4894. String field_name = selector->Ident.token.string;
  4895. if (1 < field_name.len && field_name.len <= 4) {
  4896. u8 swizzles_xyzw[4] = {'x', 'y', 'z', 'w'};
  4897. u8 swizzles_rgba[4] = {'r', 'g', 'b', 'a'};
  4898. bool found_xyzw = false;
  4899. bool found_rgba = false;
  4900. for (isize i = 0; i < field_name.len; i++) {
  4901. bool valid = false;
  4902. for (isize j = 0; j < 4; j++) {
  4903. if (field_name.text[i] == swizzles_xyzw[j]) {
  4904. found_xyzw = true;
  4905. valid = true;
  4906. break;
  4907. }
  4908. if (field_name.text[i] == swizzles_rgba[j]) {
  4909. found_rgba = true;
  4910. valid = true;
  4911. break;
  4912. }
  4913. }
  4914. if (!valid) {
  4915. goto end_of_array_selector_swizzle;
  4916. }
  4917. }
  4918. u8 *swizzles = nullptr;
  4919. u8 index_count = cast(u8)field_name.len;
  4920. if (found_xyzw && found_rgba) {
  4921. gbString op_str = expr_to_string(op_expr);
  4922. error(op_expr, "Mixture of swizzle kinds for field index, got %s", op_str);
  4923. gb_string_free(op_str);
  4924. operand->mode = Addressing_Invalid;
  4925. operand->expr = node;
  4926. return nullptr;
  4927. }
  4928. u8 indices = 0;
  4929. if (found_xyzw) {
  4930. swizzles = swizzles_xyzw;
  4931. } else if (found_rgba) {
  4932. swizzles = swizzles_rgba;
  4933. }
  4934. for (isize i = 0; i < field_name.len; i++) {
  4935. for (isize j = 0; j < 4; j++) {
  4936. if (field_name.text[i] == swizzles[j]) {
  4937. indices |= cast(u8)(j)<<(i*2);
  4938. break;
  4939. }
  4940. }
  4941. }
  4942. Type *original_type = operand->type;
  4943. Type *array_type = base_type(type_deref(original_type));
  4944. GB_ASSERT(array_type->kind == Type_Array);
  4945. i64 array_count = get_array_type_count(array_type);
  4946. for (u8 i = 0; i < index_count; i++) {
  4947. u8 idx = indices>>(i*2) & 3;
  4948. if (idx >= array_count) {
  4949. char c = 0;
  4950. if (found_xyzw) {
  4951. c = swizzles_xyzw[idx];
  4952. } else if (found_rgba) {
  4953. c = swizzles_rgba[idx];
  4954. } else {
  4955. GB_PANIC("unknown swizzle kind");
  4956. }
  4957. error(selector->Ident.token, "Swizzle value is out of bounds, got %c, max count %lld", c, array_count);
  4958. break;
  4959. }
  4960. }
  4961. se->swizzle_count = index_count;
  4962. se->swizzle_indices = indices;
  4963. AddressingMode prev_mode = operand->mode;
  4964. operand->mode = Addressing_SwizzleValue;
  4965. operand->type = determine_swizzle_array_type(original_type, type_hint, index_count);
  4966. operand->expr = node;
  4967. switch (prev_mode) {
  4968. case Addressing_Variable:
  4969. case Addressing_SoaVariable:
  4970. case Addressing_SwizzleVariable:
  4971. operand->mode = Addressing_SwizzleVariable;
  4972. break;
  4973. case Addressing_Value:
  4974. if (is_type_pointer(original_type)) {
  4975. operand->mode = Addressing_SwizzleVariable;
  4976. }
  4977. break;
  4978. }
  4979. Entity *swizzle_entity = alloc_entity_variable(nullptr, make_token_ident(field_name), operand->type, EntityState_Resolved);
  4980. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  4981. return swizzle_entity;
  4982. }
  4983. end_of_array_selector_swizzle:;
  4984. }
  4985. if (entity == nullptr) {
  4986. gbString op_str = expr_to_string(op_expr);
  4987. gbString type_str = type_to_string_shorthand(operand->type);
  4988. gbString sel_str = expr_to_string(selector);
  4989. if (operand->mode == Addressing_Type) {
  4990. if (is_type_polymorphic(operand->type, true)) {
  4991. error(op_expr, "Type '%s' has no field nor polymorphic parameter '%s'", op_str, sel_str);
  4992. } else {
  4993. error(op_expr, "Type '%s' has no field '%s'", op_str, sel_str);
  4994. }
  4995. } else {
  4996. ERROR_BLOCK();
  4997. error(op_expr, "'%s' of type '%s' has no field '%s'", op_str, type_str, sel_str);
  4998. if (operand->type != nullptr && selector->kind == Ast_Ident) {
  4999. String const &name = selector->Ident.token.string;
  5000. Type *bt = base_type(operand->type);
  5001. if (operand->type->kind == Type_Named &&
  5002. operand->type->Named.type_name &&
  5003. operand->type->Named.type_name->kind == Entity_TypeName &&
  5004. operand->type->Named.type_name->TypeName.objc_metadata) {
  5005. check_did_you_mean_objc_entity(name, operand->type->Named.type_name, operand->mode == Addressing_Type);
  5006. } else if (bt->kind == Type_Struct) {
  5007. check_did_you_mean_type(name, bt->Struct.fields);
  5008. } else if (bt->kind == Type_Enum) {
  5009. check_did_you_mean_type(name, bt->Enum.fields);
  5010. }
  5011. }
  5012. }
  5013. gb_string_free(sel_str);
  5014. gb_string_free(type_str);
  5015. gb_string_free(op_str);
  5016. operand->mode = Addressing_Invalid;
  5017. operand->expr = node;
  5018. return nullptr;
  5019. }
  5020. if (expr_entity != nullptr && expr_entity->kind == Entity_Constant && entity->kind != Entity_Constant) {
  5021. bool success = false;
  5022. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5023. if (success) {
  5024. operand->mode = Addressing_Constant;
  5025. operand->expr = node;
  5026. operand->value = field_value;
  5027. operand->type = entity->type;
  5028. add_entity_use(c, selector, entity);
  5029. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5030. return entity;
  5031. }
  5032. gbString op_str = expr_to_string(op_expr);
  5033. gbString type_str = type_to_string_shorthand(operand->type);
  5034. gbString sel_str = expr_to_string(selector);
  5035. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5036. gb_string_free(sel_str);
  5037. gb_string_free(type_str);
  5038. gb_string_free(op_str);
  5039. operand->mode = Addressing_Invalid;
  5040. operand->expr = node;
  5041. return nullptr;
  5042. }
  5043. if (operand->mode == Addressing_Constant && entity->kind != Entity_Constant) {
  5044. bool success = false;
  5045. ExactValue field_value = get_constant_field(c, operand, sel, &success);
  5046. if (success) {
  5047. operand->mode = Addressing_Constant;
  5048. operand->expr = node;
  5049. operand->value = field_value;
  5050. operand->type = entity->type;
  5051. add_entity_use(c, selector, entity);
  5052. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5053. return entity;
  5054. }
  5055. gbString op_str = expr_to_string(op_expr);
  5056. gbString type_str = type_to_string_shorthand(operand->type);
  5057. gbString sel_str = expr_to_string(selector);
  5058. error(op_expr, "Cannot access non-constant field '%s' from '%s'", sel_str, op_str);
  5059. gb_string_free(sel_str);
  5060. gb_string_free(type_str);
  5061. gb_string_free(op_str);
  5062. operand->mode = Addressing_Invalid;
  5063. operand->expr = node;
  5064. return nullptr;
  5065. }
  5066. if (expr_entity != nullptr && is_type_polymorphic(expr_entity->type)) {
  5067. gbString op_str = expr_to_string(op_expr);
  5068. gbString type_str = type_to_string_shorthand(operand->type);
  5069. gbString sel_str = expr_to_string(selector);
  5070. error(op_expr, "Cannot access field '%s' from non-specialized polymorphic type '%s'", sel_str, op_str);
  5071. gb_string_free(sel_str);
  5072. gb_string_free(type_str);
  5073. gb_string_free(op_str);
  5074. operand->mode = Addressing_Invalid;
  5075. operand->expr = node;
  5076. return nullptr;
  5077. }
  5078. add_entity_use(c, selector, entity);
  5079. operand->type = entity->type;
  5080. operand->expr = node;
  5081. if (entity->flags & EntityFlag_BitFieldField) {
  5082. add_package_dependency(c, "runtime", "__write_bits");
  5083. add_package_dependency(c, "runtime", "__read_bits");
  5084. }
  5085. switch (entity->kind) {
  5086. case Entity_Constant:
  5087. operand->value = entity->Constant.value;
  5088. operand->mode = Addressing_Constant;
  5089. if (operand->value.kind == ExactValue_Procedure) {
  5090. Entity *proc = strip_entity_wrapping(operand->value.value_procedure);
  5091. if (proc != nullptr) {
  5092. operand->mode = Addressing_Value;
  5093. operand->type = proc->type;
  5094. }
  5095. }
  5096. break;
  5097. case Entity_Variable:
  5098. if (sel.is_bit_field) {
  5099. se->is_bit_field = true;
  5100. }
  5101. if (sel.indirect) {
  5102. operand->mode = Addressing_Variable;
  5103. } else if (operand->mode == Addressing_Context) {
  5104. // Do nothing
  5105. } else if (operand->mode == Addressing_MapIndex) {
  5106. operand->mode = Addressing_Value;
  5107. } else if (entity->flags & EntityFlag_SoaPtrField) {
  5108. operand->mode = Addressing_SoaVariable;
  5109. } else if (operand->mode == Addressing_OptionalOk || operand->mode == Addressing_OptionalOkPtr) {
  5110. operand->mode = Addressing_Value;
  5111. } else if (operand->mode == Addressing_SoaVariable) {
  5112. operand->mode = Addressing_Variable;
  5113. } else if (operand->mode != Addressing_Value) {
  5114. operand->mode = Addressing_Variable;
  5115. } else {
  5116. operand->mode = Addressing_Value;
  5117. }
  5118. break;
  5119. case Entity_TypeName:
  5120. operand->mode = Addressing_Type;
  5121. break;
  5122. case Entity_Procedure:
  5123. operand->mode = Addressing_Value;
  5124. operand->value = exact_value_procedure(node);
  5125. break;
  5126. case Entity_Builtin:
  5127. operand->mode = Addressing_Builtin;
  5128. operand->builtin_id = cast(BuiltinProcId)entity->Builtin.id;
  5129. break;
  5130. case Entity_ProcGroup:
  5131. operand->mode = Addressing_ProcGroup;
  5132. operand->proc_group = entity;
  5133. break;
  5134. // NOTE(bill): These cases should never be hit but are here for sanity reasons
  5135. case Entity_Nil:
  5136. operand->mode = Addressing_Value;
  5137. break;
  5138. }
  5139. add_type_and_value(c, operand->expr, operand->mode, operand->type, operand->value);
  5140. return entity;
  5141. }
  5142. gb_internal bool is_type_normal_pointer(Type *ptr, Type **elem) {
  5143. ptr = base_type(ptr);
  5144. if (is_type_pointer(ptr)) {
  5145. if (is_type_rawptr(ptr)) {
  5146. return false;
  5147. }
  5148. if (elem) *elem = ptr->Pointer.elem;
  5149. return true;
  5150. }
  5151. return false;
  5152. }
  5153. gb_internal bool is_type_valid_atomic_type(Type *elem) {
  5154. elem = core_type(elem);
  5155. if (is_type_internally_pointer_like(elem)) {
  5156. return true;
  5157. }
  5158. if (elem->kind == Type_BitSet) {
  5159. elem = bit_set_to_int(elem);
  5160. }
  5161. if (elem->kind != Type_Basic) {
  5162. return false;
  5163. }
  5164. return (elem->Basic.flags & (BasicFlag_Boolean|BasicFlag_OrderedNumeric)) != 0;
  5165. }
  5166. gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = false, Scope **out_scope = nullptr) {
  5167. switch (node->kind) {
  5168. case_ast_node(i, Ident, node);
  5169. String name = i->token.string;
  5170. if (nested) {
  5171. Entity *e = scope_lookup_current(s, name);
  5172. if (e != nullptr) {
  5173. if (out_scope) *out_scope = e->scope;
  5174. return true;
  5175. }
  5176. } else {
  5177. Entity *e = scope_lookup(s, name);
  5178. if (e != nullptr) {
  5179. if (out_scope) *out_scope = e->scope;
  5180. return true;
  5181. }
  5182. }
  5183. case_end;
  5184. case_ast_node(se, SelectorExpr, node);
  5185. Ast *lhs = se->expr;
  5186. Ast *rhs = se->selector;
  5187. Scope *lhs_scope = nullptr;
  5188. if (check_identifier_exists(s, lhs, nested, &lhs_scope)) {
  5189. return check_identifier_exists(lhs_scope, rhs, true);
  5190. }
  5191. case_end;
  5192. }
  5193. return false;
  5194. }
  5195. gb_internal bool check_assignment_arguments(CheckerContext *ctx, Array<Operand> const &lhs, Array<Operand> *operands, Slice<Ast *> const &rhs) {
  5196. bool optional_ok = false;
  5197. isize tuple_index = 0;
  5198. for (Ast *rhs_expr : rhs) {
  5199. CheckerContext c_ = *ctx;
  5200. CheckerContext *c = &c_;
  5201. Operand o = {};
  5202. Type *type_hint = nullptr;
  5203. if (tuple_index < lhs.count) {
  5204. type_hint = lhs[tuple_index].type;
  5205. }
  5206. check_expr_base(c, &o, rhs_expr, type_hint);
  5207. if (o.mode == Addressing_NoValue) {
  5208. error_operand_no_value(&o);
  5209. o.mode = Addressing_Invalid;
  5210. }
  5211. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5212. if (lhs.count == 2 && rhs.count == 1 &&
  5213. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5214. Ast *expr = unparen_expr(o.expr);
  5215. Operand val0 = o;
  5216. Operand val1 = o;
  5217. val0.mode = Addressing_Value;
  5218. val1.mode = Addressing_Value;
  5219. val1.type = t_untyped_bool;
  5220. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5221. if (expr->kind == Ast_TypeAssertion &&
  5222. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5223. // NOTE(bill): Used only for optimizations in the backend
  5224. if (is_blank_ident(lhs[0].expr)) {
  5225. expr->TypeAssertion.ignores[0] = true;
  5226. }
  5227. if (is_blank_ident(lhs[1].expr)) {
  5228. expr->TypeAssertion.ignores[1] = true;
  5229. }
  5230. }
  5231. array_add(operands, val0);
  5232. array_add(operands, val1);
  5233. optional_ok = true;
  5234. tuple_index += 2;
  5235. } else if (o.mode == Addressing_OptionalOk && is_type_tuple(o.type)) {
  5236. Type *tuple = o.type;
  5237. GB_ASSERT(tuple->Tuple.variables.count == 2);
  5238. Ast *expr = unparen_expr(o.expr);
  5239. if (expr->kind == Ast_CallExpr) {
  5240. expr->CallExpr.optional_ok_one = true;
  5241. }
  5242. Operand val = o;
  5243. val.type = tuple->Tuple.variables[0]->type;
  5244. val.mode = Addressing_Value;
  5245. array_add(operands, val);
  5246. tuple_index += tuple->Tuple.variables.count;
  5247. } else {
  5248. array_add(operands, o);
  5249. tuple_index += 1;
  5250. }
  5251. } else {
  5252. TypeTuple *tuple = &o.type->Tuple;
  5253. for (Entity *e : tuple->variables) {
  5254. o.type = e->type;
  5255. array_add(operands, o);
  5256. }
  5257. tuple_index += tuple->variables.count;
  5258. }
  5259. }
  5260. return optional_ok;
  5261. }
  5262. typedef u32 UnpackFlags;
  5263. enum UnpackFlag : u32 {
  5264. UnpackFlag_None = 0,
  5265. UnpackFlag_AllowOk = 1<<0,
  5266. UnpackFlag_AllowUndef = 1<<1,
  5267. };
  5268. gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array<Operand> *operands, Slice<Ast *> const &rhs_arguments, UnpackFlags flags,
  5269. isize variadic_index = -1) {
  5270. auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize {
  5271. if (lhs == nullptr || c->decl == nullptr) {
  5272. return tuple_count;
  5273. }
  5274. for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) {
  5275. Entity *e = lhs[tuple_index + j];
  5276. if (e == nullptr) {
  5277. continue;
  5278. }
  5279. DeclInfo *decl = decl_info_of_entity(e);
  5280. if (decl == nullptr) {
  5281. continue;
  5282. }
  5283. rw_mutex_shared_lock(&decl->deps_mutex);
  5284. rw_mutex_lock(&c->decl->deps_mutex);
  5285. for (Entity *dep : decl->deps) {
  5286. ptr_set_add(&c->decl->deps, dep);
  5287. }
  5288. rw_mutex_unlock(&c->decl->deps_mutex);
  5289. rw_mutex_shared_unlock(&decl->deps_mutex);
  5290. }
  5291. return tuple_count;
  5292. };
  5293. bool allow_ok = (flags & UnpackFlag_AllowOk) != 0;
  5294. bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0;
  5295. bool is_variadic = variadic_index > -1;
  5296. if (!is_variadic) {
  5297. variadic_index = lhs_count;
  5298. }
  5299. bool optional_ok = false;
  5300. isize tuple_index = 0;
  5301. for (Ast *rhs : rhs_arguments) {
  5302. if (rhs->kind == Ast_FieldValue) {
  5303. error(rhs, "Invalid use of 'field = value'");
  5304. rhs = rhs->FieldValue.value;
  5305. }
  5306. CheckerContext c_ = *ctx;
  5307. CheckerContext *c = &c_;
  5308. Operand o = {};
  5309. Type *type_hint = nullptr;
  5310. if (lhs != nullptr) {
  5311. if (tuple_index < variadic_index) {
  5312. // NOTE(bill): override DeclInfo for dependency
  5313. Entity *e = lhs[tuple_index];
  5314. if (e != nullptr) {
  5315. type_hint = e->type;
  5316. }
  5317. } else if (is_variadic) {
  5318. Entity *e = lhs[variadic_index];
  5319. if (e != nullptr) {
  5320. GB_ASSERT(e->flags & EntityFlag_Ellipsis);
  5321. GB_ASSERT(is_type_slice(e->type));
  5322. type_hint = e->type->Slice.elem;
  5323. }
  5324. }
  5325. }
  5326. Ast *rhs_expr = unparen_expr(rhs);
  5327. if (allow_undef && rhs_expr != nullptr && rhs_expr->kind == Ast_Uninit) {
  5328. // NOTE(bill): Just handle this very specific logic here
  5329. o.type = t_untyped_uninit;
  5330. o.mode = Addressing_Value;
  5331. o.expr = rhs;
  5332. add_type_and_value(c, rhs, o.mode, o.type, o.value);
  5333. } else {
  5334. check_expr_base(c, &o, rhs, type_hint);
  5335. }
  5336. if (o.mode == Addressing_NoValue) {
  5337. error_operand_no_value(&o);
  5338. o.mode = Addressing_Invalid;
  5339. }
  5340. if (o.type == nullptr || o.type->kind != Type_Tuple) {
  5341. if (allow_ok && lhs_count == 2 && rhs_arguments.count == 1 &&
  5342. (o.mode == Addressing_MapIndex || o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5343. Ast *expr = unparen_expr(o.expr);
  5344. Operand val0 = o;
  5345. Operand val1 = o;
  5346. val0.mode = Addressing_Value;
  5347. val1.mode = Addressing_Value;
  5348. val1.type = t_untyped_bool;
  5349. check_promote_optional_ok(c, &o, nullptr, &val1.type);
  5350. if (expr->kind == Ast_TypeAssertion &&
  5351. (o.mode == Addressing_OptionalOk || o.mode == Addressing_OptionalOkPtr)) {
  5352. // NOTE(bill): Used only for optimizations in the backend
  5353. if (is_blank_ident(lhs[0]->token)) {
  5354. expr->TypeAssertion.ignores[0] = true;
  5355. }
  5356. if (is_blank_ident(lhs[1]->token)) {
  5357. expr->TypeAssertion.ignores[1] = true;
  5358. }
  5359. }
  5360. array_add(operands, val0);
  5361. array_add(operands, val1);
  5362. optional_ok = true;
  5363. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, 2);
  5364. } else {
  5365. array_add(operands, o);
  5366. tuple_index += 1;
  5367. }
  5368. } else {
  5369. TypeTuple *tuple = &o.type->Tuple;
  5370. for (Entity *e : tuple->variables) {
  5371. o.type = e->type;
  5372. array_add(operands, o);
  5373. }
  5374. isize count = tuple->variables.count;
  5375. tuple_index += add_dependencies_from_unpacking(c, lhs, lhs_count, tuple_index, count);
  5376. }
  5377. }
  5378. return optional_ok;
  5379. }
  5380. gb_internal isize get_procedure_param_count_excluding_defaults(Type *pt, isize *param_count_) {
  5381. GB_ASSERT(pt != nullptr);
  5382. GB_ASSERT(pt->kind == Type_Proc);
  5383. isize param_count = 0;
  5384. isize param_count_excluding_defaults = 0;
  5385. bool variadic = pt->Proc.variadic;
  5386. TypeTuple *param_tuple = nullptr;
  5387. if (pt->Proc.params != nullptr) {
  5388. param_tuple = &pt->Proc.params->Tuple;
  5389. param_count = param_tuple->variables.count;
  5390. if (variadic) {
  5391. for (isize i = param_count-1; i >= 0; i--) {
  5392. Entity *e = param_tuple->variables[i];
  5393. if (e->kind == Entity_TypeName) {
  5394. break;
  5395. }
  5396. if (e->kind == Entity_Variable) {
  5397. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5398. param_count--;
  5399. continue;
  5400. }
  5401. }
  5402. break;
  5403. }
  5404. param_count--;
  5405. }
  5406. }
  5407. param_count_excluding_defaults = param_count;
  5408. if (param_tuple != nullptr) {
  5409. for (isize i = param_count-1; i >= 0; i--) {
  5410. Entity *e = param_tuple->variables[i];
  5411. if (e->kind == Entity_TypeName) {
  5412. break;
  5413. }
  5414. if (e->kind == Entity_Variable) {
  5415. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5416. param_count_excluding_defaults--;
  5417. continue;
  5418. }
  5419. }
  5420. break;
  5421. }
  5422. }
  5423. if (param_count_) *param_count_ = param_count;
  5424. return param_count_excluding_defaults;
  5425. }
  5426. gb_internal isize lookup_procedure_parameter(TypeProc *pt, String const &parameter_name) {
  5427. isize param_count = pt->param_count;
  5428. for (isize i = 0; i < param_count; i++) {
  5429. Entity *e = pt->params->Tuple.variables[i];
  5430. String name = e->token.string;
  5431. if (is_blank_ident(name)) {
  5432. continue;
  5433. }
  5434. if (name == parameter_name) {
  5435. return i;
  5436. }
  5437. }
  5438. return -1;
  5439. }
  5440. gb_internal isize lookup_procedure_parameter(Type *type, String const &parameter_name) {
  5441. type = base_type(type);
  5442. GB_ASSERT(type->kind == Type_Proc);
  5443. return lookup_procedure_parameter(&type->Proc, parameter_name);
  5444. }
  5445. gb_internal CallArgumentError check_call_arguments_internal(CheckerContext *c, Ast *call,
  5446. Entity *entity, Type *proc_type,
  5447. Array<Operand> positional_operands, Array<Operand> const &named_operands,
  5448. CallArgumentErrorMode show_error_mode,
  5449. CallArgumentData *data) {
  5450. TEMPORARY_ALLOCATOR_GUARD();
  5451. CallArgumentError err = CallArgumentError_None;
  5452. ast_node(ce, CallExpr, call);
  5453. GB_ASSERT(is_type_proc(proc_type));
  5454. proc_type = base_type(proc_type);
  5455. TypeProc *pt = &proc_type->Proc;
  5456. isize param_count = 0;
  5457. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(proc_type, &param_count);
  5458. bool variadic = pt->variadic;
  5459. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5460. i64 score = 0;
  5461. bool show_error = show_error_mode == CallArgumentErrorMode::ShowErrors;
  5462. Type *final_proc_type = proc_type;
  5463. Entity *gen_entity = nullptr;
  5464. if (vari_expand && !variadic) {
  5465. if (show_error) {
  5466. error(ce->ellipsis,
  5467. "Cannot use '..' in call to a non-variadic procedure: '%.*s'",
  5468. LIT(ce->proc->Ident.token.string));
  5469. }
  5470. err = CallArgumentError_NonVariadicExpand;
  5471. } else if (vari_expand && pt->c_vararg) {
  5472. if (show_error) {
  5473. error(ce->ellipsis,
  5474. "Cannot use '..' in call to a '#c_vararg' variadic procedure: '%.*s'",
  5475. LIT(ce->proc->Ident.token.string));
  5476. }
  5477. err = CallArgumentError_NonVariadicExpand;
  5478. }
  5479. GB_ASSERT(ce->split_args);
  5480. auto visited = slice_make<bool>(temporary_allocator(), pt->param_count);
  5481. auto ordered_operands = array_make<Operand>(temporary_allocator(), pt->param_count);
  5482. defer ({
  5483. for (Operand const &o : ordered_operands) {
  5484. if (o.expr != nullptr) {
  5485. call->viral_state_flags |= o.expr->viral_state_flags;
  5486. }
  5487. }
  5488. });
  5489. isize positional_operand_count = positional_operands.count;
  5490. if (variadic) {
  5491. positional_operand_count = gb_min(positional_operands.count, pt->variadic_index);
  5492. } else if (positional_operand_count > pt->param_count) {
  5493. err = CallArgumentError_TooManyArguments;
  5494. char const *err_fmt = "Too many arguments for '%s', expected %td arguments, got %td";
  5495. if (show_error) {
  5496. gbString proc_str = expr_to_string(ce->proc);
  5497. defer (gb_string_free(proc_str));
  5498. error(call, err_fmt, proc_str, param_count_excluding_defaults, positional_operands.count);
  5499. }
  5500. return err;
  5501. }
  5502. positional_operand_count = gb_min(positional_operand_count, pt->param_count);
  5503. for (isize i = 0; i < positional_operand_count; i++) {
  5504. ordered_operands[i] = positional_operands[i];
  5505. visited[i] = true;
  5506. }
  5507. auto variadic_operands = slice(slice_from_array(positional_operands), positional_operand_count, positional_operands.count);
  5508. bool named_variadic_param = false;
  5509. if (named_operands.count != 0) {
  5510. GB_ASSERT(ce->split_args->named.count == named_operands.count);
  5511. for_array(i, ce->split_args->named) {
  5512. Ast *arg = ce->split_args->named[i];
  5513. Operand operand = named_operands[i];
  5514. ast_node(fv, FieldValue, arg);
  5515. if (fv->field->kind != Ast_Ident) {
  5516. if (show_error) {
  5517. gbString expr_str = expr_to_string(fv->field);
  5518. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5519. gb_string_free(expr_str);
  5520. }
  5521. err = CallArgumentError_InvalidFieldValue;
  5522. continue;
  5523. }
  5524. String name = fv->field->Ident.token.string;
  5525. isize param_index = lookup_procedure_parameter(pt, name);
  5526. if (param_index < 0) {
  5527. if (show_error) {
  5528. error(arg, "No parameter named '%.*s' for this procedure type", LIT(name));
  5529. }
  5530. err = CallArgumentError_ParameterNotFound;
  5531. continue;
  5532. }
  5533. if (pt->variadic && param_index == pt->variadic_index) {
  5534. named_variadic_param = true;
  5535. }
  5536. if (visited[param_index]) {
  5537. if (show_error) {
  5538. error(arg, "Duplicate parameter '%.*s' in procedure call", LIT(name));
  5539. }
  5540. err = CallArgumentError_DuplicateParameter;
  5541. continue;
  5542. }
  5543. visited[param_index] = true;
  5544. ordered_operands[param_index] = operand;
  5545. }
  5546. }
  5547. isize dummy_argument_count = 0;
  5548. bool actually_variadic = false;
  5549. if (variadic) {
  5550. if (visited[pt->variadic_index] &&
  5551. positional_operand_count < positional_operands.count) {
  5552. if (show_error) {
  5553. String name = pt->params->Tuple.variables[pt->variadic_index]->token.string;
  5554. error(call, "Variadic parameters already handled with a named argument '%.*s' in procedure call", LIT(name));
  5555. }
  5556. err = CallArgumentError_DuplicateParameter;
  5557. } else if (!visited[pt->variadic_index]) {
  5558. visited[pt->variadic_index] = true;
  5559. Operand *variadic_operand = &ordered_operands[pt->variadic_index];
  5560. if (vari_expand) {
  5561. if (variadic_operands.count == 0) {
  5562. error(call, "'..' in the wrong position");
  5563. } else {
  5564. GB_ASSERT(variadic_operands.count != 0);
  5565. *variadic_operand = variadic_operands[0];
  5566. variadic_operand->type = default_type(variadic_operand->type);
  5567. actually_variadic = true;
  5568. }
  5569. } else {
  5570. AstFile *f = call->file();
  5571. // HACK(bill): this is an awful hack
  5572. Operand o = {};
  5573. o.mode = Addressing_Value;
  5574. o.expr = ast_ident(f, make_token_ident("nil"));
  5575. o.expr->Ident.token.pos = ast_token(call).pos;
  5576. if (variadic_operands.count != 0) {
  5577. actually_variadic = true;
  5578. o.expr->Ident.token.pos = ast_token(variadic_operands[0].expr).pos;
  5579. Entity *vt = pt->params->Tuple.variables[pt->variadic_index];
  5580. o.type = vt->type;
  5581. } else {
  5582. dummy_argument_count += 1;
  5583. o.type = t_untyped_nil;
  5584. }
  5585. *variadic_operand = o;
  5586. }
  5587. }
  5588. }
  5589. for (isize i = 0; i < pt->param_count; i++) {
  5590. if (!visited[i]) {
  5591. Entity *e = pt->params->Tuple.variables[i];
  5592. bool context_allocator_error = false;
  5593. if (e->kind == Entity_Variable) {
  5594. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  5595. if (ast_file_vet_explicit_allocators(c->file)) {
  5596. // NOTE(lucas): check if we are trying to default to context.allocator or context.temp_allocator
  5597. if (e->Variable.param_value.original_ast_expr->kind == Ast_SelectorExpr) {
  5598. auto& expr = e->Variable.param_value.original_ast_expr->SelectorExpr.expr;
  5599. auto& selector = e->Variable.param_value.original_ast_expr->SelectorExpr.selector;
  5600. if (expr->kind == Ast_Implicit &&
  5601. expr->Implicit.string == STR_LIT("context") &&
  5602. selector->kind == Ast_Ident &&
  5603. (selector->Ident.token.string == STR_LIT("allocator") ||
  5604. selector->Ident.token.string == STR_LIT("temp_allocator"))) {
  5605. context_allocator_error = true;
  5606. }
  5607. }
  5608. }
  5609. if (!context_allocator_error) {
  5610. ordered_operands[i].mode = Addressing_Value;
  5611. ordered_operands[i].type = e->type;
  5612. ordered_operands[i].expr = e->Variable.param_value.original_ast_expr;
  5613. dummy_argument_count += 1;
  5614. score += assign_score_function(1);
  5615. continue;
  5616. }
  5617. }
  5618. }
  5619. if (show_error) {
  5620. if (context_allocator_error) {
  5621. gbString str = type_to_string(e->type);
  5622. error(call, "Parameter '%.*s' of type '%s' must be explicitly provided in procedure call",
  5623. LIT(e->token.string), str);
  5624. gb_string_free(str);
  5625. } else if (e->kind == Entity_TypeName) {
  5626. error(call, "Type parameter '%.*s' is missing in procedure call",
  5627. LIT(e->token.string));
  5628. } else if (e->kind == Entity_Constant && e->Constant.value.kind != ExactValue_Invalid) {
  5629. // Ignore
  5630. } else {
  5631. gbString str = type_to_string(e->type);
  5632. error(call, "Parameter '%.*s' of type '%s' is missing in procedure call",
  5633. LIT(e->token.string), str);
  5634. gb_string_free(str);
  5635. }
  5636. }
  5637. err = CallArgumentError_ParameterMissing;
  5638. }
  5639. }
  5640. auto eval_param_and_score = [](CheckerContext *c, Operand *o, Type *param_type, CallArgumentError &err, bool param_is_variadic, Entity *e, bool show_error) -> i64 {
  5641. bool allow_array_programming = !(e && (e->flags & EntityFlag_NoBroadcast));
  5642. i64 s = 0;
  5643. if (!check_is_assignable_to_with_score(c, o, param_type, &s, param_is_variadic, allow_array_programming)) {
  5644. bool ok = false;
  5645. if (e && (e->flags & EntityFlag_AnyInt)) {
  5646. if (is_type_integer(param_type)) {
  5647. ok = check_is_castable_to(c, o, param_type);
  5648. }
  5649. }
  5650. if (!allow_array_programming && check_is_assignable_to_with_score(c, o, param_type, nullptr, param_is_variadic, !allow_array_programming)) {
  5651. if (show_error) {
  5652. error(o->expr, "'#no_broadcast' disallows automatic broadcasting a value across all elements of an array-like type in a procedure argument");
  5653. }
  5654. }
  5655. if (ok) {
  5656. s = assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5657. } else {
  5658. if (show_error) {
  5659. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5660. }
  5661. err = CallArgumentError_WrongTypes;
  5662. }
  5663. } else if (show_error) {
  5664. check_assignment(c, o, param_type, str_lit("procedure argument"));
  5665. }
  5666. if (e && e->flags & EntityFlag_ConstInput) {
  5667. if (o->mode != Addressing_Constant) {
  5668. if (show_error) {
  5669. error(o->expr, "Expected a constant value for the argument '%.*s'", LIT(e->token.string));
  5670. }
  5671. err = CallArgumentError_NoneConstantParameter;
  5672. }
  5673. }
  5674. if (!err && is_type_any(param_type)) {
  5675. add_type_info_type(c, o->type);
  5676. }
  5677. if (o->mode == Addressing_Type && is_type_typeid(param_type)) {
  5678. add_type_info_type(c, o->type);
  5679. add_type_and_value(c, o->expr, Addressing_Value, param_type, exact_value_typeid(o->type));
  5680. } else if (show_error && is_type_untyped(o->type)) {
  5681. update_untyped_expr_type(c, o->expr, param_type, true);
  5682. }
  5683. return s;
  5684. };
  5685. if (ordered_operands.count == 0 && param_count_excluding_defaults == 0) {
  5686. err = CallArgumentError_None;
  5687. if (variadic) {
  5688. GB_ASSERT(pt->params != nullptr && pt->params->Tuple.variables.count > 0);
  5689. Type *t = pt->params->Tuple.variables[0]->type;
  5690. if (is_type_polymorphic(t)) {
  5691. if (show_error) {
  5692. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input");
  5693. }
  5694. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5695. }
  5696. }
  5697. } else {
  5698. if (pt->is_polymorphic && !pt->is_poly_specialized && err == CallArgumentError_None) {
  5699. PolyProcData poly_proc_data = {};
  5700. if (find_or_generate_polymorphic_procedure_from_parameters(c, entity, &ordered_operands, call, &poly_proc_data)) {
  5701. gen_entity = poly_proc_data.gen_entity;
  5702. Type *gept = base_type(gen_entity->type);
  5703. GB_ASSERT(is_type_proc(gept));
  5704. final_proc_type = gen_entity->type;
  5705. pt = &gept->Proc;
  5706. } else {
  5707. err = CallArgumentError_WrongTypes;
  5708. }
  5709. }
  5710. for (isize i = 0; i < pt->param_count; i++) {
  5711. Operand *o = &ordered_operands[i];
  5712. if (o->mode == Addressing_Invalid) {
  5713. continue;
  5714. }
  5715. Entity *e = pt->params->Tuple.variables[i];
  5716. bool param_is_variadic = pt->variadic && pt->variadic_index == i;
  5717. if (e->kind == Entity_TypeName) {
  5718. GB_ASSERT(pt->is_polymorphic);
  5719. if (o->mode != Addressing_Type) {
  5720. if (show_error) {
  5721. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5722. }
  5723. err = CallArgumentError_WrongTypes;
  5724. }
  5725. if (are_types_identical(e->type, o->type)) {
  5726. score += assign_score_function(1);
  5727. } else {
  5728. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5729. }
  5730. continue;
  5731. }
  5732. if (param_is_variadic) {
  5733. if (!named_variadic_param) {
  5734. continue;
  5735. }
  5736. }
  5737. score += eval_param_and_score(c, o, e->type, err, false, e, show_error);
  5738. }
  5739. }
  5740. if (variadic) {
  5741. Entity *var_entity = pt->params->Tuple.variables[pt->variadic_index];
  5742. Type *slice = var_entity->type;
  5743. GB_ASSERT(is_type_slice(slice));
  5744. Type *elem = base_type(slice)->Slice.elem;
  5745. Type *t = elem;
  5746. if (is_type_polymorphic(t)) {
  5747. if (show_error) {
  5748. error(call, "Ambiguous call to a polymorphic variadic procedure with no variadic input %s", type_to_string(final_proc_type));
  5749. }
  5750. err = CallArgumentError_AmbiguousPolymorphicVariadic;
  5751. }
  5752. for_array(operand_index, variadic_operands) {
  5753. Operand *o = &variadic_operands[operand_index];
  5754. if (vari_expand) {
  5755. t = slice;
  5756. if (operand_index > 0) {
  5757. if (show_error) {
  5758. error(o->expr, "'..' in a variadic procedure can only have one variadic argument at the end");
  5759. }
  5760. if (data) {
  5761. data->score = score;
  5762. data->result_type = final_proc_type->Proc.results;
  5763. data->gen_entity = gen_entity;
  5764. }
  5765. return CallArgumentError_MultipleVariadicExpand;
  5766. }
  5767. }
  5768. score += eval_param_and_score(c, o, t, err, true, var_entity, show_error);
  5769. }
  5770. if (!vari_expand && variadic_operands.count != 0) {
  5771. // NOTE(bill, 2024-07-14): minimize the stack usage for variadic parameters with the backing array
  5772. if (c->decl) {
  5773. bool found = false;
  5774. for (auto &vr : c->decl->variadic_reuses) {
  5775. if (are_types_identical(slice, vr.slice_type)) {
  5776. vr.max_count = gb_max(vr.max_count, variadic_operands.count);
  5777. found = true;
  5778. break;
  5779. }
  5780. }
  5781. if (!found) {
  5782. array_add(&c->decl->variadic_reuses, VariadicReuseData{slice, variadic_operands.count});
  5783. }
  5784. }
  5785. }
  5786. }
  5787. if (data) {
  5788. data->score = score;
  5789. data->result_type = final_proc_type->Proc.results;
  5790. data->gen_entity = gen_entity;
  5791. Ast *proc_lit = nullptr;
  5792. if (ce->proc->tav.value.kind == ExactValue_Procedure) {
  5793. Ast *vp = unparen_expr(ce->proc->tav.value.value_procedure);
  5794. if (vp && vp->kind == Ast_ProcLit) {
  5795. proc_lit = vp;
  5796. }
  5797. }
  5798. if (proc_lit == nullptr) {
  5799. add_type_and_value(c, ce->proc, Addressing_Value, final_proc_type, {});
  5800. }
  5801. }
  5802. return err;
  5803. }
  5804. gb_internal bool is_call_expr_field_value(AstCallExpr *ce) {
  5805. GB_ASSERT(ce != nullptr);
  5806. if (ce->args.count == 0) {
  5807. return false;
  5808. }
  5809. return ce->args[0]->kind == Ast_FieldValue;
  5810. }
  5811. gb_internal Entity **populate_proc_parameter_list(CheckerContext *c, Type *proc_type, isize *lhs_count_) {
  5812. Entity **lhs = nullptr;
  5813. isize lhs_count = -1;
  5814. if (proc_type == nullptr || proc_type == t_invalid) {
  5815. return nullptr;
  5816. }
  5817. GB_ASSERT(is_type_proc(proc_type));
  5818. TypeProc *pt = &base_type(proc_type)->Proc;
  5819. if (!pt->is_polymorphic || pt->is_poly_specialized) {
  5820. if (pt->params != nullptr) {
  5821. lhs = pt->params->Tuple.variables.data;
  5822. lhs_count = pt->params->Tuple.variables.count;
  5823. }
  5824. } else {
  5825. // NOTE(bill): Create 'lhs' list in order to ignore parameters which are polymorphic
  5826. if (pt->params == nullptr) {
  5827. lhs_count = 0;
  5828. } else {
  5829. lhs_count = pt->params->Tuple.variables.count;
  5830. }
  5831. lhs = gb_alloc_array(permanent_allocator(), Entity *, lhs_count);
  5832. for (isize i = 0; i < lhs_count; i++) {
  5833. Entity *e = pt->params->Tuple.variables[i];
  5834. if (!is_type_polymorphic(e->type)) {
  5835. lhs[i] = e;
  5836. }
  5837. }
  5838. }
  5839. if (lhs_count_) *lhs_count_ = lhs_count;
  5840. return lhs;
  5841. }
  5842. gb_internal bool evaluate_where_clauses(CheckerContext *ctx, Ast *call_expr, Scope *scope, Slice<Ast *> *clauses, bool print_err) {
  5843. if (clauses != nullptr) {
  5844. for (Ast *clause : *clauses) {
  5845. Operand o = {};
  5846. check_expr(ctx, &o, clause);
  5847. if (o.mode != Addressing_Constant) {
  5848. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5849. if (print_err && call_expr) error(call_expr, "at caller location");
  5850. return false;
  5851. } else if (o.value.kind != ExactValue_Bool) {
  5852. if (print_err) error(clause, "'where' clauses expect a constant boolean evaluation");
  5853. if (print_err && call_expr) error(call_expr, "at caller location");
  5854. return false;
  5855. } else if (!o.value.value_bool) {
  5856. if (print_err) {
  5857. ERROR_BLOCK();
  5858. gbString str = expr_to_string(clause);
  5859. error(clause, "'where' clause evaluated to false:\n\t%s", str);
  5860. gb_string_free(str);
  5861. if (scope != nullptr) {
  5862. isize print_count = 0;
  5863. for (auto const &entry : scope->elements) {
  5864. Entity *e = entry.value;
  5865. switch (e->kind) {
  5866. case Entity_TypeName: {
  5867. // if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5868. gbString str = type_to_string(e->type);
  5869. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5870. gb_string_free(str);
  5871. print_count += 1;
  5872. break;
  5873. }
  5874. case Entity_Constant: {
  5875. if (print_count == 0) error_line("\n\tWith the following definitions:\n");
  5876. gbString str = exact_value_to_string(e->Constant.value);
  5877. if (is_type_untyped(e->type)) {
  5878. error_line("\t\t%.*s :: %s;\n", LIT(e->token.string), str);
  5879. } else {
  5880. gbString t = type_to_string(e->type);
  5881. error_line("\t\t%.*s : %s : %s;\n", LIT(e->token.string), t, str);
  5882. gb_string_free(t);
  5883. }
  5884. gb_string_free(str);
  5885. print_count += 1;
  5886. break;
  5887. }
  5888. }
  5889. }
  5890. }
  5891. if (call_expr) {
  5892. TokenPos pos = ast_token(call_expr).pos;
  5893. error_line("%s at caller location\n", token_pos_to_string(pos));
  5894. }
  5895. }
  5896. return false;
  5897. }
  5898. if (ast_file_vet_style(ctx->file)) {
  5899. Ast *c = unparen_expr(clause);
  5900. if (c->kind == Ast_BinaryExpr && c->BinaryExpr.op.kind == Token_CmpAnd) {
  5901. ERROR_BLOCK();
  5902. error(c, "Prefer to separate 'where' clauses with a comma rather than '&&'");
  5903. gbString x = expr_to_string(c->BinaryExpr.left);
  5904. gbString y = expr_to_string(c->BinaryExpr.right);
  5905. error_line("\tSuggestion: '%s, %s'\n", x, y);
  5906. gb_string_free(y);
  5907. gb_string_free(x);
  5908. }
  5909. }
  5910. }
  5911. }
  5912. return true;
  5913. }
  5914. gb_internal bool check_named_arguments(CheckerContext *c, Type *type, Slice<Ast *> const &named_args, Array<Operand> *named_operands, bool show_error) {
  5915. bool success = true;
  5916. type = base_type(type);
  5917. if (named_args.count > 0) {
  5918. TypeProc *pt = nullptr;
  5919. if (is_type_proc(type)) {
  5920. pt = &type->Proc;
  5921. }
  5922. for_array(i, named_args) {
  5923. Ast *arg = named_args[i];
  5924. if (arg->kind != Ast_FieldValue) {
  5925. if (show_error) {
  5926. error(arg, "Expected a 'field = value'");
  5927. }
  5928. return false;
  5929. }
  5930. ast_node(fv, FieldValue, arg);
  5931. if (fv->field->kind != Ast_Ident) {
  5932. if (show_error) {
  5933. gbString expr_str = expr_to_string(fv->field);
  5934. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  5935. gb_string_free(expr_str);
  5936. }
  5937. success = false;
  5938. continue;
  5939. }
  5940. String key = fv->field->Ident.token.string;
  5941. Ast *value = fv->value;
  5942. Type *type_hint = nullptr;
  5943. if (pt) {
  5944. isize param_index = lookup_procedure_parameter(pt, key);
  5945. if (param_index < 0) {
  5946. if (show_error) {
  5947. error(value, "No parameter named '%.*s' for this procedure type", LIT(key));
  5948. }
  5949. success = false;
  5950. continue;
  5951. }
  5952. Entity *e = pt->params->Tuple.variables[param_index];
  5953. if (!is_type_polymorphic(e->type)) {
  5954. type_hint = e->type;
  5955. }
  5956. }
  5957. Operand o = {};
  5958. check_expr_with_type_hint(c, &o, value, type_hint);
  5959. if (o.mode == Addressing_Invalid) {
  5960. success = false;
  5961. }
  5962. array_add(named_operands, o);
  5963. }
  5964. }
  5965. return success;
  5966. }
  5967. gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Operand *operand,
  5968. Entity *e, Type *proc_type,
  5969. Array<Operand> const &positional_operands, Array<Operand> const &named_operands,
  5970. CallArgumentErrorMode show_error_mode,
  5971. CallArgumentData *data) {
  5972. bool return_on_failure = show_error_mode == CallArgumentErrorMode::NoErrors;
  5973. Ast *ident = operand->expr;
  5974. while (ident->kind == Ast_SelectorExpr) {
  5975. Ast *s = ident->SelectorExpr.selector;
  5976. ident = s;
  5977. }
  5978. if (e == nullptr) {
  5979. e = entity_of_node(ident);
  5980. if (e != nullptr) {
  5981. proc_type = e->type;
  5982. }
  5983. }
  5984. GB_ASSERT(proc_type != nullptr);
  5985. proc_type = base_type(proc_type);
  5986. if (proc_type == t_invalid) {
  5987. return false;
  5988. }
  5989. GB_ASSERT(proc_type->kind == Type_Proc);
  5990. CallArgumentError err = check_call_arguments_internal(c, call, e, proc_type, positional_operands, named_operands, show_error_mode, data);
  5991. if (return_on_failure && err != CallArgumentError_None) {
  5992. return false;
  5993. }
  5994. Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e;
  5995. if (!return_on_failure && entity_to_use != nullptr) {
  5996. add_entity_use(c, ident, entity_to_use);
  5997. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5998. add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value);
  5999. }
  6000. if (data->gen_entity != nullptr) {
  6001. Entity *e = data->gen_entity;
  6002. DeclInfo *decl = data->gen_entity->decl_info;
  6003. CheckerContext ctx = *c;
  6004. ctx.scope = decl->scope;
  6005. ctx.decl = decl;
  6006. ctx.proc_name = e->token.string;
  6007. ctx.curr_proc_decl = decl;
  6008. ctx.curr_proc_sig = e->type;
  6009. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  6010. bool ok = evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, !return_on_failure);
  6011. if (return_on_failure) {
  6012. if (!ok) {
  6013. return false;
  6014. }
  6015. } else {
  6016. decl->where_clauses_evaluated = true;
  6017. if (ok && (data->gen_entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  6018. check_procedure_later(c->checker, e->file, e->token, decl, e->type, decl->proc_lit->ProcLit.body, decl->proc_lit->ProcLit.tags);
  6019. }
  6020. if (is_type_proc(data->gen_entity->type)) {
  6021. Type *t = base_type(entity_to_use->type);
  6022. data->result_type = t->Proc.results;
  6023. }
  6024. }
  6025. }
  6026. return true;
  6027. }
  6028. gb_internal CallArgumentData check_call_arguments_proc_group(CheckerContext *c, Operand *operand, Ast *call) {
  6029. ast_node(ce, CallExpr, call);
  6030. GB_ASSERT(ce->split_args != nullptr);
  6031. Slice<Ast *> const &positional_args = ce->split_args->positional;
  6032. Slice<Ast *> const &named_args = ce->split_args->named;
  6033. CallArgumentData data = {};
  6034. data.result_type = t_invalid;
  6035. GB_ASSERT(operand->mode == Addressing_ProcGroup);
  6036. auto procs = proc_group_entities_cloned(c, *operand);
  6037. if (procs.count > 1) {
  6038. isize max_arg_count = positional_args.count + named_args.count;
  6039. for (Ast *arg : positional_args) {
  6040. // NOTE(bill): The only thing that may have multiple values
  6041. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6042. arg = strip_or_return_expr(arg);
  6043. if (arg && arg->kind == Ast_CallExpr) {
  6044. max_arg_count = ISIZE_MAX;
  6045. break;
  6046. }
  6047. }
  6048. if (max_arg_count != ISIZE_MAX) for (Ast *arg : named_args) {
  6049. // NOTE(bill): The only thing that may have multiple values
  6050. // will be a call expression (assuming `or_return` and `()` will be stripped)
  6051. if (arg->kind == Ast_FieldValue) {
  6052. arg = strip_or_return_expr(arg->FieldValue.value);
  6053. if (arg && arg->kind == Ast_CallExpr) {
  6054. max_arg_count = ISIZE_MAX;
  6055. break;
  6056. }
  6057. }
  6058. }
  6059. // ignore named arguments first
  6060. for (Ast *arg : named_args) {
  6061. if (arg->kind != Ast_FieldValue) {
  6062. continue;
  6063. }
  6064. ast_node(fv, FieldValue, arg);
  6065. if (fv->field->kind != Ast_Ident) {
  6066. continue;
  6067. }
  6068. String key = fv->field->Ident.token.string;
  6069. for (isize proc_index = procs.count-1; proc_index >= 0; proc_index--) {
  6070. Type *t = procs[proc_index]->type;
  6071. if (is_type_proc(t)) {
  6072. isize param_index = lookup_procedure_parameter(t, key);
  6073. if (param_index < 0) {
  6074. array_unordered_remove(&procs, proc_index);
  6075. }
  6076. }
  6077. }
  6078. }
  6079. if (procs.count == 0) {
  6080. // if any of the named arguments are wrong, the `procs` will be empty
  6081. // just start from scratch
  6082. array_free(&procs);
  6083. procs = proc_group_entities_cloned(c, *operand);
  6084. }
  6085. // filter by positional argument length
  6086. for (isize proc_index = 0; proc_index < procs.count; /**/) {
  6087. Entity *proc = procs[proc_index];
  6088. Type *pt = base_type(proc->type);
  6089. if (!(pt != nullptr && is_type_proc(pt))) {
  6090. proc_index++;
  6091. continue;
  6092. }
  6093. isize param_count = 0;
  6094. isize param_count_excluding_defaults = get_procedure_param_count_excluding_defaults(pt, &param_count);
  6095. if (param_count_excluding_defaults > max_arg_count) {
  6096. array_unordered_remove(&procs, proc_index);
  6097. continue;
  6098. }
  6099. proc_index++;
  6100. }
  6101. }
  6102. Entity **lhs = nullptr;
  6103. isize lhs_count = -1;
  6104. i32 variadic_index = -1;
  6105. auto positional_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6106. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6107. defer (array_free(&positional_operands));
  6108. defer (array_free(&named_operands));
  6109. if (procs.count == 1) {
  6110. Entity *e = procs[0];
  6111. Type *pt = base_type(e->type);
  6112. if (pt != nullptr && is_type_proc(pt)) {
  6113. lhs = populate_proc_parameter_list(c, pt, &lhs_count);
  6114. if (pt->Proc.variadic) {
  6115. variadic_index = pt->Proc.variadic_index;
  6116. }
  6117. }
  6118. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6119. if (check_named_arguments(c, e->type, named_args, &named_operands, true)) {
  6120. check_call_arguments_single(c, call, operand,
  6121. e, e->type,
  6122. positional_operands, named_operands,
  6123. CallArgumentErrorMode::ShowErrors,
  6124. &data);
  6125. }
  6126. return data;
  6127. }
  6128. {
  6129. // NOTE(bill, 2019-07-13): This code is used to improve the type inference for procedure groups
  6130. // where the same positional parameter has the same type value (and ellipsis)
  6131. isize proc_arg_count = -1;
  6132. for (Entity *p : procs) {
  6133. Type *pt = base_type(p->type);
  6134. if (pt != nullptr && is_type_proc(pt)) {
  6135. if (proc_arg_count < 0) {
  6136. proc_arg_count = pt->Proc.param_count;
  6137. } else {
  6138. proc_arg_count = gb_min(proc_arg_count, pt->Proc.param_count);
  6139. }
  6140. }
  6141. }
  6142. if (proc_arg_count >= 0) {
  6143. lhs_count = proc_arg_count;
  6144. if (lhs_count > 0) {
  6145. lhs = gb_alloc_array(heap_allocator(), Entity *, lhs_count);
  6146. for (isize param_index = 0; param_index < lhs_count; param_index++) {
  6147. Entity *e = nullptr;
  6148. for (Entity *p : procs) {
  6149. Type *pt = base_type(p->type);
  6150. if (!(pt != nullptr && is_type_proc(pt))) {
  6151. continue;
  6152. }
  6153. if (e == nullptr) {
  6154. e = pt->Proc.params->Tuple.variables[param_index];
  6155. } else {
  6156. Entity *f = pt->Proc.params->Tuple.variables[param_index];
  6157. if (e == f) {
  6158. continue;
  6159. }
  6160. if (are_types_identical(e->type, f->type)) {
  6161. bool ee = (e->flags & EntityFlag_Ellipsis) != 0;
  6162. bool fe = (f->flags & EntityFlag_Ellipsis) != 0;
  6163. if (ee == fe) {
  6164. continue;
  6165. }
  6166. }
  6167. // NOTE(bill): Entities are not close enough to be used
  6168. e = nullptr;
  6169. break;
  6170. }
  6171. }
  6172. lhs[param_index] = e;
  6173. }
  6174. for (Entity *p : procs) {
  6175. Type *pt = base_type(p->type);
  6176. if (!(pt != nullptr && is_type_proc(pt))) {
  6177. continue;
  6178. }
  6179. if (pt->Proc.is_polymorphic) {
  6180. if (variadic_index == -1) {
  6181. variadic_index = pt->Proc.variadic_index;
  6182. } else if (variadic_index != pt->Proc.variadic_index) {
  6183. variadic_index = -1;
  6184. break;
  6185. }
  6186. } else {
  6187. variadic_index = -1;
  6188. break;
  6189. }
  6190. }
  6191. }
  6192. }
  6193. }
  6194. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6195. for_array(i, named_args) {
  6196. Ast *arg = named_args[i];
  6197. if (arg->kind != Ast_FieldValue) {
  6198. error(arg, "Expected a 'field = value'");
  6199. return data;
  6200. }
  6201. ast_node(fv, FieldValue, arg);
  6202. if (fv->field->kind != Ast_Ident) {
  6203. gbString expr_str = expr_to_string(fv->field);
  6204. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6205. gb_string_free(expr_str);
  6206. return data;
  6207. }
  6208. String key = fv->field->Ident.token.string;
  6209. Ast *value = fv->value;
  6210. Type *type_hint = nullptr;
  6211. for (isize lhs_idx = 0; lhs_idx < lhs_count; lhs_idx++) {
  6212. Entity *e = lhs[lhs_idx];
  6213. if (e != nullptr && e->token.string == key &&
  6214. !is_type_polymorphic(e->type)) {
  6215. type_hint = e->type;
  6216. break;
  6217. }
  6218. }
  6219. Operand o = {};
  6220. check_expr_with_type_hint(c, &o, value, type_hint);
  6221. array_add(&named_operands, o);
  6222. }
  6223. gb_free(heap_allocator(), lhs);
  6224. auto valids = array_make<ValidIndexAndScore>(heap_allocator(), 0, procs.count);
  6225. defer (array_free(&valids));
  6226. auto proc_entities = array_make<Entity *>(heap_allocator(), 0, procs.count*2 + 1);
  6227. defer (array_free(&proc_entities));
  6228. for (Entity *proc : procs) {
  6229. array_add(&proc_entities, proc);
  6230. }
  6231. int max_matched_features = 0;
  6232. gbString expr_name = expr_to_string(operand->expr);
  6233. defer (gb_string_free(expr_name));
  6234. for_array(i, procs) {
  6235. Entity *p = procs[i];
  6236. if (p->flags & EntityFlag_Disabled) {
  6237. continue;
  6238. }
  6239. Type *pt = base_type(p->type);
  6240. if (pt != nullptr && is_type_proc(pt)) {
  6241. CallArgumentData data = {};
  6242. CheckerContext ctx = *c;
  6243. ctx.no_polymorphic_errors = true;
  6244. ctx.allow_polymorphic_types = is_type_polymorphic(pt);
  6245. ctx.hide_polymorphic_errors = true;
  6246. bool is_a_candidate = check_call_arguments_single(&ctx, call, operand,
  6247. p, pt,
  6248. positional_operands, named_operands,
  6249. CallArgumentErrorMode::NoErrors,
  6250. &data);
  6251. if (!is_a_candidate) {
  6252. continue;
  6253. }
  6254. isize index = i;
  6255. ValidIndexAndScore item = {};
  6256. item.score = data.score;
  6257. if (data.gen_entity != nullptr) {
  6258. array_add(&proc_entities, data.gen_entity);
  6259. index = proc_entities.count-1;
  6260. // prefer non-polymorphic procedures over polymorphic
  6261. item.score += assign_score_function(1);
  6262. }
  6263. max_matched_features = gb_max(max_matched_features, matched_target_features(&pt->Proc));
  6264. item.index = index;
  6265. array_add(&valids, item);
  6266. }
  6267. }
  6268. if (max_matched_features > 0) {
  6269. for_array(i, valids) {
  6270. Entity *p = procs[valids[i].index];
  6271. Type *t = base_type(p->type);
  6272. GB_ASSERT(t->kind == Type_Proc);
  6273. int matched = matched_target_features(&t->Proc);
  6274. valids[i].score += assign_score_function(max_matched_features-matched);
  6275. }
  6276. }
  6277. if (valids.count > 1) {
  6278. array_sort(valids, valid_index_and_score_cmp);
  6279. i64 best_score = valids[0].score;
  6280. Entity *best_entity = proc_entities[valids[0].index];
  6281. GB_ASSERT(best_entity != nullptr);
  6282. for (isize i = 1; i < valids.count; i++) {
  6283. if (best_score > valids[i].score) {
  6284. valids.count = i;
  6285. break;
  6286. }
  6287. if (best_entity == proc_entities[valids[i].index]) {
  6288. valids.count = i;
  6289. break;
  6290. }
  6291. }
  6292. }
  6293. auto print_argument_types = [&]() {
  6294. error_line("\tGiven argument types: (");
  6295. isize i = 0;
  6296. for (Operand const &o : positional_operands) {
  6297. if (i++ > 0) error_line(", ");
  6298. gbString type = type_to_string(o.type);
  6299. defer (gb_string_free(type));
  6300. error_line("%s", type);
  6301. }
  6302. for (Operand const &o : named_operands) {
  6303. if (i++ > 0) error_line(", ");
  6304. gbString type = type_to_string(o.type);
  6305. defer (gb_string_free(type));
  6306. if (i < ce->split_args->named.count) {
  6307. Ast *named_field = ce->split_args->named[i];
  6308. ast_node(fv, FieldValue, named_field);
  6309. gbString field = expr_to_string(fv->field);
  6310. defer (gb_string_free(field));
  6311. error_line("%s = %s", field, type);
  6312. } else {
  6313. error_line("%s", type);
  6314. }
  6315. }
  6316. error_line(")\n");
  6317. };
  6318. if (valids.count == 0) {
  6319. ERROR_BLOCK();
  6320. error(operand->expr, "No procedures or ambiguous call for procedure group '%s' that match with the given arguments", expr_name);
  6321. if (positional_operands.count == 0 && named_operands.count == 0) {
  6322. error_line("\tNo given arguments\n");
  6323. } else {
  6324. print_argument_types();
  6325. }
  6326. if (procs.count == 0) {
  6327. procs = proc_group_entities_cloned(c, *operand);
  6328. }
  6329. if (procs.count > 0) {
  6330. error_line("Did you mean to use one of the following:\n");
  6331. }
  6332. // Try to reduce the list further for `$T: typeid` like parameters
  6333. bool *possibly_ignore = gb_alloc_array(temporary_allocator(), bool, procs.count);
  6334. isize possibly_ignore_set = 0;
  6335. if (true) {
  6336. // NOTE(bill): This currently only checks for #soa types
  6337. for_array(i, procs) {
  6338. Entity *proc = procs[i];
  6339. Type *t = base_type(proc->type);
  6340. if (t == nullptr || t->kind != Type_Proc) {
  6341. continue;
  6342. }
  6343. TypeProc *pt = &t->Proc;
  6344. if (pt->param_count == 0) {
  6345. continue;
  6346. }
  6347. for_array(j, pt->params->Tuple.variables) {
  6348. Entity *v = pt->params->Tuple.variables[j];
  6349. if (v->kind != Entity_TypeName) {
  6350. continue;
  6351. }
  6352. Type *dst_t = base_type(v->type);
  6353. while (dst_t->kind == Type_Generic && dst_t->Generic.specialized) {
  6354. dst_t = dst_t->Generic.specialized;
  6355. }
  6356. if (j >= positional_operands.count) {
  6357. continue;
  6358. }
  6359. Operand const &o = positional_operands[j];
  6360. if (o.mode != Addressing_Type) {
  6361. continue;
  6362. }
  6363. Type *t = base_type(o.type);
  6364. if (t->kind == dst_t->kind) {
  6365. continue;
  6366. }
  6367. Type *st = base_type(type_deref(o.type));
  6368. Type *dt = base_type(type_deref(dst_t));
  6369. if (st->kind == dt->kind) {
  6370. continue;
  6371. }
  6372. if (is_type_soa_struct(st)) {
  6373. possibly_ignore[i] = true;
  6374. possibly_ignore_set += 1;
  6375. continue;
  6376. }
  6377. }
  6378. }
  6379. }
  6380. if (possibly_ignore_set == procs.count) {
  6381. possibly_ignore_set = 0;
  6382. }
  6383. isize max_name_length = 0;
  6384. isize max_type_length = 0;
  6385. for_array(i, procs) {
  6386. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6387. continue;
  6388. }
  6389. Entity *proc = procs[i];
  6390. Type *t = base_type(proc->type);
  6391. if (t == t_invalid) continue;
  6392. String prefix = {};
  6393. String prefix_sep = {};
  6394. if (proc->pkg) {
  6395. prefix = proc->pkg->name;
  6396. prefix_sep = str_lit(".");
  6397. }
  6398. String name = proc->token.string;
  6399. max_name_length = gb_max(max_name_length, prefix.len + prefix_sep.len + name.len);
  6400. gbString pt;
  6401. if (t->Proc.node != nullptr) {
  6402. pt = expr_to_string(t->Proc.node);
  6403. } else {
  6404. pt = type_to_string(t);
  6405. }
  6406. max_type_length = gb_max(max_type_length, gb_string_length(pt));
  6407. gb_string_free(pt);
  6408. }
  6409. isize max_spaces = gb_max(max_name_length, max_type_length);
  6410. char *spaces = gb_alloc_array(temporary_allocator(), char, max_spaces+1);
  6411. for (isize i = 0; i < max_spaces; i++) {
  6412. spaces[i] = ' ';
  6413. }
  6414. spaces[max_spaces] = 0;
  6415. for_array(i, procs) {
  6416. if (possibly_ignore_set != 0 && possibly_ignore[i]) {
  6417. continue;
  6418. }
  6419. Entity *proc = procs[i];
  6420. TokenPos pos = proc->token.pos;
  6421. Type *t = base_type(proc->type);
  6422. if (t == t_invalid) continue;
  6423. GB_ASSERT(t->kind == Type_Proc);
  6424. gbString pt;
  6425. defer (gb_string_free(pt));
  6426. if (t->Proc.node != nullptr) {
  6427. pt = expr_to_string(t->Proc.node);
  6428. } else {
  6429. pt = type_to_string(t);
  6430. }
  6431. String prefix = {};
  6432. String prefix_sep = {};
  6433. if (proc->pkg) {
  6434. prefix = proc->pkg->name;
  6435. prefix_sep = str_lit(".");
  6436. }
  6437. String name = proc->token.string;
  6438. isize len = prefix.len + prefix_sep.len + name.len;
  6439. int name_padding = cast(int)gb_max(max_name_length - len, 0);
  6440. int type_padding = cast(int)gb_max(max_type_length - gb_string_length(pt), 0);
  6441. char const *sep = "::";
  6442. if (proc->kind == Entity_Variable) {
  6443. sep = ":=";
  6444. }
  6445. error_line("\t%.*s%.*s%.*s %.*s%s %s %.*sat %s\n",
  6446. LIT(prefix), LIT(prefix_sep), LIT(name),
  6447. name_padding, spaces,
  6448. sep,
  6449. pt,
  6450. type_padding, spaces,
  6451. token_pos_to_string(pos)
  6452. );
  6453. }
  6454. if (procs.count > 0) {
  6455. error_line("\n");
  6456. }
  6457. data.result_type = t_invalid;
  6458. } else if (valids.count > 1) {
  6459. ERROR_BLOCK();
  6460. error(operand->expr, "Ambiguous procedure group call '%s' that match with the given arguments", expr_name);
  6461. if (positional_operands.count == 0 && named_operands.count == 0) {
  6462. error_line("\tNo given arguments\n");
  6463. } else {
  6464. print_argument_types();
  6465. }
  6466. for (auto const &valid : valids) {
  6467. Entity *proc = proc_entities[valid.index];
  6468. GB_ASSERT(proc != nullptr);
  6469. TokenPos pos = proc->token.pos;
  6470. Type *t = base_type(proc->type); GB_ASSERT(t->kind == Type_Proc);
  6471. gbString pt = nullptr;
  6472. defer (gb_string_free(pt));
  6473. if (t->Proc.node != nullptr) {
  6474. pt = expr_to_string(t->Proc.node);
  6475. } else {
  6476. pt = type_to_string(t);
  6477. }
  6478. String name = proc->token.string;
  6479. char const *sep = "::";
  6480. if (proc->kind == Entity_Variable) {
  6481. sep = ":=";
  6482. }
  6483. error_line("\t%.*s %s %s ", LIT(name), sep, pt);
  6484. if (proc->decl_info->proc_lit != nullptr) {
  6485. GB_ASSERT(proc->decl_info->proc_lit->kind == Ast_ProcLit);
  6486. auto *pl = &proc->decl_info->proc_lit->ProcLit;
  6487. if (pl->where_token.kind != Token_Invalid) {
  6488. error_line("\n\t\twhere ");
  6489. for_array(j, pl->where_clauses) {
  6490. Ast *clause = pl->where_clauses[j];
  6491. if (j != 0) {
  6492. error_line("\t\t ");
  6493. }
  6494. gbString str = expr_to_string(clause);
  6495. error_line("%s", str);
  6496. gb_string_free(str);
  6497. if (j != pl->where_clauses.count-1) {
  6498. error_line(",");
  6499. }
  6500. }
  6501. error_line("\n\t");
  6502. }
  6503. }
  6504. error_line("at %s\n", token_pos_to_string(pos));
  6505. }
  6506. data.result_type = t_invalid;
  6507. } else {
  6508. GB_ASSERT(valids.count == 1);
  6509. Ast *ident = operand->expr;
  6510. while (ident->kind == Ast_SelectorExpr) {
  6511. Ast *s = ident->SelectorExpr.selector;
  6512. ident = s;
  6513. }
  6514. Entity *e = proc_entities[valids[0].index];
  6515. GB_ASSERT(e != nullptr);
  6516. Array<Operand> named_operands = {};
  6517. check_call_arguments_single(c, call, operand,
  6518. e, e->type,
  6519. positional_operands, named_operands,
  6520. CallArgumentErrorMode::ShowErrors,
  6521. &data);
  6522. return data;
  6523. }
  6524. return data;
  6525. }
  6526. gb_internal CallArgumentData check_call_arguments(CheckerContext *c, Operand *operand, Ast *call) {
  6527. Type *proc_type = nullptr;
  6528. CallArgumentData data = {};
  6529. data.result_type = t_invalid;
  6530. proc_type = base_type(operand->type);
  6531. TypeProc *pt = nullptr;
  6532. if (proc_type) {
  6533. pt = &proc_type->Proc;
  6534. }
  6535. TEMPORARY_ALLOCATOR_GUARD();
  6536. ast_node(ce, CallExpr, call);
  6537. bool any_failure = false;
  6538. // Split positional and named args into separate arrays/slices
  6539. Slice<Ast *> positional_args = {};
  6540. Slice<Ast *> named_args = {};
  6541. if (ce->split_args == nullptr) {
  6542. positional_args = ce->args;
  6543. for (isize i = 0; i < ce->args.count; i++) {
  6544. Ast *arg = ce->args.data[i];
  6545. if (arg->kind == Ast_FieldValue) {
  6546. positional_args.count = i;
  6547. break;
  6548. }
  6549. }
  6550. named_args = slice(ce->args, positional_args.count, ce->args.count);
  6551. auto split_args = gb_alloc_item(permanent_allocator(), AstSplitArgs);
  6552. split_args->positional = positional_args;
  6553. split_args->named = named_args;
  6554. ce->split_args = split_args;
  6555. } else {
  6556. positional_args = ce->split_args->positional;
  6557. named_args = ce->split_args->named;
  6558. }
  6559. if (operand->mode == Addressing_ProcGroup) {
  6560. return check_call_arguments_proc_group(c, operand, call);
  6561. }
  6562. auto positional_operands = array_make<Operand>(heap_allocator(), 0, positional_args.count);
  6563. auto named_operands = array_make<Operand>(heap_allocator(), 0, 0);
  6564. defer (array_free(&positional_operands));
  6565. defer (array_free(&named_operands));
  6566. if (positional_args.count > 0) {
  6567. Entity **lhs = nullptr;
  6568. isize lhs_count = -1;
  6569. i32 variadic_index = -1;
  6570. if (pt != nullptr) {
  6571. lhs = populate_proc_parameter_list(c, proc_type, &lhs_count);
  6572. if (pt->variadic) {
  6573. variadic_index = pt->variadic_index;
  6574. }
  6575. }
  6576. check_unpack_arguments(c, lhs, lhs_count, &positional_operands, positional_args, UnpackFlag_None, variadic_index);
  6577. }
  6578. if (named_args.count > 0) {
  6579. for_array(i, named_args) {
  6580. Ast *arg = named_args[i];
  6581. if (arg->kind != Ast_FieldValue) {
  6582. error(arg, "Expected a 'field = value'");
  6583. return data;
  6584. }
  6585. ast_node(fv, FieldValue, arg);
  6586. if (fv->field->kind != Ast_Ident) {
  6587. gbString expr_str = expr_to_string(fv->field);
  6588. error(arg, "Invalid parameter name '%s' in procedure call", expr_str);
  6589. any_failure = true;
  6590. gb_string_free(expr_str);
  6591. continue;
  6592. }
  6593. String key = fv->field->Ident.token.string;
  6594. Ast *value = fv->value;
  6595. isize param_index = lookup_procedure_parameter(pt, key);
  6596. Type *type_hint = nullptr;
  6597. if (param_index >= 0) {
  6598. Entity *e = pt->params->Tuple.variables[param_index];
  6599. type_hint = e->type;
  6600. }
  6601. Operand o = {};
  6602. check_expr_with_type_hint(c, &o, value, type_hint);
  6603. if (o.mode == Addressing_Invalid) {
  6604. any_failure = true;
  6605. }
  6606. array_add(&named_operands, o);
  6607. }
  6608. }
  6609. if (!any_failure) {
  6610. check_call_arguments_single(c, call, operand,
  6611. nullptr, proc_type,
  6612. positional_operands, named_operands,
  6613. CallArgumentErrorMode::ShowErrors,
  6614. &data);
  6615. } else if (pt) {
  6616. data.result_type = pt->results;
  6617. }
  6618. return data;
  6619. }
  6620. gb_internal isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  6621. if (!is_type_polymorphic_record(t)) {
  6622. return -1;
  6623. }
  6624. TypeTuple *params = get_record_polymorphic_params(t);
  6625. if (params == nullptr) {
  6626. return -1;
  6627. }
  6628. for_array(i, params->variables) {
  6629. Entity *e = params->variables[i];
  6630. String name = e->token.string;
  6631. if (is_blank_ident(name)) {
  6632. continue;
  6633. }
  6634. if (name == parameter_name) {
  6635. return i;
  6636. }
  6637. }
  6638. return -1;
  6639. }
  6640. gb_internal CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  6641. ast_node(ce, CallExpr, call);
  6642. Type *original_type = operand->type;
  6643. GB_ASSERT(is_type_polymorphic_record(original_type));
  6644. bool show_error = true;
  6645. Array<Operand> operands = {};
  6646. defer (array_free(&operands));
  6647. CallArgumentError err = CallArgumentError_None;
  6648. bool named_fields = false;
  6649. {
  6650. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  6651. auto prev_type_path = c->type_path;
  6652. c->type_path = new_checker_type_path();
  6653. defer ({
  6654. destroy_checker_type_path(c->type_path);
  6655. c->type_path = prev_type_path;
  6656. });
  6657. if (is_call_expr_field_value(ce)) {
  6658. named_fields = true;
  6659. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  6660. for_array(i, ce->args) {
  6661. Ast *arg = ce->args[i];
  6662. ast_node(fv, FieldValue, arg);
  6663. if (fv->value == nullptr) {
  6664. error(fv->eq, "Expected a value");
  6665. err = CallArgumentError_InvalidFieldValue;
  6666. continue;
  6667. }
  6668. if (fv->field->kind == Ast_Ident) {
  6669. String name = fv->field->Ident.token.string;
  6670. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6671. if (index >= 0) {
  6672. TypeTuple *params = get_record_polymorphic_params(original_type);
  6673. Entity *e = params->variables[index];
  6674. if (e->kind == Entity_Constant) {
  6675. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  6676. continue;
  6677. }
  6678. }
  6679. }
  6680. check_expr_or_type(c, &operands[i], fv->value);
  6681. }
  6682. bool vari_expand = (ce->ellipsis.pos.line != 0);
  6683. if (vari_expand) {
  6684. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  6685. }
  6686. } else {
  6687. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  6688. Entity **lhs = nullptr;
  6689. isize lhs_count = -1;
  6690. TypeTuple *params = get_record_polymorphic_params(original_type);
  6691. if (params != nullptr) {
  6692. lhs = params->variables.data;
  6693. lhs_count = params->variables.count;
  6694. }
  6695. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, UnpackFlag_None);
  6696. }
  6697. }
  6698. if (err != 0) {
  6699. operand->mode = Addressing_Invalid;
  6700. return err;
  6701. }
  6702. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  6703. isize param_count = tuple->variables.count;
  6704. isize minimum_param_count = param_count;
  6705. for (; minimum_param_count > 0; minimum_param_count--) {
  6706. Entity *e = tuple->variables[minimum_param_count-1];
  6707. if (e->kind != Entity_Constant) {
  6708. break;
  6709. }
  6710. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  6711. break;
  6712. }
  6713. }
  6714. Array<Operand> ordered_operands = operands;
  6715. if (!named_fields) {
  6716. ordered_operands = array_make<Operand>(permanent_allocator(), operands.count);
  6717. array_copy(&ordered_operands, operands, 0);
  6718. } else {
  6719. TEMPORARY_ALLOCATOR_GUARD();
  6720. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  6721. // LEAK(bill)
  6722. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  6723. for_array(i, ce->args) {
  6724. Ast *arg = ce->args[i];
  6725. ast_node(fv, FieldValue, arg);
  6726. if (fv->field->kind != Ast_Ident) {
  6727. if (show_error) {
  6728. gbString expr_str = expr_to_string(fv->field);
  6729. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  6730. gb_string_free(expr_str);
  6731. }
  6732. err = CallArgumentError_InvalidFieldValue;
  6733. continue;
  6734. }
  6735. String name = fv->field->Ident.token.string;
  6736. isize index = lookup_polymorphic_record_parameter(original_type, name);
  6737. if (index < 0) {
  6738. if (show_error) {
  6739. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  6740. }
  6741. err = CallArgumentError_ParameterNotFound;
  6742. continue;
  6743. }
  6744. if (visited[index]) {
  6745. if (show_error) {
  6746. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  6747. }
  6748. err = CallArgumentError_DuplicateParameter;
  6749. continue;
  6750. }
  6751. visited[index] = true;
  6752. ordered_operands[index] = operands[i];
  6753. }
  6754. for (isize i = 0; i < param_count; i++) {
  6755. if (!visited[i]) {
  6756. Entity *e = tuple->variables[i];
  6757. if (is_blank_ident(e->token)) {
  6758. continue;
  6759. }
  6760. if (show_error) {
  6761. if (e->kind == Entity_TypeName) {
  6762. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  6763. LIT(e->token.string));
  6764. } else {
  6765. gbString str = type_to_string(e->type);
  6766. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  6767. LIT(e->token.string), str);
  6768. gb_string_free(str);
  6769. }
  6770. }
  6771. err = CallArgumentError_ParameterMissing;
  6772. }
  6773. }
  6774. }
  6775. if (err != 0) {
  6776. operand->mode = Addressing_Invalid;
  6777. return err;
  6778. }
  6779. while (ordered_operands.count > 0) {
  6780. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  6781. break;
  6782. }
  6783. array_pop(&ordered_operands);
  6784. }
  6785. if (minimum_param_count != param_count) {
  6786. if (param_count < ordered_operands.count) {
  6787. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  6788. err = CallArgumentError_TooManyArguments;
  6789. } else if (minimum_param_count > ordered_operands.count) {
  6790. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  6791. err = CallArgumentError_TooFewArguments;
  6792. }
  6793. } else {
  6794. if (param_count < ordered_operands.count) {
  6795. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6796. err = CallArgumentError_TooManyArguments;
  6797. } else if (param_count > ordered_operands.count) {
  6798. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  6799. err = CallArgumentError_TooFewArguments;
  6800. }
  6801. }
  6802. if (err != 0) {
  6803. return err;
  6804. }
  6805. if (minimum_param_count != param_count) {
  6806. array_resize(&ordered_operands, param_count);
  6807. isize missing_count = 0;
  6808. // NOTE(bill): Replace missing operands with the default values (if possible)
  6809. for_array(i, ordered_operands) {
  6810. Operand *o = &ordered_operands[i];
  6811. if (o->expr == nullptr) {
  6812. Entity *e = tuple->variables[i];
  6813. if (e->kind == Entity_Constant) {
  6814. missing_count += 1;
  6815. o->mode = Addressing_Constant;
  6816. o->type = default_type(e->type);
  6817. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  6818. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  6819. o->value = e->Constant.param_value.value;
  6820. }
  6821. } else if (e->kind == Entity_TypeName) {
  6822. missing_count += 1;
  6823. o->mode = Addressing_Type;
  6824. o->type = e->type;
  6825. o->expr = e->identifier;
  6826. }
  6827. }
  6828. }
  6829. }
  6830. isize oo_count = gb_min(param_count, ordered_operands.count);
  6831. i64 score = 0;
  6832. for (isize i = 0; i < oo_count; i++) {
  6833. Entity *e = tuple->variables[i];
  6834. Operand *o = &ordered_operands[i];
  6835. if (o->mode == Addressing_Invalid) {
  6836. continue;
  6837. }
  6838. if (e->kind == Entity_TypeName) {
  6839. if (o->mode != Addressing_Type) {
  6840. if (show_error) {
  6841. gbString expr = expr_to_string(o->expr);
  6842. error(o->expr, "Expected a type for the argument '%.*s', got %s", LIT(e->token.string), expr);
  6843. gb_string_free(expr);
  6844. }
  6845. err = CallArgumentError_WrongTypes;
  6846. }
  6847. if (are_types_identical(e->type, o->type)) {
  6848. score += assign_score_function(1);
  6849. } else {
  6850. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  6851. }
  6852. } else {
  6853. i64 s = 0;
  6854. if (o->type->kind == Type_Generic) {
  6855. // Polymorphic name!
  6856. score += assign_score_function(1);
  6857. continue;
  6858. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  6859. if (show_error) {
  6860. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  6861. }
  6862. err = CallArgumentError_WrongTypes;
  6863. }
  6864. o->type = e->type;
  6865. if (o->mode != Addressing_Constant) {
  6866. bool valid = false;
  6867. if (is_type_proc(o->type)) {
  6868. Entity *proc_entity = entity_from_expr(o->expr);
  6869. valid = proc_entity != nullptr;
  6870. }
  6871. if (!valid) {
  6872. if (show_error) {
  6873. error(o->expr, "Expected a constant value for this polymorphic type argument");
  6874. }
  6875. err = CallArgumentError_NoneConstantParameter;
  6876. }
  6877. }
  6878. score += s;
  6879. }
  6880. // NOTE(bill): Add type info the parameters
  6881. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  6882. // add_type_info_type(c, o->type);
  6883. }
  6884. if (show_error && err) {
  6885. return err;
  6886. }
  6887. {
  6888. GenTypesData *found_gen_types = ensure_polymorphic_record_entity_has_gen_types(c, original_type);
  6889. mutex_lock(&found_gen_types->mutex);
  6890. defer (mutex_unlock(&found_gen_types->mutex));
  6891. Entity *found_entity = find_polymorphic_record_entity(found_gen_types, param_count, ordered_operands);
  6892. if (found_entity) {
  6893. operand->mode = Addressing_Type;
  6894. operand->type = found_entity->type;
  6895. return err;
  6896. }
  6897. CheckerContext ctx = *c;
  6898. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  6899. ctx.scope = polymorphic_record_parent_scope(original_type);
  6900. GB_ASSERT(ctx.scope != nullptr);
  6901. Type *bt = base_type(original_type);
  6902. String generated_name = make_string_c(expr_to_string(call));
  6903. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  6904. if (bt->kind == Type_Struct) {
  6905. Ast *node = clone_ast(bt->Struct.node);
  6906. Type *struct_type = alloc_type_struct();
  6907. struct_type->Struct.node = node;
  6908. struct_type->Struct.polymorphic_parent = original_type;
  6909. set_base_type(named_type, struct_type);
  6910. check_open_scope(&ctx, node);
  6911. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  6912. check_close_scope(&ctx);
  6913. } else if (bt->kind == Type_Union) {
  6914. Ast *node = clone_ast(bt->Union.node);
  6915. Type *union_type = alloc_type_union();
  6916. union_type->Union.node = node;
  6917. union_type->Union.polymorphic_parent = original_type;
  6918. set_base_type(named_type, union_type);
  6919. check_open_scope(&ctx, node);
  6920. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  6921. check_close_scope(&ctx);
  6922. } else {
  6923. GB_PANIC("Unsupported parametric polymorphic record type");
  6924. }
  6925. bt = base_type(named_type);
  6926. if (bt->kind == Type_Struct || bt->kind == Type_Union) {
  6927. GB_ASSERT(original_type->kind == Type_Named);
  6928. Entity *e = original_type->Named.type_name;
  6929. GB_ASSERT(e->kind == Entity_TypeName);
  6930. gbString s = gb_string_make_reserve(heap_allocator(), e->token.string.len+3);
  6931. s = gb_string_append_fmt(s, "%.*s(", LIT(e->token.string));
  6932. TypeTuple *tuple = get_record_polymorphic_params(bt);
  6933. if (tuple != nullptr) for_array(i, tuple->variables) {
  6934. Entity *v = tuple->variables[i];
  6935. String name = v->token.string;
  6936. if (i > 0) {
  6937. s = gb_string_append_fmt(s, ", ");
  6938. }
  6939. s = gb_string_append_fmt(s, "$%.*s", LIT(name));
  6940. if (v->kind == Entity_TypeName) {
  6941. if (v->type->kind != Type_Generic) {
  6942. s = gb_string_append_fmt(s, "=");
  6943. s = write_type_to_string(s, v->type, false);
  6944. }
  6945. } else if (v->kind == Entity_Constant) {
  6946. if (v->Constant.value.kind != ExactValue_Invalid) {
  6947. s = gb_string_append_fmt(s, "=");
  6948. s = write_exact_value_to_string(s, v->Constant.value);
  6949. }
  6950. }
  6951. }
  6952. s = gb_string_append_fmt(s, ")");
  6953. String new_name = make_string_c(s);
  6954. named_type->Named.name = new_name;
  6955. if (named_type->Named.type_name) {
  6956. named_type->Named.type_name->token.string = new_name;
  6957. }
  6958. }
  6959. operand->mode = Addressing_Type;
  6960. operand->type = named_type;
  6961. }
  6962. return err;
  6963. }
  6964. // returns true on success
  6965. gb_internal bool check_call_parameter_mixture(Slice<Ast *> const &args, char const *context, bool allow_mixed=false) {
  6966. bool success = true;
  6967. if (args.count > 0) {
  6968. if (allow_mixed) {
  6969. bool was_named = false;
  6970. for (Ast *arg : args) {
  6971. if (was_named && arg->kind != Ast_FieldValue) {
  6972. error(arg, "Non-named parameter is not allowed to follow named parameter i.e. 'field = value' in a %s", context);
  6973. success = false;
  6974. break;
  6975. }
  6976. was_named = was_named || arg->kind == Ast_FieldValue;
  6977. }
  6978. } else {
  6979. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  6980. for (Ast *arg : args) {
  6981. bool mix = false;
  6982. if (first_is_field_value) {
  6983. mix = arg->kind != Ast_FieldValue;
  6984. } else {
  6985. mix = arg->kind == Ast_FieldValue;
  6986. }
  6987. if (mix) {
  6988. error(arg, "Mixture of 'field = value' and value elements in a %s is not allowed", context);
  6989. success = false;
  6990. }
  6991. }
  6992. }
  6993. }
  6994. return success;
  6995. }
  6996. #define CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(context_, ...) if (!check_call_parameter_mixture(args, context_, ##__VA_ARGS__)) { \
  6997. operand->mode = Addressing_Invalid; \
  6998. operand->expr = call; \
  6999. return Expr_Stmt; \
  7000. }
  7001. gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  7002. if (proc != nullptr &&
  7003. proc->kind == Ast_BasicDirective) {
  7004. ast_node(bd, BasicDirective, proc);
  7005. String name = bd->name.string;
  7006. if (
  7007. name == "location" ||
  7008. name == "exists" ||
  7009. name == "assert" ||
  7010. name == "panic" ||
  7011. name == "defined" ||
  7012. name == "config" ||
  7013. name == "load" ||
  7014. name == "load_directory" ||
  7015. name == "load_hash" ||
  7016. name == "hash" ||
  7017. name == "caller_expression"
  7018. ) {
  7019. operand->mode = Addressing_Builtin;
  7020. operand->builtin_id = BuiltinProc_DIRECTIVE;
  7021. operand->expr = proc;
  7022. operand->type = t_invalid;
  7023. add_type_and_value(c, proc, operand->mode, operand->type, operand->value);
  7024. } else {
  7025. error(proc, "Unknown directive: #%.*s", LIT(name));
  7026. operand->expr = proc;
  7027. operand->type = t_invalid;
  7028. operand->mode = Addressing_Invalid;
  7029. return Expr_Expr;
  7030. }
  7031. if (inlining != ProcInlining_none) {
  7032. error(call, "Inlining operators are not allowed on built-in procedures");
  7033. }
  7034. } else {
  7035. if (proc != nullptr) {
  7036. check_expr_or_type(c, operand, proc);
  7037. } else {
  7038. GB_ASSERT(operand->expr != nullptr);
  7039. }
  7040. }
  7041. if (operand->mode == Addressing_Invalid) {
  7042. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("procedure call");
  7043. for (Ast *arg : args) {
  7044. if (arg->kind == Ast_FieldValue) {
  7045. arg = arg->FieldValue.value;
  7046. }
  7047. check_expr_base(c, operand, arg, nullptr);
  7048. }
  7049. operand->mode = Addressing_Invalid;
  7050. operand->expr = call;
  7051. return Expr_Stmt;
  7052. }
  7053. if (operand->mode == Addressing_Type) {
  7054. Type *t = operand->type;
  7055. if (is_type_polymorphic_record(t)) {
  7056. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("polymorphic type construction");
  7057. if (!is_type_named(t)) {
  7058. gbString s = expr_to_string(operand->expr);
  7059. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  7060. gb_string_free(s);
  7061. operand->mode = Addressing_Invalid;
  7062. operand->type = t_invalid;;
  7063. return Expr_Expr;
  7064. }
  7065. auto err = check_polymorphic_record_type(c, operand, call);
  7066. if (err == 0) {
  7067. Ast *ident = operand->expr;
  7068. while (ident->kind == Ast_SelectorExpr) {
  7069. Ast *s = ident->SelectorExpr.selector;
  7070. ident = s;
  7071. }
  7072. Type *ot = operand->type;
  7073. GB_ASSERT(ot->kind == Type_Named);
  7074. Entity *e = ot->Named.type_name;
  7075. add_entity_use(c, ident, e);
  7076. add_type_and_value(c, call, Addressing_Type, ot, empty_exact_value);
  7077. } else {
  7078. operand->mode = Addressing_Invalid;
  7079. operand->type = t_invalid;
  7080. }
  7081. } else {
  7082. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("type conversion");
  7083. operand->mode = Addressing_Invalid;
  7084. isize arg_count = args.count;
  7085. switch (arg_count) {
  7086. case 0:
  7087. {
  7088. gbString str = type_to_string(t);
  7089. error(call, "Missing argument in conversion to '%s'", str);
  7090. gb_string_free(str);
  7091. } break;
  7092. default:
  7093. {
  7094. gbString str = type_to_string(t);
  7095. if (t->kind == Type_Basic) {
  7096. ERROR_BLOCK();
  7097. switch (t->Basic.kind) {
  7098. case Basic_complex32:
  7099. case Basic_complex64:
  7100. case Basic_complex128:
  7101. error(call, "Too many arguments in conversion to '%s'", str);
  7102. error_line("\tSuggestion: %s(1+2i) or construct with 'complex'\n", str);
  7103. break;
  7104. case Basic_quaternion64:
  7105. case Basic_quaternion128:
  7106. case Basic_quaternion256:
  7107. error(call, "Too many arguments in conversion to '%s'", str);
  7108. error_line("\tSuggestion: %s(1+2i+3j+4k) or construct with 'quaternion'\n", str);
  7109. break;
  7110. default:
  7111. error(call, "Too many arguments in conversion to '%s'", str);
  7112. }
  7113. } else {
  7114. error(call, "Too many arguments in conversion to '%s'", str);
  7115. }
  7116. gb_string_free(str);
  7117. } break;
  7118. case 1: {
  7119. Ast *arg = args[0];
  7120. if (arg->kind == Ast_FieldValue) {
  7121. error(call, "'field = value' cannot be used in a type conversion");
  7122. arg = arg->FieldValue.value;
  7123. // NOTE(bill): Carry on the cast regardless
  7124. }
  7125. check_expr_with_type_hint(c, operand, arg, t);
  7126. if (operand->mode != Addressing_Invalid) {
  7127. if (is_type_polymorphic(t)) {
  7128. error(call, "A polymorphic type cannot be used in a type conversion");
  7129. } else {
  7130. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  7131. // as it assumes it is determining the type
  7132. check_cast(c, operand, t);
  7133. }
  7134. }
  7135. operand->type = t;
  7136. operand->expr = call;
  7137. if (operand->mode != Addressing_Invalid) {
  7138. update_untyped_expr_type(c, arg, t, false);
  7139. }
  7140. break;
  7141. }
  7142. }
  7143. }
  7144. return Expr_Expr;
  7145. }
  7146. if (operand->mode == Addressing_Builtin) {
  7147. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN("builtin call");
  7148. i32 id = operand->builtin_id;
  7149. Entity *e = entity_of_node(operand->expr);
  7150. if (e != nullptr && e->token.string == "expand_to_tuple") {
  7151. error(operand->expr, "'expand_to_tuple' has been replaced with 'expand_values'");
  7152. }
  7153. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  7154. operand->mode = Addressing_Invalid;
  7155. operand->type = t_invalid;
  7156. }
  7157. operand->expr = call;
  7158. return builtin_procs[id].kind;
  7159. }
  7160. CHECK_CALL_PARAMETER_MIXTURE_OR_RETURN(operand->mode == Addressing_ProcGroup ? "procedure group call": "procedure call", true);
  7161. Entity *initial_entity = entity_of_node(operand->expr);
  7162. if (initial_entity != nullptr && initial_entity->kind == Entity_Procedure) {
  7163. if (initial_entity->Procedure.deferred_procedure.entity != nullptr) {
  7164. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  7165. if (c->decl) {
  7166. c->decl->defer_used += 1;
  7167. }
  7168. }
  7169. add_entity_use(c, operand->expr, initial_entity);
  7170. if (initial_entity->Procedure.entry_point_only) {
  7171. if (c->curr_proc_decl && c->curr_proc_decl->entity == c->info->entry_point) {
  7172. // Okay
  7173. } else {
  7174. error(operand->expr, "Procedures with the attribute '@(entry_point_only)' can only be called directly from the user-level entry point procedure");
  7175. }
  7176. }
  7177. }
  7178. if (operand->mode != Addressing_ProcGroup) {
  7179. Type *proc_type = base_type(operand->type);
  7180. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  7181. bool valid_mode = is_operand_value(*operand);
  7182. if (!valid_type || !valid_mode) {
  7183. Ast *e = operand->expr;
  7184. gbString str = expr_to_string(e);
  7185. gbString type_str = type_to_string(operand->type);
  7186. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  7187. gb_string_free(type_str);
  7188. gb_string_free(str);
  7189. operand->mode = Addressing_Invalid;
  7190. operand->expr = call;
  7191. return Expr_Stmt;
  7192. }
  7193. }
  7194. CallArgumentData data = check_call_arguments(c, operand, call);
  7195. Type *result_type = data.result_type;
  7196. gb_zero_item(operand);
  7197. operand->expr = call;
  7198. if (result_type == t_invalid) {
  7199. operand->mode = Addressing_Invalid;
  7200. operand->type = t_invalid;
  7201. return Expr_Stmt;
  7202. }
  7203. Type *pt = base_type(operand->type);
  7204. if (pt == nullptr) {
  7205. pt = t_invalid;
  7206. }
  7207. if (pt == t_invalid) {
  7208. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7209. pt = type_of_expr(operand->expr->CallExpr.proc);
  7210. }
  7211. if (pt == t_invalid && data.gen_entity) {
  7212. pt = data.gen_entity->type;
  7213. }
  7214. }
  7215. pt = base_type(pt);
  7216. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  7217. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  7218. ERROR_BLOCK();
  7219. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  7220. error_line("\tSuggestion: 'context = runtime.default_context()'");
  7221. }
  7222. }
  7223. if (result_type == nullptr) {
  7224. operand->mode = Addressing_NoValue;
  7225. } else {
  7226. GB_ASSERT(is_type_tuple(result_type));
  7227. isize count = result_type->Tuple.variables.count;
  7228. switch (count) {
  7229. case 0:
  7230. operand->mode = Addressing_NoValue;
  7231. break;
  7232. case 1:
  7233. operand->mode = Addressing_Value;
  7234. operand->type = result_type->Tuple.variables[0]->type;
  7235. break;
  7236. default:
  7237. operand->mode = Addressing_Value;
  7238. operand->type = result_type;
  7239. break;
  7240. }
  7241. }
  7242. bool is_call_inlined = false;
  7243. switch (inlining) {
  7244. case ProcInlining_inline:
  7245. is_call_inlined = true;
  7246. if (proc != nullptr) {
  7247. Entity *e = entity_from_expr(proc);
  7248. if (e != nullptr && e->kind == Entity_Procedure) {
  7249. DeclInfo *decl = e->decl_info;
  7250. if (decl->proc_lit) {
  7251. ast_node(pl, ProcLit, decl->proc_lit);
  7252. if (pl->inlining == ProcInlining_no_inline) {
  7253. error(call, "'#force_inline' cannot be applied to a procedure that has been marked as '#force_no_inline'");
  7254. }
  7255. }
  7256. }
  7257. }
  7258. break;
  7259. case ProcInlining_no_inline:
  7260. break;
  7261. case ProcInlining_none:
  7262. if (proc != nullptr) {
  7263. Entity *e = entity_from_expr(proc);
  7264. if (e != nullptr && e->kind == Entity_Procedure) {
  7265. DeclInfo *decl = e->decl_info;
  7266. if (decl->proc_lit) {
  7267. ast_node(pl, ProcLit, decl->proc_lit);
  7268. if (pl->inlining == ProcInlining_inline) {
  7269. is_call_inlined = true;
  7270. }
  7271. }
  7272. }
  7273. }
  7274. }
  7275. {
  7276. String invalid;
  7277. if (pt->kind == Type_Proc && pt->Proc.require_target_feature.len != 0) {
  7278. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.require_target_feature, &invalid)) {
  7279. error(call, "Called procedure requires target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7280. } else if (!check_target_feature_is_enabled(pt->Proc.require_target_feature, &invalid)) {
  7281. error(call, "Calling this procedure requires target feature '%.*s' to be enabled", LIT(invalid));
  7282. }
  7283. }
  7284. if (pt->kind == Type_Proc && pt->Proc.enable_target_feature.len != 0) {
  7285. if (!check_target_feature_is_valid_for_target_arch(pt->Proc.enable_target_feature, &invalid)) {
  7286. error(call, "Called procedure enables target feature '%.*s' which is invalid for the build target", LIT(invalid));
  7287. }
  7288. // NOTE: Due to restrictions in LLVM you can not inline calls with a superset of features.
  7289. if (is_call_inlined) {
  7290. if (c->curr_proc_decl == nullptr) {
  7291. error(call, "Calling a '#force_inline' procedure that enables target features is not allowed at file scope");
  7292. } else {
  7293. GB_ASSERT(c->curr_proc_decl->entity);
  7294. GB_ASSERT(c->curr_proc_decl->entity->type->kind == Type_Proc);
  7295. String scope_features = c->curr_proc_decl->entity->type->Proc.enable_target_feature;
  7296. if (!check_target_feature_is_superset_of(scope_features, pt->Proc.enable_target_feature, &invalid)) {
  7297. ERROR_BLOCK();
  7298. error(call, "Inlined procedure enables target feature '%.*s', this requires the calling procedure to at least enable the same feature", LIT(invalid));
  7299. error_line("\tSuggested Example: @(enable_target_feature=\"%.*s\")\n", LIT(invalid));
  7300. }
  7301. }
  7302. }
  7303. }
  7304. }
  7305. operand->expr = call;
  7306. {
  7307. Type *type = nullptr;
  7308. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7309. type = type_of_expr(operand->expr->CallExpr.proc);
  7310. }
  7311. if (type == nullptr) {
  7312. type = pt;
  7313. }
  7314. type = base_type(type);
  7315. if (type->kind == Type_Proc && type->Proc.optional_ok && type->Proc.result_count > 0) {
  7316. operand->mode = Addressing_OptionalOk;
  7317. operand->type = type->Proc.results->Tuple.variables[0]->type;
  7318. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  7319. operand->expr->CallExpr.optional_ok_one = true;
  7320. }
  7321. }
  7322. }
  7323. return Expr_Expr;
  7324. }
  7325. gb_internal void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  7326. check_expr_base(c, o, e, t);
  7327. check_not_tuple(c, o);
  7328. char const *err_str = nullptr;
  7329. switch (o->mode) {
  7330. case Addressing_NoValue:
  7331. err_str = "used as a value";
  7332. break;
  7333. case Addressing_Type:
  7334. if (t == nullptr || !is_type_typeid(t)) {
  7335. err_str = "is not an expression but a type, in this context it is ambiguous";
  7336. }
  7337. break;
  7338. case Addressing_Builtin:
  7339. err_str = "must be called";
  7340. break;
  7341. }
  7342. if (err_str != nullptr) {
  7343. gbString str = expr_to_string(e);
  7344. error(e, "'%s' %s", str, err_str);
  7345. gb_string_free(str);
  7346. o->mode = Addressing_Invalid;
  7347. }
  7348. }
  7349. gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  7350. switch (t->kind) {
  7351. case Type_Basic:
  7352. if (t->Basic.kind == Basic_string) {
  7353. if (o->mode == Addressing_Constant) {
  7354. GB_ASSERT(o->value.kind == ExactValue_String);
  7355. *max_count = o->value.value_string.len;
  7356. }
  7357. if (o->mode != Addressing_Constant) {
  7358. o->mode = Addressing_Value;
  7359. }
  7360. o->type = t_u8;
  7361. return true;
  7362. } else if (t->Basic.kind == Basic_string16) {
  7363. if (o->mode == Addressing_Constant) {
  7364. GB_ASSERT(o->value.kind == ExactValue_String16);
  7365. *max_count = o->value.value_string16.len;
  7366. }
  7367. if (o->mode != Addressing_Constant) {
  7368. o->mode = Addressing_Value;
  7369. }
  7370. o->type = t_u16;
  7371. return true;
  7372. } else if (t->Basic.kind == Basic_UntypedString) {
  7373. if (o->mode == Addressing_Constant) {
  7374. *max_count = o->value.value_string.len;
  7375. o->type = t_u8;
  7376. return true;
  7377. }
  7378. return false;
  7379. }
  7380. break;
  7381. case Type_MultiPointer:
  7382. o->type = t->MultiPointer.elem;
  7383. if (o->mode != Addressing_Constant) {
  7384. o->mode = Addressing_Variable;
  7385. }
  7386. return true;
  7387. case Type_Array:
  7388. *max_count = t->Array.count;
  7389. if (indirection) {
  7390. o->mode = Addressing_Variable;
  7391. } else if (o->mode != Addressing_Variable &&
  7392. o->mode != Addressing_Constant) {
  7393. o->mode = Addressing_Value;
  7394. }
  7395. o->type = t->Array.elem;
  7396. return true;
  7397. case Type_EnumeratedArray:
  7398. *max_count = t->EnumeratedArray.count;
  7399. if (indirection) {
  7400. o->mode = Addressing_Variable;
  7401. } else if (o->mode != Addressing_Variable &&
  7402. o->mode != Addressing_Constant) {
  7403. o->mode = Addressing_Value;
  7404. }
  7405. o->type = t->EnumeratedArray.elem;
  7406. return true;
  7407. case Type_Matrix:
  7408. if (indirection) {
  7409. o->mode = Addressing_Variable;
  7410. } else if (o->mode != Addressing_Variable) {
  7411. o->mode = Addressing_Value;
  7412. }
  7413. if (t->Matrix.is_row_major) {
  7414. *max_count = t->Matrix.row_count;
  7415. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.column_count);
  7416. } else {
  7417. *max_count = t->Matrix.column_count;
  7418. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  7419. }
  7420. return true;
  7421. case Type_Slice:
  7422. o->type = t->Slice.elem;
  7423. if (o->mode != Addressing_Constant) {
  7424. o->mode = Addressing_Variable;
  7425. }
  7426. return true;
  7427. case Type_DynamicArray:
  7428. o->type = t->DynamicArray.elem;
  7429. if (o->mode != Addressing_Constant) {
  7430. o->mode = Addressing_Variable;
  7431. }
  7432. return true;
  7433. case Type_Struct:
  7434. if (t->Struct.soa_kind != StructSoa_None) {
  7435. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7436. *max_count = t->Struct.soa_count;
  7437. }
  7438. o->type = t->Struct.soa_elem;
  7439. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable || indirection) {
  7440. o->mode = Addressing_SoaVariable;
  7441. } else {
  7442. o->mode = Addressing_Value;
  7443. }
  7444. return true;
  7445. }
  7446. return false;
  7447. }
  7448. if (is_type_pointer(original_type) && indirection) {
  7449. Type *ptr = base_type(original_type);
  7450. if (ptr->kind == Type_MultiPointer && o->mode == Addressing_SoaVariable) {
  7451. o->type = ptr->MultiPointer.elem;
  7452. o->mode = Addressing_Value;
  7453. return true;
  7454. }
  7455. }
  7456. return false;
  7457. }
  7458. gb_internal bool ternary_compare_types(Type *x, Type *y) {
  7459. if (is_type_untyped_uninit(x)) {
  7460. return true;
  7461. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  7462. return true;
  7463. } else if (is_type_untyped_uninit(y)) {
  7464. return true;
  7465. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  7466. return true;
  7467. }
  7468. return are_types_identical(x, y);
  7469. }
  7470. 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) {
  7471. if (!is_ast_range(node)) {
  7472. return false;
  7473. }
  7474. ast_node(ie, BinaryExpr, node);
  7475. check_expr_with_type_hint(c, x, ie->left, type_hint);
  7476. if (x->mode == Addressing_Invalid) {
  7477. return false;
  7478. }
  7479. check_expr_with_type_hint(c, y, ie->right, type_hint);
  7480. if (y->mode == Addressing_Invalid) {
  7481. return false;
  7482. }
  7483. convert_to_typed(c, x, y->type);
  7484. if (x->mode == Addressing_Invalid) {
  7485. return false;
  7486. }
  7487. convert_to_typed(c, y, x->type);
  7488. if (y->mode == Addressing_Invalid) {
  7489. return false;
  7490. }
  7491. convert_to_typed(c, x, default_type(y->type));
  7492. if (x->mode == Addressing_Invalid) {
  7493. return false;
  7494. }
  7495. convert_to_typed(c, y, default_type(x->type));
  7496. if (y->mode == Addressing_Invalid) {
  7497. return false;
  7498. }
  7499. if (!are_types_identical(x->type, y->type)) {
  7500. if (x->type != t_invalid &&
  7501. y->type != t_invalid) {
  7502. gbString xt = type_to_string(x->type);
  7503. gbString yt = type_to_string(y->type);
  7504. gbString expr_str = expr_to_string(x->expr);
  7505. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  7506. gb_string_free(expr_str);
  7507. gb_string_free(yt);
  7508. gb_string_free(xt);
  7509. }
  7510. return false;
  7511. }
  7512. Type *type = x->type;
  7513. if (is_for_loop) {
  7514. if (!is_type_integer(type) && !is_type_float(type) && !is_type_enum(type)) {
  7515. error(ie->op, "Only numerical types are allowed within interval expressions");
  7516. return false;
  7517. }
  7518. } else {
  7519. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  7520. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  7521. return false;
  7522. }
  7523. }
  7524. if (x->mode == Addressing_Constant &&
  7525. y->mode == Addressing_Constant) {
  7526. ExactValue a = x->value;
  7527. ExactValue b = y->value;
  7528. GB_ASSERT(are_types_identical(x->type, y->type));
  7529. TokenKind op = Token_Lt;
  7530. switch (ie->op.kind) {
  7531. case Token_Ellipsis: op = Token_LtEq; break; // ..
  7532. case Token_RangeFull: op = Token_LtEq; break; // ..=
  7533. case Token_RangeHalf: op = Token_Lt; break; // ..<
  7534. default: error(ie->op, "Invalid range operator"); break;
  7535. }
  7536. bool ok = compare_exact_values(op, a, b);
  7537. if (!ok) {
  7538. // TODO(bill): Better error message
  7539. error(ie->op, "Invalid interval range");
  7540. return false;
  7541. }
  7542. ExactValue inline_for_depth = exact_value_sub(b, a);
  7543. if (ie->op.kind != Token_RangeHalf) {
  7544. inline_for_depth = exact_value_increment_one(inline_for_depth);
  7545. }
  7546. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  7547. } else if (inline_for_depth_ != nullptr) {
  7548. error(ie->op, "Interval expressions must be constant");
  7549. return false;
  7550. }
  7551. add_type_and_value(c, ie->left, x->mode, x->type, x->value);
  7552. add_type_and_value(c, ie->right, y->mode, y->type, y->value);
  7553. return true;
  7554. }
  7555. gb_internal bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  7556. if (is_operand_nil(*o)) {
  7557. return true;
  7558. }
  7559. Ast *expr = unparen_expr(o->expr);
  7560. if (expr != nullptr) {
  7561. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  7562. if (e != nullptr && e->kind == Entity_Procedure) {
  7563. return true;
  7564. }
  7565. if (expr->kind == Ast_ProcLit) {
  7566. add_type_and_value(c, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  7567. return true;
  7568. }
  7569. }
  7570. return o->mode == Addressing_Constant;
  7571. }
  7572. gb_internal bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  7573. if (is_type_enum(th)) {
  7574. Type *enum_type = base_type(th);
  7575. GB_ASSERT(enum_type->kind == Type_Enum);
  7576. String name = ise->selector->Ident.token.string;
  7577. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  7578. if (e == nullptr) {
  7579. return false;
  7580. }
  7581. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  7582. GB_ASSERT(e->kind == Entity_Constant);
  7583. o->value = e->Constant.value;
  7584. o->mode = Addressing_Constant;
  7585. o->type = e->type;
  7586. return true;
  7587. }
  7588. if (is_type_union(th)) {
  7589. TEMPORARY_ALLOCATOR_GUARD();
  7590. Type *union_type = base_type(th);
  7591. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  7592. for (Type *vt : union_type->Union.variants) {
  7593. Operand x = {};
  7594. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  7595. array_add(&operands, x);
  7596. }
  7597. }
  7598. if (operands.count == 1) {
  7599. *o = operands[0];
  7600. return true;
  7601. }
  7602. }
  7603. return false;
  7604. }
  7605. gb_internal ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7606. ast_node(ise, ImplicitSelectorExpr, node);
  7607. o->type = t_invalid;
  7608. o->expr = node;
  7609. o->mode = Addressing_Invalid;
  7610. Type *th = type_hint;
  7611. if (th == nullptr) {
  7612. gbString str = expr_to_string(node);
  7613. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  7614. gb_string_free(str);
  7615. return Expr_Expr;
  7616. }
  7617. o->type = th;
  7618. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  7619. if (!ok) {
  7620. String name = ise->selector->Ident.token.string;
  7621. if (is_type_enum(th)) {
  7622. ERROR_BLOCK();
  7623. Type *bt = base_type(th);
  7624. GB_ASSERT(bt->kind == Type_Enum);
  7625. gbString typ = type_to_string(th);
  7626. defer (gb_string_free(typ));
  7627. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  7628. check_did_you_mean_type(name, bt->Enum.fields);
  7629. } else if (is_type_bit_set(th) && is_type_enum(th->BitSet.elem)) {
  7630. ERROR_BLOCK();
  7631. gbString typ = type_to_string(th);
  7632. gbString str = expr_to_string(node);
  7633. error(node, "Cannot convert enum value to '%s'", typ);
  7634. error_line("\tSuggestion: Did you mean '{ %s }'?\n", str);
  7635. gb_string_free(typ);
  7636. gb_string_free(str);
  7637. } else {
  7638. gbString typ = type_to_string(th);
  7639. gbString str = expr_to_string(node);
  7640. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  7641. gb_string_free(str);
  7642. gb_string_free(typ);
  7643. }
  7644. }
  7645. o->expr = node;
  7646. return Expr_Expr;
  7647. }
  7648. gb_internal void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_, bool change_operand) {
  7649. switch (x->mode) {
  7650. case Addressing_MapIndex:
  7651. case Addressing_OptionalOk:
  7652. case Addressing_OptionalOkPtr:
  7653. if (val_type_) *val_type_ = x->type;
  7654. break;
  7655. default:
  7656. if (ok_type_) *ok_type_ = x->type;
  7657. return;
  7658. }
  7659. Ast *expr = unparen_expr(x->expr);
  7660. if (expr->kind == Ast_CallExpr) {
  7661. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  7662. if (is_type_proc(pt)) {
  7663. Type *tuple = pt->Proc.results;
  7664. if (pt->Proc.result_count >= 2) {
  7665. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7666. }
  7667. if (change_operand) {
  7668. expr->CallExpr.optional_ok_one = false;
  7669. x->type = tuple;
  7670. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7671. }
  7672. return;
  7673. }
  7674. }
  7675. Type *tuple = make_optional_ok_type(x->type);
  7676. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  7677. if (change_operand) {
  7678. add_type_and_value(c, x->expr, x->mode, tuple, x->value);
  7679. x->type = tuple;
  7680. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  7681. }
  7682. }
  7683. gb_internal void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7684. ast_node(ie, MatrixIndexExpr, node);
  7685. check_expr(c, o, ie->expr);
  7686. node->viral_state_flags |= ie->expr->viral_state_flags;
  7687. if (o->mode == Addressing_Invalid) {
  7688. o->expr = node;
  7689. return;
  7690. }
  7691. Type *t = base_type(type_deref(o->type));
  7692. bool is_ptr = is_type_pointer(o->type);
  7693. bool is_const = o->mode == Addressing_Constant;
  7694. if (t->kind != Type_Matrix) {
  7695. gbString str = expr_to_string(o->expr);
  7696. gbString type_str = type_to_string(o->type);
  7697. defer (gb_string_free(str));
  7698. defer (gb_string_free(type_str));
  7699. if (is_const) {
  7700. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  7701. } else {
  7702. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  7703. }
  7704. o->mode = Addressing_Invalid;
  7705. o->expr = node;
  7706. return;
  7707. }
  7708. o->type = t->Matrix.elem;
  7709. if (is_ptr) {
  7710. o->mode = Addressing_Variable;
  7711. } else if (o->mode != Addressing_Variable) {
  7712. o->mode = Addressing_Value;
  7713. }
  7714. if (ie->row_index == nullptr) {
  7715. gbString str = expr_to_string(o->expr);
  7716. error(o->expr, "Missing row index for '%s'", str);
  7717. gb_string_free(str);
  7718. o->mode = Addressing_Invalid;
  7719. o->expr = node;
  7720. return;
  7721. }
  7722. if (ie->column_index == nullptr) {
  7723. gbString str = expr_to_string(o->expr);
  7724. error(o->expr, "Missing column index for '%s'", str);
  7725. gb_string_free(str);
  7726. o->mode = Addressing_Invalid;
  7727. o->expr = node;
  7728. return;
  7729. }
  7730. i64 row_count = t->Matrix.row_count;
  7731. i64 column_count = t->Matrix.column_count;
  7732. i64 row_index = 0;
  7733. i64 column_index = 0;
  7734. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  7735. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  7736. if (is_const && (ie->row_index->tav.mode != Addressing_Constant || ie->column_index->tav.mode != Addressing_Constant)) {
  7737. error(o->expr, "Cannot index constant matrix with non-constant indices '%s'", expr_to_string(node));
  7738. }
  7739. gb_unused(row_ok);
  7740. gb_unused(column_ok);
  7741. }
  7742. struct TypeAndToken {
  7743. Type *type;
  7744. Token token;
  7745. };
  7746. typedef PtrMap<uintptr, TypeAndToken> SeenMap;
  7747. gb_internal void add_constant_switch_case(CheckerContext *ctx, SeenMap *seen, Operand operand, bool use_expr = true) {
  7748. if (operand.mode != Addressing_Constant) {
  7749. return;
  7750. }
  7751. if (operand.value.kind == ExactValue_Invalid) {
  7752. return;
  7753. }
  7754. uintptr key = hash_exact_value(operand.value);
  7755. GB_ASSERT(key != 0);
  7756. isize count = multi_map_count(seen, key);
  7757. if (count) {
  7758. TEMPORARY_ALLOCATOR_GUARD();
  7759. TypeAndToken *taps = gb_alloc_array(temporary_allocator(), TypeAndToken, count);
  7760. multi_map_get_all(seen, key, taps);
  7761. for (isize i = 0; i < count; i++) {
  7762. TypeAndToken tap = taps[i];
  7763. Operand to = {};
  7764. to.mode = Addressing_Value;
  7765. to.type = tap.type;
  7766. if (!check_is_assignable_to_with_score(ctx, &to, operand.type, nullptr)) {
  7767. continue;
  7768. }
  7769. TokenPos pos = tap.token.pos;
  7770. if (use_expr) {
  7771. gbString expr_str = expr_to_string(operand.expr);
  7772. error(operand.expr,
  7773. "Duplicate case '%s'\n"
  7774. "\tprevious case at %s",
  7775. expr_str,
  7776. token_pos_to_string(pos));
  7777. gb_string_free(expr_str);
  7778. } else {
  7779. error(operand.expr, "Duplicate case found with previous case at %s", token_pos_to_string(pos));
  7780. }
  7781. return;
  7782. }
  7783. }
  7784. TypeAndToken tap = {operand.type, ast_token(operand.expr)};
  7785. multi_map_insert(seen, key, tap);
  7786. }
  7787. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, TokenKind upper_op, Operand const &x, Operand const &lhs, Operand const &rhs) {
  7788. if (is_type_enum(x.type)) {
  7789. // TODO(bill): Fix this logic so it's fast!!!
  7790. i64 v0 = exact_value_to_i64(lhs.value);
  7791. i64 v1 = exact_value_to_i64(rhs.value);
  7792. Operand v = {};
  7793. v.mode = Addressing_Constant;
  7794. v.type = x.type;
  7795. v.expr = x.expr;
  7796. Type *bt = base_type(x.type);
  7797. GB_ASSERT(bt->kind == Type_Enum);
  7798. for (i64 vi = v0; vi <= v1; vi++) {
  7799. if (upper_op != Token_LtEq && vi == v1) {
  7800. break;
  7801. }
  7802. v.value = exact_value_i64(vi);
  7803. add_constant_switch_case(ctx, seen, v);
  7804. }
  7805. } else {
  7806. add_constant_switch_case(ctx, seen, lhs);
  7807. if (upper_op == Token_LtEq) {
  7808. add_constant_switch_case(ctx, seen, rhs);
  7809. }
  7810. }
  7811. }
  7812. gb_internal void add_to_seen_map(CheckerContext *ctx, SeenMap *seen, Operand const &x) {
  7813. add_constant_switch_case(ctx, seen, x);
  7814. }
  7815. gb_internal ExprKind check_basic_directive_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7816. ast_node(bd, BasicDirective, node);
  7817. ExprKind kind = Expr_Expr;
  7818. o->mode = Addressing_Constant;
  7819. String name = bd->name.string;
  7820. if (name == "file") {
  7821. String file = get_file_path_string(bd->token.pos.file_id);
  7822. switch (build_context.source_code_location_info) {
  7823. case SourceCodeLocationInfo_Normal:
  7824. break;
  7825. case SourceCodeLocationInfo_Obfuscated:
  7826. file = obfuscate_string(file, "F");
  7827. break;
  7828. case SourceCodeLocationInfo_Filename:
  7829. file = last_path_element(file);
  7830. break;
  7831. case SourceCodeLocationInfo_None:
  7832. file = str_lit("");
  7833. break;
  7834. }
  7835. o->type = t_untyped_string;
  7836. o->value = exact_value_string(file);
  7837. } else if (name == "directory") {
  7838. String file = get_file_path_string(bd->token.pos.file_id);
  7839. String path = dir_from_path(file);
  7840. switch (build_context.source_code_location_info) {
  7841. case SourceCodeLocationInfo_Normal:
  7842. break;
  7843. case SourceCodeLocationInfo_Obfuscated:
  7844. path = obfuscate_string(path, "D");
  7845. break;
  7846. case SourceCodeLocationInfo_Filename:
  7847. path = last_path_element(path);
  7848. break;
  7849. case SourceCodeLocationInfo_None:
  7850. path = str_lit("");
  7851. break;
  7852. }
  7853. o->type = t_untyped_string;
  7854. o->value = exact_value_string(path);
  7855. } else if (name == "line") {
  7856. i32 line = bd->token.pos.line;
  7857. switch (build_context.source_code_location_info) {
  7858. case SourceCodeLocationInfo_Normal:
  7859. break;
  7860. case SourceCodeLocationInfo_Obfuscated:
  7861. line = obfuscate_i32(line);
  7862. break;
  7863. case SourceCodeLocationInfo_Filename:
  7864. break;
  7865. case SourceCodeLocationInfo_None:
  7866. line = 0;
  7867. break;
  7868. }
  7869. o->type = t_untyped_integer;
  7870. o->value = exact_value_i64(line);
  7871. } else if (name == "procedure") {
  7872. if (c->curr_proc_decl == nullptr) {
  7873. error(node, "#procedure may only be used within procedures");
  7874. o->type = t_untyped_string;
  7875. o->value = exact_value_string(str_lit(""));
  7876. } else {
  7877. String p = c->proc_name;
  7878. switch (build_context.source_code_location_info) {
  7879. case SourceCodeLocationInfo_Normal:
  7880. break;
  7881. case SourceCodeLocationInfo_Obfuscated:
  7882. p = obfuscate_string(p, "P");
  7883. break;
  7884. case SourceCodeLocationInfo_Filename:
  7885. break;
  7886. case SourceCodeLocationInfo_None:
  7887. p = str_lit("");
  7888. break;
  7889. }
  7890. o->type = t_untyped_string;
  7891. o->value = exact_value_string(p);
  7892. }
  7893. } else if (name == "caller_location") {
  7894. init_core_source_code_location(c->checker);
  7895. error(node, "#caller_location may only be used as a default argument parameter");
  7896. o->type = t_source_code_location;
  7897. o->mode = Addressing_Value;
  7898. } else if (name == "caller_expression") {
  7899. error(node, "#caller_expression may only be used as a default argument parameter");
  7900. o->type = t_string;
  7901. o->mode = Addressing_Value;
  7902. } else if (name == "branch_location") {
  7903. if (!c->in_defer) {
  7904. error(node, "#branch_location may only be used within a 'defer' statement");
  7905. } else if (c->curr_proc_decl) {
  7906. Entity *e = c->curr_proc_decl->entity;
  7907. if (e != nullptr) {
  7908. GB_ASSERT(e->kind == Entity_Procedure);
  7909. e->Procedure.uses_branch_location = true;
  7910. }
  7911. }
  7912. o->type = t_source_code_location;
  7913. o->mode = Addressing_Value;
  7914. } else {
  7915. if (name == "location") {
  7916. init_core_source_code_location(c->checker);
  7917. error(node, "'#location' must be used as a call, i.e. #location(proc), where #location() defaults to the procedure in which it was used.");
  7918. o->type = t_source_code_location;
  7919. o->mode = Addressing_Value;
  7920. } else if (
  7921. name == "assert" ||
  7922. name == "defined" ||
  7923. name == "config" ||
  7924. name == "exists" ||
  7925. name == "load" ||
  7926. name == "load_hash" ||
  7927. name == "load_directory" ||
  7928. name == "load_or"
  7929. ) {
  7930. error(node, "'#%.*s' must be used as a call", LIT(name));
  7931. o->type = t_invalid;
  7932. o->mode = Addressing_Invalid;
  7933. } else {
  7934. error(node, "Unknown directive: #%.*s", LIT(name));
  7935. o->type = t_invalid;
  7936. o->mode = Addressing_Invalid;
  7937. }
  7938. }
  7939. return kind;
  7940. }
  7941. gb_internal ExprKind check_ternary_if_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7942. ExprKind kind = Expr_Expr;
  7943. Operand cond = {Addressing_Invalid};
  7944. ast_node(te, TernaryIfExpr, node);
  7945. check_expr(c, &cond, te->cond);
  7946. node->viral_state_flags |= te->cond->viral_state_flags;
  7947. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  7948. error(te->cond, "Non-boolean condition in ternary if expression");
  7949. }
  7950. Operand x = {Addressing_Invalid};
  7951. Operand y = {Addressing_Invalid};
  7952. check_expr_or_type(c, &x, te->x, type_hint);
  7953. node->viral_state_flags |= te->x->viral_state_flags;
  7954. if (te->y != nullptr) {
  7955. Type *th = type_hint;
  7956. if (type_hint == nullptr && is_type_typed(x.type)) {
  7957. th = x.type;
  7958. }
  7959. check_expr_or_type(c, &y, te->y, th);
  7960. node->viral_state_flags |= te->y->viral_state_flags;
  7961. } else {
  7962. error(node, "A ternary expression must have an else clause");
  7963. return kind;
  7964. }
  7965. if (x.mode == Addressing_Type || y.mode == Addressing_Type) {
  7966. Ast *type_expr = (x.mode == Addressing_Type) ? x.expr : y.expr;
  7967. gbString type_string = expr_to_string(type_expr);
  7968. error(node, "Type %s is invalid operand for ternary if expression", type_string);
  7969. gb_string_free(type_string);
  7970. return kind;
  7971. }
  7972. bool use_type_hint = type_hint != nullptr && (is_operand_nil(x) || is_operand_nil(y));
  7973. convert_to_typed(c, &x, use_type_hint ? type_hint : y.type);
  7974. if (x.mode == Addressing_Invalid) {
  7975. return kind;
  7976. }
  7977. convert_to_typed(c, &y, use_type_hint ? type_hint : x.type);
  7978. if (y.mode == Addressing_Invalid) {
  7979. x.mode = Addressing_Invalid;
  7980. return kind;
  7981. }
  7982. // NOTE(bill, 2023-01-30): Allow for expression like this:
  7983. // x: union{f32} = f32(123) if cond else nil
  7984. if (type_hint && !is_type_any(type_hint)) {
  7985. if (check_is_assignable_to(c, &x, type_hint) && check_is_assignable_to(c, &y, type_hint)) {
  7986. check_cast(c, &x, type_hint);
  7987. check_cast(c, &y, type_hint);
  7988. }
  7989. }
  7990. if (!ternary_compare_types(x.type, y.type)) {
  7991. gbString its = type_to_string(x.type);
  7992. gbString ets = type_to_string(y.type);
  7993. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  7994. gb_string_free(ets);
  7995. gb_string_free(its);
  7996. return kind;
  7997. }
  7998. o->type = x.type;
  7999. if (is_type_untyped_nil(o->type) || is_type_untyped_uninit(o->type)) {
  8000. o->type = y.type;
  8001. }
  8002. o->mode = Addressing_Value;
  8003. o->expr = node;
  8004. if (type_hint != nullptr && is_type_untyped(o->type) && !is_type_any(type_hint)) {
  8005. if (check_cast_internal(c, &x, type_hint) &&
  8006. check_cast_internal(c, &y, type_hint)) {
  8007. convert_to_typed(c, o, type_hint);
  8008. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  8009. o->type = type_hint;
  8010. }
  8011. }
  8012. return kind;
  8013. }
  8014. gb_internal ExprKind check_ternary_when_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8015. ExprKind kind = Expr_Expr;
  8016. Operand cond = {};
  8017. ast_node(te, TernaryWhenExpr, node);
  8018. check_expr(c, &cond, te->cond);
  8019. node->viral_state_flags |= te->cond->viral_state_flags;
  8020. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  8021. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  8022. return kind;
  8023. }
  8024. if (cond.value.value_bool) {
  8025. check_expr_or_type(c, o, te->x, type_hint);
  8026. node->viral_state_flags |= te->x->viral_state_flags;
  8027. } else {
  8028. if (te->y != nullptr) {
  8029. check_expr_or_type(c, o, te->y, type_hint);
  8030. node->viral_state_flags |= te->y->viral_state_flags;
  8031. } else {
  8032. error(node, "A ternary when expression must have an else clause");
  8033. return kind;
  8034. }
  8035. }
  8036. return kind;
  8037. }
  8038. gb_internal ExprKind check_or_else_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8039. ast_node(oe, OrElseExpr, node);
  8040. String name = oe->token.string;
  8041. Ast *arg = oe->x;
  8042. Ast *default_value = oe->y;
  8043. Operand x = {};
  8044. Operand y = {};
  8045. // NOTE(bill, 2022-08-11): edge case to handle #load(path) or_else default
  8046. if (is_load_directive_call(arg)) {
  8047. LoadDirectiveResult res = check_load_directive(c, &x, arg, type_hint, false);
  8048. // Allow for chaining of '#load(path) or_else #load(path)'
  8049. if (!(is_load_directive_call(default_value) && res == LoadDirective_Success)) {
  8050. bool y_is_diverging = false;
  8051. check_expr_base(c, &y, default_value, x.type);
  8052. switch (y.mode) {
  8053. case Addressing_NoValue:
  8054. if (is_diverging_expr(y.expr)) {
  8055. // Allow
  8056. y.mode = Addressing_Value;
  8057. y_is_diverging = true;
  8058. } else {
  8059. error_operand_no_value(&y);
  8060. y.mode = Addressing_Invalid;
  8061. }
  8062. break;
  8063. case Addressing_Type:
  8064. error_operand_not_expression(&y);
  8065. y.mode = Addressing_Invalid;
  8066. break;
  8067. }
  8068. if (y.mode == Addressing_Invalid) {
  8069. o->mode = Addressing_Value;
  8070. o->type = t_invalid;
  8071. o->expr = node;
  8072. return Expr_Expr;
  8073. }
  8074. if (!y_is_diverging) {
  8075. check_assignment(c, &y, x.type, name);
  8076. if (y.mode != Addressing_Constant) {
  8077. error(y.expr, "expected a constant expression on the right-hand side of 'or_else' in conjuction with '#load'");
  8078. }
  8079. }
  8080. }
  8081. if (res == LoadDirective_Success) {
  8082. *o = x;
  8083. } else {
  8084. *o = y;
  8085. }
  8086. o->expr = node;
  8087. return Expr_Expr;
  8088. }
  8089. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  8090. if (x.mode == Addressing_Invalid) {
  8091. o->mode = Addressing_Value;
  8092. o->type = t_invalid;
  8093. o->expr = node;
  8094. return Expr_Expr;
  8095. }
  8096. Type *left_type = nullptr;
  8097. Type *right_type = nullptr;
  8098. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  8099. add_type_and_value(c, arg, x.mode, x.type, x.value);
  8100. bool y_is_diverging = false;
  8101. check_expr_base(c, &y, default_value, left_type);
  8102. switch (y.mode) {
  8103. case Addressing_NoValue:
  8104. if (is_diverging_expr(y.expr)) {
  8105. // Allow
  8106. y.mode = Addressing_Value;
  8107. y_is_diverging = true;
  8108. } else {
  8109. error_operand_no_value(&y);
  8110. y.mode = Addressing_Invalid;
  8111. }
  8112. break;
  8113. case Addressing_Type:
  8114. error_operand_not_expression(&y);
  8115. y.mode = Addressing_Invalid;
  8116. break;
  8117. }
  8118. if (y.mode == Addressing_Invalid) {
  8119. o->mode = Addressing_Value;
  8120. o->type = t_invalid;
  8121. o->expr = node;
  8122. return Expr_Expr;
  8123. }
  8124. if (left_type != nullptr) {
  8125. if (!y_is_diverging) {
  8126. if (is_type_tuple(left_type)) {
  8127. if (!is_type_tuple(y.type)) {
  8128. error(y.expr, "Found a single value where a %td-valued expression was expected", left_type->Tuple.variables.count);
  8129. } else if (!are_types_identical(left_type, y.type)) {
  8130. gbString xt = type_to_string(left_type);
  8131. gbString yt = type_to_string(y.type);
  8132. error(y.expr, "Mismatched types, expected (%s), got (%s)", xt, yt);
  8133. gb_string_free(yt);
  8134. gb_string_free(xt);
  8135. }
  8136. } else {
  8137. check_assignment(c, &y, left_type, name);
  8138. }
  8139. }
  8140. } else {
  8141. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8142. }
  8143. if (left_type == nullptr) {
  8144. left_type = t_invalid;
  8145. }
  8146. o->mode = Addressing_Value;
  8147. o->type = left_type;
  8148. o->expr = node;
  8149. return Expr_Expr;
  8150. }
  8151. gb_internal ExprKind check_or_return_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8152. ast_node(re, OrReturnExpr, node);
  8153. String name = re->token.string;
  8154. Operand x = {};
  8155. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  8156. if (x.mode == Addressing_Invalid) {
  8157. o->mode = Addressing_Value;
  8158. o->type = t_invalid;
  8159. o->expr = node;
  8160. return Expr_Expr;
  8161. }
  8162. Type *left_type = nullptr;
  8163. Type *right_type = nullptr;
  8164. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8165. add_type_and_value(c, re->expr, x.mode, x.type, x.value);
  8166. if (right_type == nullptr) {
  8167. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8168. } else {
  8169. Type *proc_type = base_type(c->curr_proc_sig);
  8170. GB_ASSERT(proc_type->kind == Type_Proc);
  8171. Type *result_type = proc_type->Proc.results;
  8172. if (result_type == nullptr) {
  8173. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  8174. } else {
  8175. GB_ASSERT(result_type->kind == Type_Tuple);
  8176. auto const &vars = result_type->Tuple.variables;
  8177. Type *end_type = vars[vars.count-1]->type;
  8178. if (vars.count > 1) {
  8179. if (!proc_type->Proc.has_named_results) {
  8180. 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));
  8181. }
  8182. }
  8183. Operand rhs = {};
  8184. rhs.type = right_type;
  8185. rhs.mode = Addressing_Value;
  8186. if (is_type_boolean(right_type) && is_type_boolean(end_type)) {
  8187. // NOTE(bill): allow implicit conversion between boolean types
  8188. // within 'or_return' to improve the experience using third-party code
  8189. } else if (!check_is_assignable_to(c, &rhs, end_type)) {
  8190. ERROR_BLOCK();
  8191. // TODO(bill): better error message
  8192. gbString a = type_to_string(right_type);
  8193. gbString b = type_to_string(end_type);
  8194. gbString ret_type = type_to_string(result_type);
  8195. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  8196. if (vars.count == 1) {
  8197. error_line("\tProcedure return value type: %s\n", ret_type);
  8198. } else {
  8199. error_line("\tProcedure return value types: (%s)\n", ret_type);
  8200. }
  8201. gb_string_free(ret_type);
  8202. gb_string_free(b);
  8203. gb_string_free(a);
  8204. }
  8205. }
  8206. }
  8207. o->expr = node;
  8208. o->type = left_type;
  8209. if (left_type != nullptr) {
  8210. o->mode = Addressing_Value;
  8211. } else {
  8212. o->mode = Addressing_NoValue;
  8213. }
  8214. if (c->curr_proc_sig == nullptr) {
  8215. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8216. }
  8217. if (c->in_defer) {
  8218. error(node, "'or_return' cannot be used within a defer statement");
  8219. }
  8220. return Expr_Expr;
  8221. }
  8222. gb_internal ExprKind check_or_branch_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8223. ast_node(be, OrBranchExpr, node);
  8224. String name = be->token.string;
  8225. Operand x = {};
  8226. check_multi_expr_with_type_hint(c, &x, be->expr, type_hint);
  8227. if (x.mode == Addressing_Invalid) {
  8228. o->mode = Addressing_Value;
  8229. o->type = t_invalid;
  8230. o->expr = node;
  8231. return Expr_Expr;
  8232. }
  8233. Type *left_type = nullptr;
  8234. Type *right_type = nullptr;
  8235. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  8236. add_type_and_value(c, be->expr, x.mode, x.type, x.value);
  8237. if (right_type == nullptr) {
  8238. check_or_else_expr_no_value_error(c, name, x, type_hint);
  8239. } else {
  8240. if (is_type_boolean(right_type) || type_has_nil(right_type)) {
  8241. // okay
  8242. } else {
  8243. gbString s = type_to_string(right_type);
  8244. error(node, "'%.*s' requires a boolean or nil-able type, got %s", LIT(name), s);
  8245. gb_string_free(s);
  8246. }
  8247. }
  8248. o->expr = node;
  8249. o->type = left_type;
  8250. if (left_type != nullptr) {
  8251. o->mode = Addressing_Value;
  8252. } else {
  8253. o->mode = Addressing_NoValue;
  8254. }
  8255. if (c->curr_proc_sig == nullptr) {
  8256. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  8257. }
  8258. Ast *label = be->label;
  8259. switch (be->token.kind) {
  8260. case Token_or_break:
  8261. node->viral_state_flags |= ViralStateFlag_ContainsOrBreak;
  8262. if ((c->stmt_flags & Stmt_BreakAllowed) == 0 && label == nullptr) {
  8263. error(be->token, "'%.*s' only allowed in non-inline loops or 'switch' statements", LIT(name));
  8264. }
  8265. break;
  8266. case Token_or_continue:
  8267. if ((c->stmt_flags & Stmt_ContinueAllowed) == 0 && label == nullptr) {
  8268. error(be->token, "'%.*s' only allowed in non-inline loops", LIT(name));
  8269. }
  8270. break;
  8271. }
  8272. if (label != nullptr) {
  8273. if (c->in_defer) {
  8274. error(label, "A labelled '%.*s' cannot be used within a 'defer'", LIT(name));
  8275. return Expr_Expr;
  8276. }
  8277. if (label->kind != Ast_Ident) {
  8278. error(label, "A branch statement's label name must be an identifier");
  8279. return Expr_Expr;
  8280. }
  8281. Ast *ident = label;
  8282. String name = ident->Ident.token.string;
  8283. Operand o = {};
  8284. Entity *e = check_ident(c, &o, ident, nullptr, nullptr, false);
  8285. if (e == nullptr) {
  8286. error(ident, "Undeclared label name: %.*s", LIT(name));
  8287. return Expr_Expr;
  8288. }
  8289. add_entity_use(c, ident, e);
  8290. if (e->kind != Entity_Label) {
  8291. error(ident, "'%.*s' is not a label", LIT(name));
  8292. return Expr_Expr;
  8293. }
  8294. Ast *parent = e->Label.parent;
  8295. GB_ASSERT(parent != nullptr);
  8296. switch (parent->kind) {
  8297. case Ast_BlockStmt:
  8298. case Ast_IfStmt:
  8299. case Ast_SwitchStmt:
  8300. if (be->token.kind != Token_or_break) {
  8301. error(label, "Label '%.*s' can only be used with 'or_break'", LIT(e->token.string));
  8302. }
  8303. break;
  8304. case Ast_RangeStmt:
  8305. case Ast_ForStmt:
  8306. if ((be->token.kind != Token_or_break) && (be->token.kind != Token_or_continue)) {
  8307. error(label, "Label '%.*s' can only be used with 'or_break' and 'or_continue'", LIT(e->token.string));
  8308. }
  8309. break;
  8310. }
  8311. }
  8312. return Expr_Expr;
  8313. }
  8314. gb_internal void check_compound_literal_field_values(CheckerContext *c, Slice<Ast *> const &elems, Operand *o, Type *type, bool &is_constant) {
  8315. Type *bt = base_type(type);
  8316. StringSet fields_visited = {};
  8317. defer (string_set_destroy(&fields_visited));
  8318. StringMap<String> fields_visited_through_raw_union = {};
  8319. defer (string_map_destroy(&fields_visited_through_raw_union));
  8320. String assignment_str = str_lit("structure literal");
  8321. if (bt->kind == Type_BitField) {
  8322. assignment_str = str_lit("bit_field literal");
  8323. }
  8324. for (Ast *elem : elems) {
  8325. if (elem->kind != Ast_FieldValue) {
  8326. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8327. continue;
  8328. }
  8329. ast_node(fv, FieldValue, elem);
  8330. Ast *ident = fv->field;
  8331. if (ident->kind == Ast_ImplicitSelectorExpr) {
  8332. gbString expr_str = expr_to_string(ident);
  8333. error(ident, "Field names do not start with a '.', remove the '.' in structure literal", expr_str);
  8334. gb_string_free(expr_str);
  8335. ident = ident->ImplicitSelectorExpr.selector;
  8336. }
  8337. if (ident->kind != Ast_Ident) {
  8338. gbString expr_str = expr_to_string(ident);
  8339. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  8340. gb_string_free(expr_str);
  8341. continue;
  8342. }
  8343. String name = ident->Ident.token.string;
  8344. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  8345. bool is_unknown = sel.entity == nullptr;
  8346. if (is_unknown) {
  8347. error(ident, "Unknown field '%.*s' in structure literal", LIT(name));
  8348. continue;
  8349. }
  8350. Entity *field = nullptr;
  8351. if (bt->kind == Type_Struct) {
  8352. field = bt->Struct.fields[sel.index[0]];
  8353. } else if (bt->kind == Type_BitField) {
  8354. field = bt->BitField.fields[sel.index[0]];
  8355. } else {
  8356. GB_PANIC("Unknown type");
  8357. }
  8358. add_entity_use(c, ident, field);
  8359. if (string_set_update(&fields_visited, name)) {
  8360. if (sel.index.count > 1) {
  8361. if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8362. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8363. } else {
  8364. error(ident, "Duplicate or reused field '%.*s' in %.*s", LIT(sel.entity->token.string), LIT(assignment_str));
  8365. }
  8366. } else {
  8367. error(ident, "Duplicate field '%.*s' in %.*s", LIT(field->token.string), LIT(assignment_str));
  8368. }
  8369. continue;
  8370. } else if (String *found = string_map_get(&fields_visited_through_raw_union, sel.entity->token.string)) {
  8371. error(ident, "Field '%.*s' is already initialized due to a previously assigned struct #raw_union field '%.*s'", LIT(sel.entity->token.string), LIT(*found));
  8372. continue;
  8373. }
  8374. if (sel.indirect) {
  8375. 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));
  8376. continue;
  8377. }
  8378. if (sel.index.count > 1) {
  8379. GB_ASSERT(bt->kind == Type_Struct);
  8380. if (is_constant) {
  8381. Type *ft = type;
  8382. for (i32 index : sel.index) {
  8383. Type *bt = base_type(ft);
  8384. switch (bt->kind) {
  8385. case Type_Struct:
  8386. if (bt->Struct.is_raw_union) {
  8387. is_constant = false;
  8388. break;
  8389. }
  8390. ft = bt->Struct.fields[index]->type;
  8391. break;
  8392. case Type_Array:
  8393. ft = bt->Array.elem;
  8394. break;
  8395. case Type_BitField:
  8396. is_constant = false;
  8397. ft = bt->BitField.fields[index]->type;
  8398. break;
  8399. default:
  8400. GB_PANIC("invalid type: %s", type_to_string(ft));
  8401. break;
  8402. }
  8403. }
  8404. if (is_constant &&
  8405. (is_type_any(ft) || is_type_union(ft) || is_type_raw_union(ft) || is_type_typeid(ft))) {
  8406. is_constant = false;
  8407. }
  8408. }
  8409. Type *nested_ft = bt;
  8410. for (i32 index : sel.index) {
  8411. Type *bt = base_type(nested_ft);
  8412. switch (bt->kind) {
  8413. case Type_Struct:
  8414. if (bt->Struct.is_raw_union) {
  8415. for (Entity *re : bt->Struct.fields) {
  8416. string_map_set(&fields_visited_through_raw_union, re->token.string, sel.entity->token.string);
  8417. }
  8418. }
  8419. nested_ft = bt->Struct.fields[index]->type;
  8420. break;
  8421. case Type_Array:
  8422. nested_ft = bt->Array.elem;
  8423. break;
  8424. case Type_BitField:
  8425. nested_ft = bt->BitField.fields[index]->type;
  8426. break;
  8427. default:
  8428. GB_PANIC("invalid type %s", type_to_string(nested_ft));
  8429. break;
  8430. }
  8431. }
  8432. field = sel.entity;
  8433. }
  8434. Operand o = {};
  8435. check_expr_or_type(c, &o, fv->value, field->type);
  8436. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8437. is_constant = false;
  8438. }
  8439. if (is_constant) {
  8440. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8441. }
  8442. u8 prev_bit_field_bit_size = c->bit_field_bit_size;
  8443. if (field->kind == Entity_Variable && field->Variable.bit_field_bit_size) {
  8444. // HACK NOTE(bill): This is a bit of a hack, but it will work fine for this use case
  8445. c->bit_field_bit_size = field->Variable.bit_field_bit_size;
  8446. }
  8447. check_assignment(c, &o, field->type, assignment_str);
  8448. c->bit_field_bit_size = prev_bit_field_bit_size;
  8449. }
  8450. }
  8451. gb_internal bool is_expr_inferred_fixed_array(Ast *type_expr) {
  8452. type_expr = unparen_expr(type_expr);
  8453. if (type_expr == nullptr) {
  8454. return false;
  8455. }
  8456. // [?]Type
  8457. if (type_expr->kind == Ast_ArrayType && type_expr->ArrayType.count != nullptr) {
  8458. Ast *count = type_expr->ArrayType.count;
  8459. if (count->kind == Ast_UnaryExpr &&
  8460. count->UnaryExpr.op.kind == Token_Question) {
  8461. return true;
  8462. }
  8463. }
  8464. return false;
  8465. }
  8466. gb_internal bool check_for_dynamic_literals(CheckerContext *c, Ast *node, AstCompoundLit *cl) {
  8467. if (cl->elems.count > 0 && (check_feature_flags(c, node) & OptInFeatureFlag_DynamicLiterals) == 0 && !build_context.dynamic_literals) {
  8468. ERROR_BLOCK();
  8469. error(node, "Compound literals of dynamic types are disabled by default");
  8470. error_line("\tSuggestion: If you want to enable them for this specific file, add '#+feature dynamic-literals' at the top of the file\n");
  8471. error_line("\tWarning: Please understand that dynamic literals will implicitly allocate using the current 'context.allocator' in that scope\n");
  8472. if (build_context.ODIN_DEFAULT_TO_NIL_ALLOCATOR) {
  8473. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8474. } else if (build_context.ODIN_DEFAULT_TO_PANIC_ALLOCATOR) {
  8475. error_line("\tWarning: As '-default-to-panic-allocator' has been set, the dynamic compound literal may not be initialized as expected\n");
  8476. }
  8477. return false;
  8478. }
  8479. return cl->elems.count > 0;
  8480. }
  8481. gb_internal IntegerDivisionByZeroKind check_for_integer_division_by_zero(CheckerContext *c, Ast *node) {
  8482. // TODO(bill): per file `#+feature` flags
  8483. u64 flags = check_feature_flags(c, node);
  8484. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Trap) != 0) {
  8485. return IntegerDivisionByZero_Trap;
  8486. }
  8487. if ((flags & OptInFeatureFlag_IntegerDivisionByZero_Zero) != 0) {
  8488. return IntegerDivisionByZero_Zero;
  8489. }
  8490. return build_context.integer_division_by_zero_behaviour;
  8491. }
  8492. gb_internal ExprKind check_compound_literal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  8493. ExprKind kind = Expr_Expr;
  8494. ast_node(cl, CompoundLit, node);
  8495. Type *type = type_hint;
  8496. if (type != nullptr && is_type_untyped(type)) {
  8497. type = nullptr;
  8498. }
  8499. bool is_to_be_determined_array_count = false;
  8500. bool is_constant = true;
  8501. bool is_soa = false;
  8502. Ast *type_expr = cl->type;
  8503. bool used_type_hint_expr = false;
  8504. if (type_expr == nullptr && c->type_hint_expr != nullptr) {
  8505. if (is_expr_inferred_fixed_array(c->type_hint_expr)) {
  8506. type_expr = clone_ast(c->type_hint_expr);
  8507. used_type_hint_expr = true;
  8508. }
  8509. }
  8510. if (type_expr != nullptr) {
  8511. type = nullptr;
  8512. // [?]Type
  8513. if (type_expr->kind == Ast_ArrayType) {
  8514. Ast *count = type_expr->ArrayType.count;
  8515. if (count != nullptr) {
  8516. if (count->kind == Ast_UnaryExpr &&
  8517. count->UnaryExpr.op.kind == Token_Question) {
  8518. type = alloc_type_array(check_type(c, type_expr->ArrayType.elem), -1);
  8519. is_to_be_determined_array_count = true;
  8520. }
  8521. } else {
  8522. type = alloc_type_slice(check_type(c, type_expr->ArrayType.elem));
  8523. }
  8524. if (cl->elems.count > 0) {
  8525. if (type_expr->ArrayType.tag != nullptr) {
  8526. Ast *tag = type_expr->ArrayType.tag;
  8527. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8528. String name = tag->BasicDirective.name.string;
  8529. if (name == "soa") {
  8530. is_soa = true;
  8531. if (count == nullptr) {
  8532. error(node, "#soa slices are not supported for compound literals");
  8533. return kind;
  8534. } else if (count->kind == Ast_UnaryExpr &&
  8535. count->UnaryExpr.op.kind == Token_Question) {
  8536. error(node, "#soa fixed length arrays must specify their length and cannot use ?");
  8537. }
  8538. }
  8539. }
  8540. }
  8541. } else if (type_expr->kind == Ast_DynamicArrayType && type_expr->DynamicArrayType.tag != nullptr) {
  8542. if (cl->elems.count > 0) {
  8543. Ast *tag = type_expr->DynamicArrayType.tag;
  8544. GB_ASSERT(tag->kind == Ast_BasicDirective);
  8545. String name = tag->BasicDirective.name.string;
  8546. if (name == "soa") {
  8547. is_soa = true;
  8548. error(node, "#soa dynamic arrays are not supported for compound literals");
  8549. return kind;
  8550. }
  8551. }
  8552. }
  8553. if (type == nullptr) {
  8554. type = check_type(c, type_expr);
  8555. }
  8556. }
  8557. if (type == nullptr) {
  8558. error(node, "Missing type in compound literal");
  8559. return kind;
  8560. }
  8561. Type *t = base_type(type);
  8562. if (is_type_polymorphic(t)) {
  8563. gbString str = type_to_string(type);
  8564. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  8565. o->expr = node;
  8566. o->type = type;
  8567. gb_string_free(str);
  8568. return kind;
  8569. }
  8570. switch (t->kind) {
  8571. case Type_Struct:
  8572. if (cl->elems.count == 0) {
  8573. break; // NOTE(bill): No need to init
  8574. }
  8575. if (t->Struct.soa_kind == StructSoa_None) {
  8576. if (t->Struct.is_raw_union) {
  8577. if (cl->elems.count > 0) {
  8578. // NOTE: unions cannot be constant
  8579. is_constant = false;
  8580. if (cl->elems[0]->kind != Ast_FieldValue) {
  8581. gbString type_str = type_to_string(type);
  8582. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  8583. gb_string_free(type_str);
  8584. } else {
  8585. if (cl->elems.count != 1) {
  8586. gbString type_str = type_to_string(type);
  8587. 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);
  8588. gb_string_free(type_str);
  8589. } else {
  8590. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8591. }
  8592. }
  8593. }
  8594. break;
  8595. }
  8596. wait_signal_until_available(&t->Struct.fields_wait_signal);
  8597. isize field_count = t->Struct.fields.count;
  8598. isize min_field_count = t->Struct.fields.count;
  8599. for (isize i = min_field_count-1; i >= 0; i--) {
  8600. Entity *e = t->Struct.fields[i];
  8601. GB_ASSERT(e->kind == Entity_Variable);
  8602. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  8603. min_field_count--;
  8604. } else {
  8605. break;
  8606. }
  8607. }
  8608. if (cl->elems[0]->kind == Ast_FieldValue) {
  8609. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  8610. } else {
  8611. bool seen_field_value = false;
  8612. for_array(index, cl->elems) {
  8613. Entity *field = nullptr;
  8614. Ast *elem = cl->elems[index];
  8615. if (elem->kind == Ast_FieldValue) {
  8616. seen_field_value = true;
  8617. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8618. continue;
  8619. } else if (seen_field_value) {
  8620. error(elem, "Value elements cannot be used after a 'field = value'");
  8621. continue;
  8622. }
  8623. if (index >= field_count) {
  8624. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8625. break;
  8626. }
  8627. if (field == nullptr) {
  8628. field = t->Struct.fields[index];
  8629. }
  8630. Operand o = {};
  8631. check_expr_or_type(c, &o, elem, field->type);
  8632. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  8633. is_constant = false;
  8634. }
  8635. if (is_constant) {
  8636. is_constant = check_is_operand_compound_lit_constant(c, &o);
  8637. }
  8638. check_assignment(c, &o, field->type, str_lit("structure literal"));
  8639. }
  8640. if (cl->elems.count < field_count) {
  8641. if (min_field_count < field_count) {
  8642. if (cl->elems.count < min_field_count) {
  8643. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  8644. }
  8645. } else {
  8646. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  8647. }
  8648. }
  8649. }
  8650. break;
  8651. } else if (t->Struct.soa_kind != StructSoa_Fixed) {
  8652. error(node, "#soa slices and dynamic arrays are not supported for compound literals");
  8653. break;
  8654. }
  8655. /*fallthrough*/
  8656. case Type_Slice:
  8657. case Type_Array:
  8658. case Type_DynamicArray:
  8659. case Type_SimdVector:
  8660. case Type_Matrix:
  8661. {
  8662. Type *elem_type = nullptr;
  8663. String context_name = {};
  8664. i64 max_type_count = -1;
  8665. if (t->kind == Type_Struct) {
  8666. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8667. elem_type = t->Struct.soa_elem;
  8668. context_name = str_lit("#soa array literal");
  8669. if (!is_to_be_determined_array_count) {
  8670. max_type_count = t->Struct.soa_count;
  8671. }
  8672. } else if (t->kind == Type_Slice) {
  8673. elem_type = t->Slice.elem;
  8674. context_name = str_lit("slice literal");
  8675. } else if (t->kind == Type_Array) {
  8676. elem_type = t->Array.elem;
  8677. context_name = str_lit("array literal");
  8678. if (!is_to_be_determined_array_count) {
  8679. max_type_count = t->Array.count;
  8680. }
  8681. } else if (t->kind == Type_Array) {
  8682. elem_type = t->Array.elem;
  8683. context_name = str_lit("array literal");
  8684. if (!is_to_be_determined_array_count) {
  8685. max_type_count = t->Array.count;
  8686. }
  8687. } else if (t->kind == Type_DynamicArray) {
  8688. elem_type = t->DynamicArray.elem;
  8689. context_name = str_lit("dynamic array literal");
  8690. is_constant = false;
  8691. } else if (t->kind == Type_SimdVector) {
  8692. elem_type = t->SimdVector.elem;
  8693. context_name = str_lit("simd vector literal");
  8694. max_type_count = t->SimdVector.count;
  8695. } else if (t->kind == Type_Matrix) {
  8696. elem_type = t->Matrix.elem;
  8697. context_name = str_lit("matrix literal");
  8698. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  8699. } else {
  8700. GB_PANIC("unreachable");
  8701. }
  8702. i64 max = 0;
  8703. Type *bet = base_type(elem_type);
  8704. if (!elem_type_can_be_constant(bet)) {
  8705. is_constant = false;
  8706. }
  8707. if (bet == t_invalid) {
  8708. break;
  8709. }
  8710. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8711. RangeCache rc = range_cache_make(heap_allocator());
  8712. defer (range_cache_destroy(&rc));
  8713. for (Ast *elem : cl->elems) {
  8714. if (elem->kind != Ast_FieldValue) {
  8715. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8716. continue;
  8717. }
  8718. ast_node(fv, FieldValue, elem);
  8719. if (is_ast_range(fv->field)) {
  8720. Token op = fv->field->BinaryExpr.op;
  8721. Operand x = {};
  8722. Operand y = {};
  8723. bool ok = check_range(c, fv->field, false, &x, &y, nullptr);
  8724. if (!ok) {
  8725. continue;
  8726. }
  8727. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  8728. error(x.expr, "Expected a constant integer as an array field");
  8729. continue;
  8730. }
  8731. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  8732. error(y.expr, "Expected a constant integer as an array field");
  8733. continue;
  8734. }
  8735. i64 lo = exact_value_to_i64(x.value);
  8736. i64 hi = exact_value_to_i64(y.value);
  8737. i64 max_index = hi;
  8738. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  8739. hi -= 1;
  8740. } else { // .. (inclusive)
  8741. max_index += 1;
  8742. }
  8743. bool new_range = range_cache_add_range(&rc, lo, hi);
  8744. if (!new_range) {
  8745. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  8746. continue;
  8747. }
  8748. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  8749. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  8750. continue;
  8751. }
  8752. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  8753. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  8754. continue;
  8755. }
  8756. if (max < hi) {
  8757. max = max_index;
  8758. }
  8759. Operand operand = {};
  8760. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8761. check_assignment(c, &operand, elem_type, context_name);
  8762. is_constant = is_constant && operand.mode == Addressing_Constant;
  8763. } else {
  8764. Operand op_index = {};
  8765. check_expr(c, &op_index, fv->field);
  8766. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  8767. error(elem, "Expected a constant integer as an array field");
  8768. continue;
  8769. }
  8770. // add_type_and_value(c, op_index.expr, op_index.mode, op_index.type, op_index.value);
  8771. i64 index = exact_value_to_i64(op_index.value);
  8772. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  8773. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  8774. continue;
  8775. }
  8776. bool new_index = range_cache_add_index(&rc, index);
  8777. if (!new_index) {
  8778. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  8779. continue;
  8780. }
  8781. if (max < index+1) {
  8782. max = index+1;
  8783. }
  8784. Operand operand = {};
  8785. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8786. check_assignment(c, &operand, elem_type, context_name);
  8787. is_constant = is_constant && operand.mode == Addressing_Constant;
  8788. }
  8789. }
  8790. cl->max_count = max;
  8791. } else {
  8792. isize index = 0;
  8793. for (; index < cl->elems.count; index++) {
  8794. Ast *e = cl->elems[index];
  8795. if (e == nullptr) {
  8796. error(node, "Invalid literal element");
  8797. continue;
  8798. }
  8799. if (e->kind == Ast_FieldValue) {
  8800. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8801. continue;
  8802. }
  8803. if (0 <= max_type_count && max_type_count <= index) {
  8804. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  8805. }
  8806. Operand operand = {};
  8807. check_expr_with_type_hint(c, &operand, e, elem_type);
  8808. check_assignment(c, &operand, elem_type, context_name);
  8809. is_constant = is_constant && operand.mode == Addressing_Constant;
  8810. }
  8811. if (max < index) {
  8812. max = index;
  8813. }
  8814. }
  8815. if (t->kind == Type_Array) {
  8816. if (is_to_be_determined_array_count) {
  8817. t->Array.count = max;
  8818. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8819. if (0 < max && max < t->Array.count) {
  8820. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  8821. }
  8822. }
  8823. } else if (t->kind == Type_Struct) {
  8824. GB_ASSERT(t->Struct.soa_kind == StructSoa_Fixed);
  8825. if (is_to_be_determined_array_count) {
  8826. t->Struct.soa_count = cast(i32)max;
  8827. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8828. if (0 < max && max < t->Struct.soa_count) {
  8829. error(node, "Expected %lld values for this #soa array literal, got %lld", cast(long long)t->Struct.soa_count, cast(long long)max);
  8830. }
  8831. }
  8832. }
  8833. if (t->kind == Type_SimdVector) {
  8834. if (!is_constant) {
  8835. // error(node, "Expected all constant elements for a simd vector");
  8836. }
  8837. }
  8838. if (t->kind == Type_DynamicArray) {
  8839. if (check_for_dynamic_literals(c, node, cl)) {
  8840. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  8841. add_package_dependency(c, "runtime", "__dynamic_array_append");
  8842. }
  8843. }
  8844. if (t->kind == Type_Matrix) {
  8845. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  8846. if (0 < max && max < max_type_count) {
  8847. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  8848. }
  8849. }
  8850. }
  8851. break;
  8852. }
  8853. case Type_EnumeratedArray:
  8854. {
  8855. Type *elem_type = t->EnumeratedArray.elem;
  8856. Type *index_type = t->EnumeratedArray.index;
  8857. String context_name = str_lit("enumerated array literal");
  8858. i64 max_type_count = t->EnumeratedArray.count;
  8859. gbString index_type_str = type_to_string(index_type);
  8860. defer (gb_string_free(index_type_str));
  8861. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  8862. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  8863. String total_lo_string = {};
  8864. String total_hi_string = {};
  8865. GB_ASSERT(is_type_enum(index_type));
  8866. {
  8867. Type *bt = base_type(index_type);
  8868. GB_ASSERT(bt->kind == Type_Enum);
  8869. for (Entity *f : bt->Enum.fields) {
  8870. if (f->kind != Entity_Constant) {
  8871. continue;
  8872. }
  8873. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  8874. total_lo_string = f->token.string;
  8875. }
  8876. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  8877. total_hi_string = f->token.string;
  8878. }
  8879. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  8880. break;
  8881. }
  8882. }
  8883. }
  8884. i64 max = 0;
  8885. Type *bet = base_type(elem_type);
  8886. if (!elem_type_can_be_constant(bet)) {
  8887. is_constant = false;
  8888. }
  8889. if (bet == t_invalid) {
  8890. break;
  8891. }
  8892. bool is_partial = cl->tag && (cl->tag->BasicDirective.name.string == "partial");
  8893. SeenMap seen = {}; // NOTE(bill): Multimap, Key: ExactValue
  8894. defer (map_destroy(&seen));
  8895. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  8896. RangeCache rc = range_cache_make(heap_allocator());
  8897. defer (range_cache_destroy(&rc));
  8898. for (Ast *elem : cl->elems) {
  8899. if (elem->kind != Ast_FieldValue) {
  8900. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  8901. continue;
  8902. }
  8903. ast_node(fv, FieldValue, elem);
  8904. if (is_ast_range(fv->field)) {
  8905. Token op = fv->field->BinaryExpr.op;
  8906. Operand x = {};
  8907. Operand y = {};
  8908. bool ok = check_range(c, fv->field, false, &x, &y, nullptr, index_type);
  8909. if (!ok) {
  8910. continue;
  8911. }
  8912. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8913. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8914. continue;
  8915. }
  8916. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  8917. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8918. continue;
  8919. }
  8920. i64 lo = exact_value_to_i64(x.value);
  8921. i64 hi = exact_value_to_i64(y.value);
  8922. i64 max_index = hi;
  8923. if (op.kind == Token_RangeHalf) {
  8924. hi -= 1;
  8925. }
  8926. bool new_range = range_cache_add_range(&rc, lo, hi);
  8927. if (!new_range) {
  8928. gbString lo_str = expr_to_string(x.expr);
  8929. gbString hi_str = expr_to_string(y.expr);
  8930. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  8931. gb_string_free(hi_str);
  8932. gb_string_free(lo_str);
  8933. continue;
  8934. }
  8935. // NOTE(bill): These are sanity checks for invalid enum values
  8936. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  8937. gbString lo_str = expr_to_string(x.expr);
  8938. 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));
  8939. gb_string_free(lo_str);
  8940. continue;
  8941. }
  8942. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  8943. gbString hi_str = expr_to_string(y.expr);
  8944. 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));
  8945. gb_string_free(hi_str);
  8946. continue;
  8947. }
  8948. if (max < hi) {
  8949. max = max_index;
  8950. }
  8951. Operand operand = {};
  8952. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8953. check_assignment(c, &operand, elem_type, context_name);
  8954. is_constant = is_constant && operand.mode == Addressing_Constant;
  8955. TokenKind upper_op = Token_LtEq;
  8956. if (op.kind == Token_RangeHalf) {
  8957. upper_op = Token_Lt;
  8958. }
  8959. add_to_seen_map(c, &seen, upper_op, x, x, y);
  8960. } else {
  8961. Operand op_index = {};
  8962. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  8963. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  8964. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  8965. continue;
  8966. }
  8967. i64 index = exact_value_to_i64(op_index.value);
  8968. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  8969. gbString idx_str = expr_to_string(op_index.expr);
  8970. 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));
  8971. gb_string_free(idx_str);
  8972. continue;
  8973. }
  8974. bool new_index = range_cache_add_index(&rc, index);
  8975. if (!new_index) {
  8976. gbString idx_str = expr_to_string(op_index.expr);
  8977. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  8978. gb_string_free(idx_str);
  8979. continue;
  8980. }
  8981. if (max < index+1) {
  8982. max = index+1;
  8983. }
  8984. Operand operand = {};
  8985. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  8986. check_assignment(c, &operand, elem_type, context_name);
  8987. is_constant = is_constant && operand.mode == Addressing_Constant;
  8988. add_to_seen_map(c, &seen, op_index);
  8989. }
  8990. }
  8991. cl->max_count = max;
  8992. } else {
  8993. isize index = 0;
  8994. for (; index < cl->elems.count; index++) {
  8995. Ast *e = cl->elems[index];
  8996. if (e == nullptr) {
  8997. error(node, "Invalid literal element");
  8998. continue;
  8999. }
  9000. if (e->kind == Ast_FieldValue) {
  9001. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  9002. continue;
  9003. }
  9004. if (0 <= max_type_count && max_type_count <= index) {
  9005. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  9006. }
  9007. Operand operand = {};
  9008. check_expr_with_type_hint(c, &operand, e, elem_type);
  9009. check_assignment(c, &operand, elem_type, context_name);
  9010. is_constant = is_constant && operand.mode == Addressing_Constant;
  9011. }
  9012. if (max < index) {
  9013. max = index;
  9014. }
  9015. }
  9016. bool was_error = false;
  9017. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  9018. if (0 < max && max < t->EnumeratedArray.count) {
  9019. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  9020. was_error = true;
  9021. } else {
  9022. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  9023. was_error = true;
  9024. }
  9025. }
  9026. // NOTE(bill): Check for missing cases when `#partial literal` is not present
  9027. if (cl->elems.count > 0 && !was_error && !is_partial) {
  9028. TEMPORARY_ALLOCATOR_GUARD();
  9029. Type *et = base_type(index_type);
  9030. GB_ASSERT(et->kind == Type_Enum);
  9031. auto fields = et->Enum.fields;
  9032. auto unhandled = array_make<Entity *>(temporary_allocator(), 0, fields.count);
  9033. for (Entity *f : fields) {
  9034. if (f->kind != Entity_Constant) {
  9035. continue;
  9036. }
  9037. ExactValue v = f->Constant.value;
  9038. uintptr hash = hash_exact_value(v);
  9039. auto found = map_get(&seen, hash);
  9040. if (!found) {
  9041. array_add(&unhandled, f);
  9042. }
  9043. }
  9044. if (unhandled.count > 0) {
  9045. ERROR_BLOCK();
  9046. if (unhandled.count == 1) {
  9047. error_no_newline(node, "Unhandled enumerated array case: %.*s", LIT(unhandled[0]->token.string));
  9048. } else {
  9049. error(node, "Unhandled enumerated array cases:");
  9050. for_array(i, unhandled) {
  9051. Entity *f = unhandled[i];
  9052. error_line("\t%.*s\n", LIT(f->token.string));
  9053. }
  9054. }
  9055. if (!build_context.terse_errors) {
  9056. error_line("\n");
  9057. error_line("\tSuggestion: Was '#partial %s{...}' wanted?\n", type_to_string(type));
  9058. }
  9059. }
  9060. }
  9061. break;
  9062. }
  9063. case Type_Basic: {
  9064. if (!is_type_any(t)) {
  9065. if (cl->elems.count != 0) {
  9066. gbString s = type_to_string(t);
  9067. error(node, "Illegal compound literal, %s cannot be used as a compound literal with fields", s);
  9068. gb_string_free(s);
  9069. is_constant = false;
  9070. }
  9071. break;
  9072. }
  9073. if (cl->elems.count == 0) {
  9074. break; // NOTE(bill): No need to init
  9075. }
  9076. { // Checker values
  9077. Type *field_types[2] = {t_rawptr, t_typeid};
  9078. isize field_count = 2;
  9079. if (cl->elems[0]->kind == Ast_FieldValue) {
  9080. bool fields_visited[2] = {};
  9081. for_array(i, cl->elems) {
  9082. Ast *elem = cl->elems[i];
  9083. if (elem->kind != Ast_FieldValue) {
  9084. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9085. continue;
  9086. }
  9087. ast_node(fv, FieldValue, elem);
  9088. if (fv->field->kind != Ast_Ident) {
  9089. gbString expr_str = expr_to_string(fv->field);
  9090. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  9091. gb_string_free(expr_str);
  9092. continue;
  9093. }
  9094. String name = fv->field->Ident.token.string;
  9095. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  9096. if (sel.entity == nullptr) {
  9097. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  9098. continue;
  9099. }
  9100. isize index = sel.index[0];
  9101. if (fields_visited[index]) {
  9102. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  9103. continue;
  9104. }
  9105. fields_visited[index] = true;
  9106. check_expr(c, o, fv->value);
  9107. // NOTE(bill): 'any' literals can never be constant
  9108. is_constant = false;
  9109. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9110. }
  9111. } else {
  9112. for_array(index, cl->elems) {
  9113. Ast *elem = cl->elems[index];
  9114. if (elem->kind == Ast_FieldValue) {
  9115. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  9116. continue;
  9117. }
  9118. check_expr(c, o, elem);
  9119. if (index >= field_count) {
  9120. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  9121. break;
  9122. }
  9123. // NOTE(bill): 'any' literals can never be constant
  9124. is_constant = false;
  9125. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  9126. }
  9127. if (cl->elems.count < field_count) {
  9128. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  9129. }
  9130. }
  9131. }
  9132. break;
  9133. }
  9134. case Type_Map: {
  9135. if (cl->elems.count == 0) {
  9136. break;
  9137. }
  9138. is_constant = false;
  9139. { // Checker values
  9140. bool key_is_typeid = is_type_typeid(t->Map.key);
  9141. bool value_is_typeid = is_type_typeid(t->Map.value);
  9142. for (Ast *elem : cl->elems) {
  9143. if (elem->kind != Ast_FieldValue) {
  9144. error(elem, "Only 'field = value' elements are allowed in a map literal");
  9145. continue;
  9146. }
  9147. ast_node(fv, FieldValue, elem);
  9148. if (key_is_typeid) {
  9149. check_expr_or_type(c, o, fv->field, t->Map.key);
  9150. } else {
  9151. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  9152. }
  9153. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  9154. if (o->mode == Addressing_Invalid) {
  9155. continue;
  9156. }
  9157. if (value_is_typeid) {
  9158. check_expr_or_type(c, o, fv->value, t->Map.value);
  9159. } else {
  9160. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  9161. }
  9162. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  9163. }
  9164. }
  9165. if (check_for_dynamic_literals(c, node, cl)) {
  9166. add_map_reserve_dependencies(c);
  9167. add_map_set_dependencies(c);
  9168. }
  9169. break;
  9170. }
  9171. case Type_BitSet: {
  9172. if (cl->elems.count == 0) {
  9173. break; // NOTE(bill): No need to init
  9174. }
  9175. Type *et = base_type(t->BitSet.elem);
  9176. isize field_count = 0;
  9177. if (et != nullptr && et->kind == Type_Enum) {
  9178. field_count = et->Enum.fields.count;
  9179. }
  9180. if (is_type_array(bit_set_to_int(t))) {
  9181. is_constant = false;
  9182. }
  9183. for (Ast *elem : cl->elems) {
  9184. if (elem->kind == Ast_FieldValue) {
  9185. error(elem, "'field = value' in a bit_set literal is not allowed");
  9186. is_constant = false;
  9187. continue;
  9188. }
  9189. check_expr_with_type_hint(c, o, elem, et);
  9190. if (is_constant) {
  9191. is_constant = o->mode == Addressing_Constant;
  9192. }
  9193. if (elem->kind == Ast_BinaryExpr) {
  9194. switch (elem->BinaryExpr.op.kind) {
  9195. case Token_Or:
  9196. {
  9197. gbString x = expr_to_string(elem->BinaryExpr.left);
  9198. gbString y = expr_to_string(elem->BinaryExpr.right);
  9199. gbString e = expr_to_string(elem);
  9200. error(elem, "Was the following intended? '%s, %s'; if not, surround the expression with parentheses '(%s)'", x, y, e);
  9201. gb_string_free(e);
  9202. gb_string_free(y);
  9203. gb_string_free(x);
  9204. }
  9205. break;
  9206. }
  9207. }
  9208. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  9209. if (o->mode == Addressing_Constant) {
  9210. i64 lower = t->BitSet.lower;
  9211. i64 upper = t->BitSet.upper;
  9212. i64 v = exact_value_to_i64(o->value);
  9213. if (lower <= v && v <= upper) {
  9214. // okay
  9215. } else {
  9216. gbString s = expr_to_string(o->expr);
  9217. error(elem, "Bit field value out of bounds, %s (%lld) not in the range %lld .. %lld", s, v, lower, upper);
  9218. gb_string_free(s);
  9219. continue;
  9220. }
  9221. }
  9222. }
  9223. break;
  9224. }
  9225. case Type_BitField: {
  9226. if (cl->elems.count == 0) {
  9227. break; // NOTE(bill): No need to init
  9228. }
  9229. is_constant = false;
  9230. if (cl->elems[0]->kind != Ast_FieldValue) {
  9231. gbString type_str = type_to_string(type);
  9232. error(node, "%s ('bit_field') compound literals are only allowed to contain 'field = value' elements", type_str);
  9233. gb_string_free(type_str);
  9234. } else {
  9235. check_compound_literal_field_values(c, cl->elems, o, type, is_constant);
  9236. }
  9237. break;
  9238. }
  9239. default: {
  9240. if (cl->elems.count == 0) {
  9241. break; // NOTE(bill): No need to init
  9242. }
  9243. gbString str = type_to_string(type);
  9244. error(node, "Invalid compound literal type '%s'", str);
  9245. gb_string_free(str);
  9246. return kind;
  9247. }
  9248. }
  9249. if (is_constant) {
  9250. o->mode = Addressing_Constant;
  9251. if (is_type_bit_set(type)) {
  9252. // NOTE(bill): Encode as an integer
  9253. Type *bt = base_type(type);
  9254. BigInt bits = {};
  9255. BigInt one = {};
  9256. big_int_from_u64(&one, 1);
  9257. for (Ast *e : cl->elems) {
  9258. GB_ASSERT(e->kind != Ast_FieldValue);
  9259. TypeAndValue tav = e->tav;
  9260. if (tav.mode != Addressing_Constant) {
  9261. continue;
  9262. }
  9263. if (tav.value.kind != ExactValue_Integer) {
  9264. continue;
  9265. }
  9266. i64 v = big_int_to_i64(&tav.value.value_integer);
  9267. i64 lower = bt->BitSet.lower;
  9268. u64 index = cast(u64)(v-lower);
  9269. BigInt bit = {};
  9270. big_int_from_u64(&bit, index);
  9271. big_int_shl(&bit, &one, &bit);
  9272. big_int_or(&bits, &bits, &bit);
  9273. }
  9274. o->value.kind = ExactValue_Integer;
  9275. o->value.value_integer = bits;
  9276. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  9277. ExactValue value = exact_value_compound(node);
  9278. Type *bt = core_type(type);
  9279. if (bt->kind == Type_Basic) {
  9280. if (bt->Basic.flags & BasicFlag_Boolean) {
  9281. value = exact_value_bool(false);
  9282. } else if (bt->Basic.flags & BasicFlag_Integer) {
  9283. value = exact_value_i64(0);
  9284. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  9285. value = exact_value_i64(0);
  9286. } else if (bt->Basic.flags & BasicFlag_Float) {
  9287. value = exact_value_float(0);
  9288. } else if (bt->Basic.flags & BasicFlag_Complex) {
  9289. value = exact_value_complex(0, 0);
  9290. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  9291. value = exact_value_quaternion(0, 0, 0, 0);
  9292. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  9293. value = exact_value_pointer(0);
  9294. } else if (bt->Basic.flags & BasicFlag_String) {
  9295. String empty_string = {};
  9296. value = exact_value_string(empty_string);
  9297. } else if (bt->Basic.flags & BasicFlag_Rune) {
  9298. value = exact_value_i64(0);
  9299. }
  9300. }
  9301. o->value = value;
  9302. } else {
  9303. o->value = exact_value_compound(node);
  9304. }
  9305. } else {
  9306. o->mode = Addressing_Value;
  9307. }
  9308. o->type = type;
  9309. return kind;
  9310. }
  9311. gb_internal ExprKind check_type_assertion(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9312. ExprKind kind = Expr_Expr;
  9313. ast_node(ta, TypeAssertion, node);
  9314. check_expr(c, o, ta->expr);
  9315. node->viral_state_flags |= ta->expr->viral_state_flags;
  9316. if (o->mode == Addressing_Invalid) {
  9317. o->expr = node;
  9318. return kind;
  9319. }
  9320. if (o->mode == Addressing_Constant) {
  9321. gbString expr_str = expr_to_string(o->expr);
  9322. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  9323. gb_string_free(expr_str);
  9324. o->mode = Addressing_Invalid;
  9325. o->expr = node;
  9326. return kind;
  9327. }
  9328. if (is_type_untyped(o->type)) {
  9329. gbString expr_str = expr_to_string(o->expr);
  9330. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  9331. gb_string_free(expr_str);
  9332. o->mode = Addressing_Invalid;
  9333. o->expr = node;
  9334. return kind;
  9335. }
  9336. Type *src = type_deref(o->type);
  9337. Type *bsrc = base_type(src);
  9338. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  9339. if (!is_type_union(src)) {
  9340. gbString str = type_to_string(o->type);
  9341. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  9342. gb_string_free(str);
  9343. o->mode = Addressing_Invalid;
  9344. o->expr = node;
  9345. return kind;
  9346. }
  9347. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  9348. bool allowed = false;
  9349. for (Type *vt : bsrc->Union.variants) {
  9350. if (are_types_identical(vt, type_hint)) {
  9351. allowed = true;
  9352. add_type_info_type(c, vt);
  9353. break;
  9354. }
  9355. }
  9356. if (allowed) {
  9357. add_type_info_type(c, o->type);
  9358. o->type = type_hint;
  9359. o->mode = Addressing_OptionalOk;
  9360. goto end;
  9361. }
  9362. }
  9363. if (bsrc->Union.variants.count != 1) {
  9364. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  9365. o->mode = Addressing_Invalid;
  9366. o->expr = node;
  9367. return kind;
  9368. }
  9369. add_type_info_type(c, o->type);
  9370. add_type_info_type(c, bsrc->Union.variants[0]);
  9371. o->type = bsrc->Union.variants[0];
  9372. o->mode = Addressing_OptionalOk;
  9373. } else {
  9374. Type *t = check_type(c, ta->type);
  9375. Type *dst = t;
  9376. if (is_type_union(src)) {
  9377. bool ok = false;
  9378. for (Type *vt : bsrc->Union.variants) {
  9379. if (are_types_identical(vt, dst)) {
  9380. ok = true;
  9381. break;
  9382. }
  9383. }
  9384. if (!ok) {
  9385. gbString expr_str = expr_to_string(o->expr);
  9386. gbString dst_type_str = type_to_string(t);
  9387. defer (gb_string_free(expr_str));
  9388. defer (gb_string_free(dst_type_str));
  9389. if (bsrc->Union.variants.count == 0) {
  9390. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  9391. } else {
  9392. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  9393. }
  9394. o->mode = Addressing_Invalid;
  9395. o->expr = node;
  9396. return kind;
  9397. }
  9398. add_type_info_type(c, o->type);
  9399. add_type_info_type(c, t);
  9400. o->type = t;
  9401. o->mode = Addressing_OptionalOk;
  9402. } else if (is_type_any(src)) {
  9403. o->type = t;
  9404. o->mode = Addressing_OptionalOk;
  9405. add_type_info_type(c, o->type);
  9406. add_type_info_type(c, t);
  9407. } else {
  9408. gbString str = type_to_string(o->type);
  9409. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  9410. gb_string_free(str);
  9411. o->mode = Addressing_Invalid;
  9412. o->expr = node;
  9413. return kind;
  9414. }
  9415. }
  9416. end:;
  9417. if ((c->state_flags & StateFlag_no_type_assert) == 0) {
  9418. add_package_dependency(c, "runtime", "type_assertion_check");
  9419. add_package_dependency(c, "runtime", "type_assertion_check2");
  9420. }
  9421. return kind;
  9422. }
  9423. gb_internal ExprKind check_selector_call_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9424. ast_node(se, SelectorCallExpr, node);
  9425. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  9426. // COM APIs is a great example of where this kind of thing is extremely useful
  9427. // General idea:
  9428. //
  9429. // x->y(123) == x.y(x, 123)
  9430. //
  9431. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  9432. // Just regenerating a new AST aids things
  9433. //
  9434. // TODO(bill): Is this a good hack or not?
  9435. //
  9436. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  9437. if (se->modified_call) {
  9438. // Prevent double evaluation
  9439. o->expr = node;
  9440. o->type = node->tav.type;
  9441. o->value = node->tav.value;
  9442. o->mode = node->tav.mode;
  9443. return Expr_Expr;
  9444. }
  9445. bool allow_arrow_right_selector_expr;
  9446. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9447. c->allow_arrow_right_selector_expr = true;
  9448. Operand x = {};
  9449. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  9450. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9451. if (x.mode == Addressing_Invalid || (x.type == t_invalid && x.mode != Addressing_ProcGroup)) {
  9452. o->mode = Addressing_Invalid;
  9453. o->type = t_invalid;
  9454. o->expr = node;
  9455. return kind;
  9456. }
  9457. if (!is_type_proc(x.type) && x.mode != Addressing_ProcGroup) {
  9458. gbString type_str = type_to_string(x.type);
  9459. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  9460. gb_string_free(type_str);
  9461. o->mode = Addressing_Invalid;
  9462. o->type = t_invalid;
  9463. o->expr = node;
  9464. return Expr_Stmt;
  9465. }
  9466. ast_node(ce, CallExpr, se->call);
  9467. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  9468. Ast *first_arg = x.expr->SelectorExpr.expr;
  9469. GB_ASSERT(first_arg != nullptr);
  9470. Entity *e = entity_of_node(se->expr);
  9471. if (!(e != nullptr && (e->kind == Entity_Procedure || e->kind == Entity_ProcGroup))) {
  9472. first_arg->state_flags |= StateFlag_SelectorCallExpr;
  9473. }
  9474. if (e->kind != Entity_ProcGroup) {
  9475. Type *pt = base_type(x.type);
  9476. GB_ASSERT_MSG(pt->kind == Type_Proc, "%.*s %.*s %s", LIT(e->token.string), LIT(entity_strings[e->kind]), type_to_string(x.type));
  9477. Type *first_type = nullptr;
  9478. String first_arg_name = {};
  9479. if (pt->Proc.param_count > 0) {
  9480. Entity *f = pt->Proc.params->Tuple.variables[0];
  9481. first_type = f->type;
  9482. first_arg_name = f->token.string;
  9483. }
  9484. if (first_arg_name.len == 0) {
  9485. first_arg_name = str_lit("_");
  9486. }
  9487. if (first_type == nullptr) {
  9488. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  9489. o->mode = Addressing_Invalid;
  9490. o->type = t_invalid;
  9491. o->expr = node;
  9492. return Expr_Stmt;
  9493. }
  9494. Operand y = {};
  9495. y.mode = first_arg->tav.mode;
  9496. y.type = first_arg->tav.type;
  9497. y.value = first_arg->tav.value;
  9498. if (check_is_assignable_to(c, &y, first_type)) {
  9499. // Do nothing, it's valid
  9500. } else {
  9501. Operand z = y;
  9502. z.type = type_deref(y.type);
  9503. if (check_is_assignable_to(c, &z, first_type)) {
  9504. // NOTE(bill): AST GENERATION HACK!
  9505. Token op = {Token_Pointer};
  9506. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  9507. } else if (y.mode == Addressing_Variable) {
  9508. Operand w = y;
  9509. w.type = alloc_type_pointer(y.type);
  9510. if (check_is_assignable_to(c, &w, first_type)) {
  9511. // NOTE(bill): AST GENERATION HACK!
  9512. Token op = {Token_And};
  9513. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  9514. }
  9515. }
  9516. }
  9517. if (ce->args.count > 0) {
  9518. bool fail = false;
  9519. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  9520. for (Ast *arg : ce->args) {
  9521. bool mix = false;
  9522. if (first_is_field_value) {
  9523. mix = arg->kind != Ast_FieldValue;
  9524. } else {
  9525. mix = arg->kind == Ast_FieldValue;
  9526. }
  9527. if (mix) {
  9528. fail = true;
  9529. break;
  9530. }
  9531. }
  9532. if (!fail && first_is_field_value) {
  9533. Token op = {Token_Eq};
  9534. AstFile *f = first_arg->file();
  9535. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  9536. }
  9537. }
  9538. }
  9539. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  9540. modified_args[0] = first_arg;
  9541. slice_copy(&modified_args, ce->args, 1);
  9542. ce->args = modified_args;
  9543. se->modified_call = true;
  9544. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  9545. c->allow_arrow_right_selector_expr = true;
  9546. check_expr_base(c, o, se->call, type_hint);
  9547. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  9548. o->expr = node;
  9549. return Expr_Expr;
  9550. }
  9551. gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9552. ExprKind kind = Expr_Expr;
  9553. ast_node(ie, IndexExpr, node);
  9554. check_expr(c, o, ie->expr);
  9555. node->viral_state_flags |= ie->expr->viral_state_flags;
  9556. if (o->mode == Addressing_Invalid) {
  9557. o->expr = node;
  9558. return kind;
  9559. }
  9560. Type *t = base_type(type_deref(o->type));
  9561. bool is_ptr = is_type_pointer(o->type);
  9562. bool is_const = o->mode == Addressing_Constant;
  9563. if (is_type_map(t)) {
  9564. Operand key = {};
  9565. if (is_type_typeid(t->Map.key)) {
  9566. check_expr_or_type(c, &key, ie->index, t->Map.key);
  9567. } else {
  9568. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  9569. }
  9570. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  9571. if (key.mode == Addressing_Invalid) {
  9572. o->mode = Addressing_Invalid;
  9573. o->expr = node;
  9574. return kind;
  9575. }
  9576. o->mode = Addressing_MapIndex;
  9577. o->type = t->Map.value;
  9578. o->expr = node;
  9579. add_map_get_dependencies(c);
  9580. add_map_set_dependencies(c);
  9581. return Expr_Expr;
  9582. }
  9583. i64 max_count = -1;
  9584. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  9585. if (is_const) {
  9586. if (is_type_array(t)) {
  9587. // Okay
  9588. } else if (is_type_slice(t)) {
  9589. // Okay
  9590. } else if (is_type_enumerated_array(t)) {
  9591. // Okay
  9592. } else if (is_type_string(t)) {
  9593. // Okay
  9594. } else if (is_type_matrix(t)) {
  9595. // Okay
  9596. } else {
  9597. valid = false;
  9598. }
  9599. }
  9600. if (!valid) {
  9601. gbString str = expr_to_string(o->expr);
  9602. gbString type_str = type_to_string(o->type);
  9603. defer (gb_string_free(str));
  9604. defer (gb_string_free(type_str));
  9605. if (is_const) {
  9606. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  9607. } else {
  9608. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  9609. }
  9610. o->mode = Addressing_Invalid;
  9611. o->expr = node;
  9612. return kind;
  9613. }
  9614. if (ie->index == nullptr) {
  9615. gbString str = expr_to_string(o->expr);
  9616. error(o->expr, "Missing index for '%s'", str);
  9617. gb_string_free(str);
  9618. o->mode = Addressing_Invalid;
  9619. o->expr = node;
  9620. return kind;
  9621. }
  9622. Type *index_type_hint = nullptr;
  9623. if (is_type_enumerated_array(t)) {
  9624. Type *bt = base_type(t);
  9625. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  9626. index_type_hint = bt->EnumeratedArray.index;
  9627. }
  9628. i64 index = 0;
  9629. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  9630. if (is_const) {
  9631. if (index < 0) {
  9632. ERROR_BLOCK();
  9633. gbString str = expr_to_string(o->expr);
  9634. error(o->expr, "Cannot index a constant '%s'", str);
  9635. if (!build_context.terse_errors) {
  9636. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9637. }
  9638. gb_string_free(str);
  9639. o->mode = Addressing_Invalid;
  9640. o->expr = node;
  9641. return kind;
  9642. } else if (ok && !is_type_matrix(t)) {
  9643. TypeAndValue tav = type_and_value_of_expr(ie->expr);
  9644. ExactValue value = tav.value;
  9645. o->mode = Addressing_Constant;
  9646. bool success = false;
  9647. bool finish = false;
  9648. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  9649. if (!success) {
  9650. ERROR_BLOCK();
  9651. gbString str = expr_to_string(o->expr);
  9652. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  9653. if (!build_context.terse_errors) {
  9654. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9655. }
  9656. gb_string_free(str);
  9657. o->mode = Addressing_Invalid;
  9658. o->expr = node;
  9659. return kind;
  9660. }
  9661. }
  9662. }
  9663. if (type_hint != nullptr && is_type_matrix(t)) {
  9664. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  9665. // if a type hint exists
  9666. }
  9667. return kind;
  9668. }
  9669. gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9670. ExprKind kind = Expr_Stmt;
  9671. ast_node(se, SliceExpr, node);
  9672. check_expr(c, o, se->expr);
  9673. node->viral_state_flags |= se->expr->viral_state_flags;
  9674. if (o->mode == Addressing_Invalid) {
  9675. o->mode = Addressing_Invalid;
  9676. o->expr = node;
  9677. return kind;
  9678. }
  9679. bool valid = false;
  9680. i64 max_count = -1;
  9681. Type *t = base_type(type_deref(o->type));
  9682. switch (t->kind) {
  9683. case Type_Basic:
  9684. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  9685. valid = true;
  9686. if (o->mode == Addressing_Constant) {
  9687. GB_ASSERT(o->value.kind == ExactValue_String);
  9688. max_count = o->value.value_string.len;
  9689. }
  9690. o->type = type_deref(o->type);
  9691. } else if (t->Basic.kind == Basic_string16) {
  9692. valid = true;
  9693. if (o->mode == Addressing_Constant) {
  9694. GB_ASSERT(o->value.kind == ExactValue_String16);
  9695. max_count = o->value.value_string16.len;
  9696. }
  9697. o->type = type_deref(o->type);
  9698. }
  9699. break;
  9700. case Type_Array:
  9701. valid = true;
  9702. max_count = t->Array.count;
  9703. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9704. gbString str = expr_to_string(node);
  9705. error(node, "Cannot slice array '%s', value is not addressable", str);
  9706. gb_string_free(str);
  9707. o->mode = Addressing_Invalid;
  9708. o->expr = node;
  9709. return kind;
  9710. }
  9711. o->type = alloc_type_slice(t->Array.elem);
  9712. break;
  9713. case Type_MultiPointer:
  9714. valid = true;
  9715. o->type = type_deref(o->type);
  9716. break;
  9717. case Type_Slice:
  9718. valid = true;
  9719. o->type = type_deref(o->type);
  9720. break;
  9721. case Type_DynamicArray:
  9722. valid = true;
  9723. o->type = alloc_type_slice(t->DynamicArray.elem);
  9724. break;
  9725. case Type_Struct:
  9726. if (is_type_soa_struct(t)) {
  9727. valid = true;
  9728. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9729. max_count = t->Struct.soa_count;
  9730. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  9731. gbString str = expr_to_string(node);
  9732. error(node, "Cannot slice #soa array '%s', value is not addressable", str);
  9733. gb_string_free(str);
  9734. o->mode = Addressing_Invalid;
  9735. o->expr = node;
  9736. return kind;
  9737. }
  9738. }
  9739. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  9740. }
  9741. break;
  9742. case Type_EnumeratedArray:
  9743. {
  9744. gbString str = expr_to_string(o->expr);
  9745. gbString type_str = type_to_string(o->type);
  9746. error(o->expr, "Cannot slice '%s' of type '%s', as enumerated arrays cannot be sliced", str, type_str);
  9747. gb_string_free(type_str);
  9748. gb_string_free(str);
  9749. o->mode = Addressing_Invalid;
  9750. o->expr = node;
  9751. return kind;
  9752. }
  9753. break;
  9754. }
  9755. if (!valid) {
  9756. gbString str = expr_to_string(o->expr);
  9757. gbString type_str = type_to_string(o->type);
  9758. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  9759. gb_string_free(type_str);
  9760. gb_string_free(str);
  9761. o->mode = Addressing_Invalid;
  9762. o->expr = node;
  9763. return kind;
  9764. }
  9765. if (se->low == nullptr && se->high != nullptr) {
  9766. // It is okay to continue as it will assume the 1st index is zero
  9767. }
  9768. i64 indices[2] = {};
  9769. Ast *nodes[2] = {se->low, se->high};
  9770. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9771. i64 index = max_count;
  9772. if (nodes[i] != nullptr) {
  9773. i64 capacity = -1;
  9774. if (max_count >= 0) {
  9775. capacity = max_count;
  9776. }
  9777. i64 j = 0;
  9778. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  9779. index = j;
  9780. }
  9781. node->viral_state_flags |= nodes[i]->viral_state_flags;
  9782. } else if (i == 0) {
  9783. index = 0;
  9784. }
  9785. indices[i] = index;
  9786. }
  9787. for (isize i = 0; i < gb_count_of(indices); i++) {
  9788. i64 a = indices[i];
  9789. for (isize j = i+1; j < gb_count_of(indices); j++) {
  9790. i64 b = indices[j];
  9791. if (a > b && b >= 0) {
  9792. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  9793. }
  9794. }
  9795. }
  9796. if (max_count < 0) {
  9797. if (o->mode == Addressing_Constant) {
  9798. gbString s = expr_to_string(se->expr);
  9799. error(se->expr, "Cannot slice constant value '%s'", s);
  9800. gb_string_free(s);
  9801. }
  9802. }
  9803. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  9804. /*
  9805. x[:] -> [^]T
  9806. x[i:] -> [^]T
  9807. x[:n] -> []T
  9808. x[i:n] -> []T
  9809. */
  9810. o->type = alloc_type_slice(t->MultiPointer.elem);
  9811. }
  9812. o->mode = Addressing_Value;
  9813. if (is_type_string(t) && max_count >= 0) {
  9814. bool all_constant = true;
  9815. for (isize i = 0; i < gb_count_of(nodes); i++) {
  9816. if (nodes[i] != nullptr) {
  9817. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  9818. if (tav.mode != Addressing_Constant) {
  9819. all_constant = false;
  9820. break;
  9821. }
  9822. }
  9823. }
  9824. if (!all_constant) {
  9825. ERROR_BLOCK();
  9826. gbString str = expr_to_string(o->expr);
  9827. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  9828. if (!build_context.terse_errors) {
  9829. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  9830. }
  9831. gb_string_free(str);
  9832. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  9833. o->expr = node;
  9834. return kind;
  9835. }
  9836. o->mode = Addressing_Constant;
  9837. o->type = t;
  9838. if (o->value.kind == ExactValue_String16) {
  9839. String16 s = o->value.value_string16;
  9840. o->value = exact_value_string16(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9841. } else {
  9842. String s = {};
  9843. if (o->value.kind == ExactValue_String) {
  9844. s = o->value.value_string;
  9845. }
  9846. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  9847. }
  9848. }
  9849. return kind;
  9850. }
  9851. gb_internal ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  9852. u32 prev_state_flags = c->state_flags;
  9853. defer (c->state_flags = prev_state_flags);
  9854. if (node->state_flags != 0) {
  9855. u32 in = node->state_flags;
  9856. u32 out = c->state_flags;
  9857. if (in & StateFlag_no_bounds_check) {
  9858. out |= StateFlag_no_bounds_check;
  9859. out &= ~StateFlag_bounds_check;
  9860. } else if (in & StateFlag_bounds_check) {
  9861. out |= StateFlag_bounds_check;
  9862. out &= ~StateFlag_no_bounds_check;
  9863. }
  9864. if (in & StateFlag_no_type_assert) {
  9865. out |= StateFlag_no_type_assert;
  9866. out &= ~StateFlag_type_assert;
  9867. } else if (in & StateFlag_type_assert) {
  9868. out |= StateFlag_type_assert;
  9869. out &= ~StateFlag_no_type_assert;
  9870. }
  9871. c->state_flags = out;
  9872. }
  9873. ExprKind kind = Expr_Stmt;
  9874. o->mode = Addressing_Invalid;
  9875. o->type = t_invalid;
  9876. o->value = {ExactValue_Invalid};
  9877. switch (node->kind) {
  9878. default:
  9879. return kind;
  9880. case_ast_node(be, BadExpr, node)
  9881. return kind;
  9882. case_end;
  9883. case_ast_node(i, Implicit, node);
  9884. switch (i->kind) {
  9885. case Token_context:
  9886. {
  9887. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  9888. error(node, "'context' is only allowed within procedures");
  9889. return kind;
  9890. }
  9891. if (unparen_expr(c->assignment_lhs_hint) == node) {
  9892. c->scope->flags |= ScopeFlag_ContextDefined;
  9893. }
  9894. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  9895. error(node, "'context' has not been defined within this scope");
  9896. // Continue with value
  9897. }
  9898. init_core_context(c->checker);
  9899. o->mode = Addressing_Context;
  9900. o->type = t_context;
  9901. }
  9902. break;
  9903. default:
  9904. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  9905. return kind;
  9906. }
  9907. case_end;
  9908. case_ast_node(i, Ident, node);
  9909. check_ident(c, o, node, nullptr, type_hint, false);
  9910. case_end;
  9911. case_ast_node(u, Uninit, node);
  9912. o->mode = Addressing_Value;
  9913. o->type = t_untyped_uninit;
  9914. error(node, "Global variables will always be zeroed if left unassigned, --- is disallowed");
  9915. case_end;
  9916. case_ast_node(bl, BasicLit, node);
  9917. Type *t = t_invalid;
  9918. switch (node->tav.value.kind) {
  9919. case ExactValue_String: t = t_untyped_string; break;
  9920. case ExactValue_String16: t = t_string16; break; // TODO(bill): determine this correctly
  9921. case ExactValue_Float: t = t_untyped_float; break;
  9922. case ExactValue_Complex: t = t_untyped_complex; break;
  9923. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  9924. case ExactValue_Integer:
  9925. t = t_untyped_integer;
  9926. if (bl->token.kind == Token_Rune) {
  9927. t = t_untyped_rune;
  9928. }
  9929. break;
  9930. default:
  9931. GB_PANIC("Unhandled value type for basic literal");
  9932. break;
  9933. }
  9934. o->mode = Addressing_Constant;
  9935. o->type = t;
  9936. o->value = node->tav.value;
  9937. case_end;
  9938. case_ast_node(bd, BasicDirective, node);
  9939. kind = check_basic_directive_expr(c, o, node, type_hint);
  9940. case_end;
  9941. case_ast_node(pg, ProcGroup, node);
  9942. error(node, "Illegal use of a procedure group");
  9943. o->mode = Addressing_Invalid;
  9944. case_end;
  9945. case_ast_node(pl, ProcLit, node);
  9946. CheckerContext ctx = *c;
  9947. DeclInfo *decl = nullptr;
  9948. Type *type = alloc_type(Type_Proc);
  9949. check_open_scope(&ctx, pl->type);
  9950. {
  9951. decl = make_decl_info(ctx.scope, ctx.decl);
  9952. decl->proc_lit = node;
  9953. ctx.decl = decl;
  9954. defer (ctx.decl = ctx.decl->parent);
  9955. if (pl->tags != 0) {
  9956. error(node, "A procedure literal cannot have tags");
  9957. pl->tags = 0; // TODO(bill): Should I zero this?!
  9958. }
  9959. check_procedure_type(&ctx, type, pl->type);
  9960. if (!is_type_proc(type)) {
  9961. gbString str = expr_to_string(node);
  9962. error(node, "Invalid procedure literal '%s'", str);
  9963. gb_string_free(str);
  9964. check_close_scope(&ctx);
  9965. return kind;
  9966. }
  9967. if (pl->body == nullptr) {
  9968. error(node, "A procedure literal must have a body");
  9969. return kind;
  9970. }
  9971. pl->decl = decl;
  9972. check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  9973. mutex_lock(&ctx.checker->nested_proc_lits_mutex);
  9974. array_add(&ctx.checker->nested_proc_lits, decl);
  9975. mutex_unlock(&ctx.checker->nested_proc_lits_mutex);
  9976. }
  9977. check_close_scope(&ctx);
  9978. o->mode = Addressing_Value;
  9979. o->type = type;
  9980. case_end;
  9981. case_ast_node(te, TernaryIfExpr, node);
  9982. kind = check_ternary_if_expr(c, o, node, type_hint);
  9983. case_end;
  9984. case_ast_node(te, TernaryWhenExpr, node);
  9985. kind = check_ternary_when_expr(c, o, node, type_hint);
  9986. case_end;
  9987. case_ast_node(oe, OrElseExpr, node);
  9988. return check_or_else_expr(c, o, node, type_hint);
  9989. case_end;
  9990. case_ast_node(re, OrReturnExpr, node);
  9991. node->viral_state_flags |= ViralStateFlag_ContainsOrReturn;
  9992. return check_or_return_expr(c, o, node, type_hint);
  9993. case_end;
  9994. case_ast_node(re, OrBranchExpr, node);
  9995. return check_or_branch_expr(c, o, node, type_hint);
  9996. case_end;
  9997. case_ast_node(cl, CompoundLit, node);
  9998. kind = check_compound_literal(c, o, node, type_hint);
  9999. case_end;
  10000. case_ast_node(pe, ParenExpr, node);
  10001. kind = check_expr_base(c, o, pe->expr, type_hint);
  10002. node->viral_state_flags |= pe->expr->viral_state_flags;
  10003. o->expr = node;
  10004. case_end;
  10005. case_ast_node(te, TagExpr, node);
  10006. String name = te->name.string;
  10007. error(node, "Unknown tag expression, #%.*s", LIT(name));
  10008. if (te->expr) {
  10009. kind = check_expr_base(c, o, te->expr, type_hint);
  10010. node->viral_state_flags |= te->expr->viral_state_flags;
  10011. }
  10012. o->expr = node;
  10013. case_end;
  10014. case_ast_node(ta, TypeAssertion, node);
  10015. kind = check_type_assertion(c, o, node, type_hint);
  10016. case_end;
  10017. case_ast_node(tc, TypeCast, node);
  10018. check_expr_or_type(c, o, tc->type);
  10019. if (o->mode != Addressing_Type) {
  10020. gbString str = expr_to_string(tc->type);
  10021. error(tc->type, "Expected a type, got %s", str);
  10022. gb_string_free(str);
  10023. o->mode = Addressing_Invalid;
  10024. }
  10025. if (o->mode == Addressing_Invalid) {
  10026. o->expr = node;
  10027. return kind;
  10028. }
  10029. Type *type = o->type;
  10030. check_expr_base(c, o, tc->expr, type);
  10031. node->viral_state_flags |= tc->expr->viral_state_flags;
  10032. if (o->mode != Addressing_Invalid) {
  10033. switch (tc->token.kind) {
  10034. case Token_transmute:
  10035. check_transmute(c, node, o, type, true);
  10036. break;
  10037. case Token_cast:
  10038. check_cast(c, o, type, true);
  10039. break;
  10040. default:
  10041. error(node, "Invalid AST: Invalid casting expression");
  10042. o->mode = Addressing_Invalid;
  10043. break;
  10044. }
  10045. }
  10046. return Expr_Expr;
  10047. case_end;
  10048. case_ast_node(ac, AutoCast, node);
  10049. check_expr_base(c, o, ac->expr, type_hint);
  10050. node->viral_state_flags |= ac->expr->viral_state_flags;
  10051. if (o->mode == Addressing_Invalid) {
  10052. o->expr = node;
  10053. return kind;
  10054. }
  10055. if (type_hint) {
  10056. check_cast(c, o, type_hint);
  10057. }
  10058. o->expr = node;
  10059. return Expr_Expr;
  10060. case_end;
  10061. case_ast_node(ue, UnaryExpr, node);
  10062. Type *th = type_hint;
  10063. if (ue->op.kind == Token_And) {
  10064. th = type_deref(th);
  10065. }
  10066. check_expr_base(c, o, ue->expr, th);
  10067. node->viral_state_flags |= ue->expr->viral_state_flags;
  10068. if (o->mode != Addressing_Invalid) {
  10069. check_unary_expr(c, o, ue->op, node);
  10070. }
  10071. o->expr = node;
  10072. return Expr_Expr;
  10073. case_end;
  10074. case_ast_node(be, BinaryExpr, node);
  10075. check_binary_expr(c, o, node, type_hint, true);
  10076. if (o->mode == Addressing_Invalid) {
  10077. o->expr = node;
  10078. return kind;
  10079. }
  10080. case_end;
  10081. case_ast_node(se, SelectorExpr, node);
  10082. check_selector(c, o, node, type_hint);
  10083. node->viral_state_flags |= se->expr->viral_state_flags;
  10084. case_end;
  10085. case_ast_node(se, SelectorCallExpr, node);
  10086. return check_selector_call_expr(c, o, node, type_hint);
  10087. case_end;
  10088. case_ast_node(ise, ImplicitSelectorExpr, node);
  10089. return check_implicit_selector_expr(c, o, node, type_hint);
  10090. case_end;
  10091. case_ast_node(ie, IndexExpr, node);
  10092. kind = check_index_expr(c, o, node, type_hint);
  10093. case_end;
  10094. case_ast_node(se, SliceExpr, node);
  10095. kind = check_slice_expr(c, o, node, type_hint);
  10096. case_end;
  10097. case_ast_node(mie, MatrixIndexExpr, node);
  10098. check_matrix_index_expr(c, o, node, type_hint);
  10099. o->expr = node;
  10100. return Expr_Expr;
  10101. case_end;
  10102. case_ast_node(ce, CallExpr, node);
  10103. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  10104. case_end;
  10105. case_ast_node(de, DerefExpr, node);
  10106. check_expr_or_type(c, o, de->expr);
  10107. node->viral_state_flags |= de->expr->viral_state_flags;
  10108. if (o->mode == Addressing_Invalid) {
  10109. o->mode = Addressing_Invalid;
  10110. o->expr = node;
  10111. return kind;
  10112. } else if (o->mode == Addressing_Type) {
  10113. gbString str = expr_to_string(o->expr);
  10114. error(o->expr, "Cannot dereference '%s' because it is a type", str);
  10115. o->mode = Addressing_Invalid;
  10116. o->expr = node;
  10117. return kind;
  10118. } else {
  10119. Type *t = base_type(o->type);
  10120. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  10121. o->mode = Addressing_Variable;
  10122. o->type = t->Pointer.elem;
  10123. } else if (t->kind == Type_SoaPointer) {
  10124. o->mode = Addressing_SoaVariable;
  10125. o->type = type_deref(t);
  10126. } else {
  10127. gbString str = expr_to_string(o->expr);
  10128. gbString typ = type_to_string(o->type);
  10129. ERROR_BLOCK();
  10130. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  10131. if (o->type && is_type_multi_pointer(o->type)) {
  10132. if (!build_context.terse_errors) {
  10133. error_line("\tDid you mean '%s[0]'?\n", str);
  10134. }
  10135. }
  10136. gb_string_free(typ);
  10137. gb_string_free(str);
  10138. o->mode = Addressing_Invalid;
  10139. o->expr = node;
  10140. return kind;
  10141. }
  10142. }
  10143. case_end;
  10144. case_ast_node(ia, InlineAsmExpr, node);
  10145. if (c->curr_proc_decl == nullptr) {
  10146. error(node, "Inline asm expressions are only allowed within a procedure body");
  10147. }
  10148. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  10149. Type *return_type = nullptr;
  10150. for_array(i, ia->param_types) {
  10151. param_types[i] = check_type(c, ia->param_types[i]);
  10152. }
  10153. if (ia->return_type != nullptr) {
  10154. return_type = check_type(c, ia->return_type);
  10155. }
  10156. Operand x = {};
  10157. check_expr(c, &x, ia->asm_string);
  10158. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10159. error(x.expr, "Expected a constant string for the inline asm main parameter");
  10160. }
  10161. check_expr(c, &x, ia->constraints_string);
  10162. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  10163. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  10164. }
  10165. Scope *scope = create_scope(c->info, c->scope);
  10166. scope->flags |= ScopeFlag_Proc;
  10167. Type *params = alloc_type_tuple();
  10168. Type *results = alloc_type_tuple();
  10169. if (param_types.count != 0) {
  10170. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  10171. for_array(i, param_types) {
  10172. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  10173. }
  10174. }
  10175. if (return_type != nullptr) {
  10176. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  10177. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  10178. }
  10179. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  10180. o->type = pt;
  10181. o->mode = Addressing_Value;
  10182. o->expr = node;
  10183. return Expr_Expr;
  10184. case_end;
  10185. case Ast_DistinctType:
  10186. case Ast_TypeidType:
  10187. case Ast_PolyType:
  10188. case Ast_ProcType:
  10189. case Ast_PointerType:
  10190. case Ast_MultiPointerType:
  10191. case Ast_ArrayType:
  10192. case Ast_DynamicArrayType:
  10193. case Ast_StructType:
  10194. case Ast_UnionType:
  10195. case Ast_EnumType:
  10196. case Ast_MapType:
  10197. case Ast_BitSetType:
  10198. case Ast_MatrixType:
  10199. case Ast_RelativeType:
  10200. o->mode = Addressing_Type;
  10201. o->type = check_type(c, node);
  10202. break;
  10203. }
  10204. kind = Expr_Expr;
  10205. o->expr = node;
  10206. return kind;
  10207. }
  10208. gb_internal ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  10209. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  10210. if (o->type != nullptr && core_type(o->type) == nullptr) {
  10211. o->type = t_invalid;
  10212. gbString xs = expr_to_string(o->expr);
  10213. if (o->mode == Addressing_Type) {
  10214. error(o->expr, "Invalid type usage '%s'", xs);
  10215. } else {
  10216. error(o->expr, "Invalid expression '%s'", xs);
  10217. }
  10218. gb_string_free(xs);
  10219. }
  10220. if (o->type != nullptr && is_type_untyped(o->type)) {
  10221. add_untyped(c, node, o->mode, o->type, o->value);
  10222. }
  10223. check_rtti_type_disallowed(node, o->type, "An expression is using a type, %s, which has been disallowed");
  10224. add_type_and_value(c, node, o->mode, o->type, o->value);
  10225. return kind;
  10226. }
  10227. gb_internal void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  10228. check_expr_base(c, o, e, nullptr);
  10229. switch (o->mode) {
  10230. default:
  10231. return; // NOTE(bill): Valid
  10232. case Addressing_NoValue:
  10233. error_operand_no_value(o);
  10234. break;
  10235. }
  10236. o->mode = Addressing_Invalid;
  10237. }
  10238. gb_internal void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  10239. check_expr_base(c, o, e, nullptr);
  10240. switch (o->mode) {
  10241. default:
  10242. return; // NOTE(bill): Valid
  10243. case Addressing_NoValue:
  10244. error_operand_no_value(o);
  10245. break;
  10246. case Addressing_Type:
  10247. error_operand_not_expression(o);
  10248. break;
  10249. }
  10250. o->mode = Addressing_Invalid;
  10251. }
  10252. gb_internal void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10253. check_expr_base(c, o, e, type_hint);
  10254. switch (o->mode) {
  10255. default:
  10256. return; // NOTE(bill): Valid
  10257. case Addressing_NoValue:
  10258. error_operand_no_value(o);
  10259. break;
  10260. case Addressing_Type:
  10261. error_operand_not_expression(o);
  10262. break;
  10263. }
  10264. o->mode = Addressing_Invalid;
  10265. }
  10266. gb_internal void check_not_tuple(CheckerContext *c, Operand *o) {
  10267. if (o->mode == Addressing_Value) {
  10268. // NOTE(bill): Tuples are not first class thus never named
  10269. if (o->type->kind == Type_Tuple) {
  10270. isize count = o->type->Tuple.variables.count;
  10271. error(o->expr,
  10272. "%td-valued expression found where single value expected", count);
  10273. o->mode = Addressing_Invalid;
  10274. GB_ASSERT(count != 1);
  10275. }
  10276. }
  10277. }
  10278. gb_internal void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  10279. check_multi_expr(c, o, e);
  10280. check_not_tuple(c, o);
  10281. }
  10282. gb_internal void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  10283. check_expr_base(c, o, e, type_hint);
  10284. check_not_tuple(c, o);
  10285. error_operand_no_value(o);
  10286. }
  10287. gb_internal bool is_exact_value_zero(ExactValue const &v) {
  10288. switch (v.kind) {
  10289. case ExactValue_Invalid:
  10290. return true;
  10291. case ExactValue_Bool:
  10292. return !v.value_bool;
  10293. case ExactValue_String:
  10294. return v.value_string.len == 0;
  10295. case ExactValue_String16:
  10296. return v.value_string16.len == 0;
  10297. case ExactValue_Integer:
  10298. return big_int_is_zero(&v.value_integer);
  10299. case ExactValue_Float:
  10300. return v.value_float == 0.0;
  10301. case ExactValue_Complex:
  10302. if (v.value_complex) {
  10303. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  10304. }
  10305. return true;
  10306. case ExactValue_Quaternion:
  10307. if (v.value_quaternion) {
  10308. return v.value_quaternion->real == 0.0 &&
  10309. v.value_quaternion->imag == 0.0 &&
  10310. v.value_quaternion->jmag == 0.0 &&
  10311. v.value_quaternion->kmag == 0.0;
  10312. }
  10313. return true;
  10314. case ExactValue_Pointer:
  10315. return v.value_pointer == 0;
  10316. case ExactValue_Compound:
  10317. if (v.value_compound == nullptr) {
  10318. return true;
  10319. } else {
  10320. ast_node(cl, CompoundLit, v.value_compound);
  10321. if (cl->elems.count == 0) {
  10322. return true;
  10323. } else {
  10324. for (Ast *elem : cl->elems) {
  10325. if (elem->tav.mode != Addressing_Constant) {
  10326. return false;
  10327. }
  10328. if (!is_exact_value_zero(elem->tav.value)) {
  10329. return false;
  10330. }
  10331. }
  10332. return true;
  10333. }
  10334. }
  10335. case ExactValue_Procedure:
  10336. return v.value_procedure == nullptr;
  10337. case ExactValue_Typeid:
  10338. return v.value_typeid == nullptr;
  10339. }
  10340. return true;
  10341. }
  10342. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  10343. gb_internal gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  10344. for_array(i, params) {
  10345. if (i > 0) {
  10346. str = gb_string_appendc(str, ", ");
  10347. }
  10348. str = write_expr_to_string(str, params[i], false);
  10349. }
  10350. return str;
  10351. }
  10352. gb_internal gbString string_append_string(gbString str, String string) {
  10353. if (string.len > 0) {
  10354. return gb_string_append_length(str, &string[0], string.len);
  10355. }
  10356. return str;
  10357. }
  10358. gb_internal gbString string_append_token(gbString str, Token token) {
  10359. str = string_append_string(str, token.string);
  10360. return str;
  10361. }
  10362. gb_internal gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  10363. if (node == nullptr)
  10364. return str;
  10365. if (is_ast_stmt(node)) {
  10366. GB_ASSERT("stmt passed to write_expr_to_string");
  10367. }
  10368. switch (node->kind) {
  10369. default:
  10370. str = gb_string_appendc(str, "(BadExpr)");
  10371. break;
  10372. case_ast_node(i, Ident, node);
  10373. str = string_append_token(str, i->token);
  10374. case_end;
  10375. case_ast_node(i, Implicit, node);
  10376. str = string_append_token(str, *i);
  10377. case_end;
  10378. case_ast_node(bl, BasicLit, node);
  10379. str = string_append_token(str, bl->token);
  10380. case_end;
  10381. case_ast_node(bd, BasicDirective, node);
  10382. str = gb_string_append_rune(str, '#');
  10383. str = string_append_string(str, bd->name.string);
  10384. case_end;
  10385. case_ast_node(ud, Uninit, node);
  10386. str = gb_string_appendc(str, "---");
  10387. case_end;
  10388. case_ast_node(pg, ProcGroup, node);
  10389. str = gb_string_appendc(str, "proc{");
  10390. for_array(i, pg->args) {
  10391. if (i > 0) str = gb_string_appendc(str, ", ");
  10392. str = write_expr_to_string(str, pg->args[i], shorthand);
  10393. }
  10394. str = gb_string_append_rune(str, '}');
  10395. case_end;
  10396. case_ast_node(pl, ProcLit, node);
  10397. str = write_expr_to_string(str, pl->type, shorthand);
  10398. if (pl->body) {
  10399. str = gb_string_appendc(str, " {...}");
  10400. } else {
  10401. str = gb_string_appendc(str, " ---");
  10402. }
  10403. case_end;
  10404. case_ast_node(cl, CompoundLit, node);
  10405. str = write_expr_to_string(str, cl->type, shorthand);
  10406. str = gb_string_append_rune(str, '{');
  10407. if (shorthand) {
  10408. str = gb_string_appendc(str, "...");
  10409. } else {
  10410. for_array(i, cl->elems) {
  10411. if (i > 0) str = gb_string_appendc(str, ", ");
  10412. str = write_expr_to_string(str, cl->elems[i], shorthand);
  10413. }
  10414. }
  10415. str = gb_string_append_rune(str, '}');
  10416. case_end;
  10417. case_ast_node(te, TagExpr, node);
  10418. str = gb_string_append_rune(str, '#');
  10419. str = string_append_token(str, te->name);
  10420. str = write_expr_to_string(str, te->expr, shorthand);
  10421. case_end;
  10422. case_ast_node(ue, UnaryExpr, node);
  10423. str = string_append_token(str, ue->op);
  10424. str = write_expr_to_string(str, ue->expr, shorthand);
  10425. case_end;
  10426. case_ast_node(de, DerefExpr, node);
  10427. str = write_expr_to_string(str, de->expr, shorthand);
  10428. str = gb_string_append_rune(str, '^');
  10429. case_end;
  10430. case_ast_node(be, BinaryExpr, node);
  10431. str = write_expr_to_string(str, be->left, shorthand);
  10432. str = gb_string_append_rune(str, ' ');
  10433. str = string_append_token(str, be->op);
  10434. str = gb_string_append_rune(str, ' ');
  10435. str = write_expr_to_string(str, be->right, shorthand);
  10436. case_end;
  10437. case_ast_node(te, TernaryIfExpr, node);
  10438. TokenPos x = ast_token(te->x).pos;
  10439. TokenPos cond = ast_token(te->cond).pos;
  10440. if (x < cond) {
  10441. str = write_expr_to_string(str, te->x, shorthand);
  10442. str = gb_string_appendc(str, " if ");
  10443. str = write_expr_to_string(str, te->cond, shorthand);
  10444. str = gb_string_appendc(str, " else ");
  10445. str = write_expr_to_string(str, te->y, shorthand);
  10446. } else {
  10447. str = write_expr_to_string(str, te->cond, shorthand);
  10448. str = gb_string_appendc(str, " ? ");
  10449. str = write_expr_to_string(str, te->x, shorthand);
  10450. str = gb_string_appendc(str, " : ");
  10451. str = write_expr_to_string(str, te->y, shorthand);
  10452. }
  10453. case_end;
  10454. case_ast_node(te, TernaryWhenExpr, node);
  10455. str = write_expr_to_string(str, te->x, shorthand);
  10456. str = gb_string_appendc(str, " when ");
  10457. str = write_expr_to_string(str, te->cond, shorthand);
  10458. str = gb_string_appendc(str, " else ");
  10459. str = write_expr_to_string(str, te->y, shorthand);
  10460. case_end;
  10461. case_ast_node(oe, OrElseExpr, node);
  10462. str = write_expr_to_string(str, oe->x, shorthand);
  10463. str = gb_string_appendc(str, " or_else ");
  10464. str = write_expr_to_string(str, oe->y, shorthand);
  10465. case_end;
  10466. case_ast_node(oe, OrReturnExpr, node);
  10467. str = write_expr_to_string(str, oe->expr, shorthand);
  10468. str = gb_string_appendc(str, " or_return");
  10469. case_end;
  10470. case_ast_node(oe, OrBranchExpr, node);
  10471. str = write_expr_to_string(str, oe->expr, shorthand);
  10472. str = gb_string_append_rune(str, ' ');
  10473. str = string_append_token(str, oe->token);
  10474. if (oe->label) {
  10475. str = gb_string_append_rune(str, ' ');
  10476. str = write_expr_to_string(str, oe->label, shorthand);
  10477. }
  10478. case_end;
  10479. case_ast_node(pe, ParenExpr, node);
  10480. str = gb_string_append_rune(str, '(');
  10481. str = write_expr_to_string(str, pe->expr, shorthand);
  10482. str = gb_string_append_rune(str, ')');
  10483. case_end;
  10484. case_ast_node(se, SelectorExpr, node);
  10485. str = write_expr_to_string(str, se->expr, shorthand);
  10486. str = string_append_token(str, se->token);
  10487. str = write_expr_to_string(str, se->selector, shorthand);
  10488. case_end;
  10489. case_ast_node(se, ImplicitSelectorExpr, node);
  10490. str = gb_string_append_rune(str, '.');
  10491. str = write_expr_to_string(str, se->selector, shorthand);
  10492. case_end;
  10493. case_ast_node(se, SelectorCallExpr, node);
  10494. str = write_expr_to_string(str, se->expr, shorthand);
  10495. str = gb_string_appendc(str, "(");
  10496. ast_node(ce, CallExpr, se->call);
  10497. isize start = se->modified_call ? 1 : 0;
  10498. for (isize i = start; i < ce->args.count; i++) {
  10499. Ast *arg = ce->args[i];
  10500. if (i > start) {
  10501. str = gb_string_appendc(str, ", ");
  10502. }
  10503. str = write_expr_to_string(str, arg, shorthand);
  10504. }
  10505. str = gb_string_appendc(str, ")");
  10506. case_end;
  10507. case_ast_node(ta, TypeAssertion, node);
  10508. str = write_expr_to_string(str, ta->expr, shorthand);
  10509. if (ta->type != nullptr &&
  10510. ta->type->kind == Ast_UnaryExpr &&
  10511. ta->type->UnaryExpr.op.kind == Token_Question) {
  10512. str = gb_string_appendc(str, ".?");
  10513. } else {
  10514. str = gb_string_appendc(str, ".(");
  10515. str = write_expr_to_string(str, ta->type, shorthand);
  10516. str = gb_string_append_rune(str, ')');
  10517. }
  10518. case_end;
  10519. case_ast_node(tc, TypeCast, node);
  10520. str = string_append_token(str, tc->token);
  10521. str = gb_string_append_rune(str, '(');
  10522. str = write_expr_to_string(str, tc->type, shorthand);
  10523. str = gb_string_append_rune(str, ')');
  10524. str = write_expr_to_string(str, tc->expr, shorthand);
  10525. case_end;
  10526. case_ast_node(ac, AutoCast, node);
  10527. str = string_append_token(str, ac->token);
  10528. str = gb_string_append_rune(str, ' ');
  10529. str = write_expr_to_string(str, ac->expr, shorthand);
  10530. case_end;
  10531. case_ast_node(ie, IndexExpr, node);
  10532. str = write_expr_to_string(str, ie->expr, shorthand);
  10533. str = gb_string_append_rune(str, '[');
  10534. str = write_expr_to_string(str, ie->index, shorthand);
  10535. str = gb_string_append_rune(str, ']');
  10536. case_end;
  10537. case_ast_node(se, SliceExpr, node);
  10538. str = write_expr_to_string(str, se->expr, shorthand);
  10539. str = gb_string_append_rune(str, '[');
  10540. str = write_expr_to_string(str, se->low, shorthand);
  10541. str = string_append_token(str, se->interval);
  10542. str = write_expr_to_string(str, se->high, shorthand);
  10543. str = gb_string_append_rune(str, ']');
  10544. case_end;
  10545. case_ast_node(mie, MatrixIndexExpr, node);
  10546. str = write_expr_to_string(str, mie->expr, shorthand);
  10547. str = gb_string_append_rune(str, '[');
  10548. str = write_expr_to_string(str, mie->row_index, shorthand);
  10549. str = gb_string_appendc(str, ", ");
  10550. str = write_expr_to_string(str, mie->column_index, shorthand);
  10551. str = gb_string_append_rune(str, ']');
  10552. case_end;
  10553. case_ast_node(e, Ellipsis, node);
  10554. str = gb_string_appendc(str, "..");
  10555. str = write_expr_to_string(str, e->expr, shorthand);
  10556. case_end;
  10557. case_ast_node(fv, FieldValue, node);
  10558. str = write_expr_to_string(str, fv->field, shorthand);
  10559. str = gb_string_appendc(str, " = ");
  10560. str = write_expr_to_string(str, fv->value, shorthand);
  10561. case_end;
  10562. case_ast_node(fv, EnumFieldValue, node);
  10563. str = write_expr_to_string(str, fv->name, shorthand);
  10564. if (fv->value) {
  10565. str = gb_string_appendc(str, " = ");
  10566. str = write_expr_to_string(str, fv->value, shorthand);
  10567. }
  10568. case_end;
  10569. case_ast_node(ht, HelperType, node);
  10570. str = gb_string_appendc(str, "#type ");
  10571. str = write_expr_to_string(str, ht->type, shorthand);
  10572. case_end;
  10573. case_ast_node(ht, DistinctType, node);
  10574. str = gb_string_appendc(str, "distinct ");
  10575. str = write_expr_to_string(str, ht->type, shorthand);
  10576. case_end;
  10577. case_ast_node(pt, PolyType, node);
  10578. str = gb_string_append_rune(str, '$');
  10579. str = write_expr_to_string(str, pt->type, shorthand);
  10580. if (pt->specialization != nullptr) {
  10581. str = gb_string_append_rune(str, '/');
  10582. str = write_expr_to_string(str, pt->specialization, shorthand);
  10583. }
  10584. case_end;
  10585. case_ast_node(pt, PointerType, node);
  10586. if (pt->tag) {
  10587. str = write_expr_to_string(str, pt->tag, false);
  10588. }
  10589. str = gb_string_append_rune(str, '^');
  10590. str = write_expr_to_string(str, pt->type, shorthand);
  10591. case_end;
  10592. case_ast_node(pt, MultiPointerType, node);
  10593. str = gb_string_appendc(str, "[^]");
  10594. str = write_expr_to_string(str, pt->type, shorthand);
  10595. case_end;
  10596. case_ast_node(at, ArrayType, node);
  10597. if (at->tag) {
  10598. str = write_expr_to_string(str, at->tag, false);
  10599. }
  10600. str = gb_string_append_rune(str, '[');
  10601. if (at->count != nullptr &&
  10602. at->count->kind == Ast_UnaryExpr &&
  10603. at->count->UnaryExpr.op.kind == Token_Question) {
  10604. str = gb_string_appendc(str, "?");
  10605. } else {
  10606. str = write_expr_to_string(str, at->count, shorthand);
  10607. }
  10608. str = gb_string_append_rune(str, ']');
  10609. str = write_expr_to_string(str, at->elem, shorthand);
  10610. case_end;
  10611. case_ast_node(at, DynamicArrayType, node);
  10612. if (at->tag) {
  10613. str = write_expr_to_string(str, at->tag, false);
  10614. }
  10615. str = gb_string_appendc(str, "[dynamic]");
  10616. str = write_expr_to_string(str, at->elem, shorthand);
  10617. case_end;
  10618. case_ast_node(bs, BitSetType, node);
  10619. str = gb_string_appendc(str, "bit_set[");
  10620. str = write_expr_to_string(str, bs->elem, shorthand);
  10621. str = gb_string_appendc(str, "]");
  10622. case_end;
  10623. case_ast_node(mt, MapType, node);
  10624. str = gb_string_appendc(str, "map[");
  10625. str = write_expr_to_string(str, mt->key, shorthand);
  10626. str = gb_string_append_rune(str, ']');
  10627. str = write_expr_to_string(str, mt->value, shorthand);
  10628. case_end;
  10629. case_ast_node(mt, MatrixType, node);
  10630. str = gb_string_appendc(str, "matrix[");
  10631. str = write_expr_to_string(str, mt->row_count, shorthand);
  10632. str = gb_string_appendc(str, ", ");
  10633. str = write_expr_to_string(str, mt->column_count, shorthand);
  10634. str = gb_string_append_rune(str, ']');
  10635. str = write_expr_to_string(str, mt->elem, shorthand);
  10636. case_end;
  10637. case_ast_node(f, Field, node);
  10638. if (f->flags&FieldFlag_using) {
  10639. str = gb_string_appendc(str, "using ");
  10640. }
  10641. if (f->flags&FieldFlag_no_alias) {
  10642. str = gb_string_appendc(str, "#no_alias ");
  10643. }
  10644. if (f->flags&FieldFlag_c_vararg) {
  10645. str = gb_string_appendc(str, "#c_vararg ");
  10646. }
  10647. if (f->flags&FieldFlag_any_int) {
  10648. str = gb_string_appendc(str, "#any_int ");
  10649. }
  10650. if (f->flags&FieldFlag_no_broadcast) {
  10651. str = gb_string_appendc(str, "#no_broadcast ");
  10652. }
  10653. if (f->flags&FieldFlag_const) {
  10654. str = gb_string_appendc(str, "#const ");
  10655. }
  10656. if (f->flags&FieldFlag_subtype) {
  10657. str = gb_string_appendc(str, "#subtype ");
  10658. }
  10659. for_array(i, f->names) {
  10660. Ast *name = f->names[i];
  10661. if (i > 0) str = gb_string_appendc(str, ", ");
  10662. str = write_expr_to_string(str, name, shorthand);
  10663. }
  10664. if (f->names.count > 0) {
  10665. if (f->type == nullptr && f->default_value != nullptr) {
  10666. str = gb_string_append_rune(str, ' ');
  10667. }
  10668. str = gb_string_appendc(str, ":");
  10669. }
  10670. if (f->type != nullptr) {
  10671. str = gb_string_append_rune(str, ' ');
  10672. str = write_expr_to_string(str, f->type, shorthand);
  10673. }
  10674. if (f->default_value != nullptr) {
  10675. if (f->type != nullptr) {
  10676. str = gb_string_append_rune(str, ' ');
  10677. }
  10678. str = gb_string_appendc(str, "= ");
  10679. str = write_expr_to_string(str, f->default_value, shorthand);
  10680. }
  10681. case_end;
  10682. case_ast_node(f, FieldList, node);
  10683. bool has_name = false;
  10684. for_array(i, f->list) {
  10685. ast_node(field, Field, f->list[i]);
  10686. if (field->names.count > 1) {
  10687. has_name = true;
  10688. break;
  10689. }
  10690. if (field->names.count == 0) {
  10691. continue;
  10692. }
  10693. if (!is_blank_ident(field->names[0])) {
  10694. has_name = true;
  10695. break;
  10696. }
  10697. }
  10698. for_array(i, f->list) {
  10699. if (i > 0) str = gb_string_appendc(str, ", ");
  10700. if (has_name) {
  10701. str = write_expr_to_string(str, f->list[i], shorthand);
  10702. } else {
  10703. ast_node(field, Field, f->list[i]);
  10704. if (field->flags&FieldFlag_using) {
  10705. str = gb_string_appendc(str, "using ");
  10706. }
  10707. if (field->flags&FieldFlag_no_alias) {
  10708. str = gb_string_appendc(str, "#no_alias ");
  10709. }
  10710. if (field->flags&FieldFlag_c_vararg) {
  10711. str = gb_string_appendc(str, "#c_vararg ");
  10712. }
  10713. if (field->flags&FieldFlag_any_int) {
  10714. str = gb_string_appendc(str, "#any_int ");
  10715. }
  10716. if (field->flags&FieldFlag_no_broadcast) {
  10717. str = gb_string_appendc(str, "#no_broadcast ");
  10718. }
  10719. if (field->flags&FieldFlag_const) {
  10720. str = gb_string_appendc(str, "#const ");
  10721. }
  10722. if (field->flags&FieldFlag_subtype) {
  10723. str = gb_string_appendc(str, "#subtype ");
  10724. }
  10725. str = write_expr_to_string(str, field->type, shorthand);
  10726. }
  10727. }
  10728. case_end;
  10729. case_ast_node(ce, CallExpr, node);
  10730. switch (ce->inlining) {
  10731. case ProcInlining_inline:
  10732. str = gb_string_appendc(str, "#force_inline ");
  10733. break;
  10734. case ProcInlining_no_inline:
  10735. str = gb_string_appendc(str, "#force_no_inline ");
  10736. break;
  10737. }
  10738. str = write_expr_to_string(str, ce->proc, shorthand);
  10739. str = gb_string_appendc(str, "(");
  10740. isize idx0 = cast(isize)ce->was_selector;
  10741. for (isize i = idx0; i < ce->args.count; i++) {
  10742. Ast *arg = ce->args[i];
  10743. if (i > idx0) {
  10744. str = gb_string_appendc(str, ", ");
  10745. }
  10746. str = write_expr_to_string(str, arg, shorthand);
  10747. }
  10748. str = gb_string_appendc(str, ")");
  10749. case_end;
  10750. case_ast_node(tt, TypeidType, node);
  10751. str = gb_string_appendc(str, "typeid");
  10752. if (tt->specialization) {
  10753. str = gb_string_appendc(str, "/");
  10754. str = write_expr_to_string(str, tt->specialization, shorthand);
  10755. }
  10756. case_end;
  10757. case_ast_node(pt, ProcType, node);
  10758. str = gb_string_appendc(str, "proc(");
  10759. str = write_expr_to_string(str, pt->params, shorthand);
  10760. str = gb_string_appendc(str, ")");
  10761. if (pt->results != nullptr) {
  10762. str = gb_string_appendc(str, " -> ");
  10763. bool parens_needed = false;
  10764. if (pt->results && pt->results->kind == Ast_FieldList) {
  10765. for (Ast *field : pt->results->FieldList.list) {
  10766. ast_node(f, Field, field);
  10767. if (f->names.count != 0) {
  10768. parens_needed = true;
  10769. break;
  10770. }
  10771. }
  10772. }
  10773. if (parens_needed) {
  10774. str = gb_string_append_rune(str, '(');
  10775. }
  10776. str = write_expr_to_string(str, pt->results, shorthand);
  10777. if (parens_needed) {
  10778. str = gb_string_append_rune(str, ')');
  10779. }
  10780. }
  10781. case_end;
  10782. case_ast_node(st, StructType, node);
  10783. str = gb_string_appendc(str, "struct ");
  10784. if (st->polymorphic_params) {
  10785. str = gb_string_append_rune(str, '(');
  10786. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10787. str = gb_string_appendc(str, ") ");
  10788. }
  10789. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  10790. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  10791. if (st->align) {
  10792. str = gb_string_appendc(str, "#align ");
  10793. str = write_expr_to_string(str, st->align, shorthand);
  10794. str = gb_string_append_rune(str, ' ');
  10795. }
  10796. str = gb_string_append_rune(str, '{');
  10797. if (shorthand) {
  10798. str = gb_string_appendc(str, "...");
  10799. } else {
  10800. str = write_struct_fields_to_string(str, st->fields);
  10801. }
  10802. str = gb_string_append_rune(str, '}');
  10803. case_end;
  10804. case_ast_node(st, UnionType, node);
  10805. str = gb_string_appendc(str, "union ");
  10806. if (st->polymorphic_params) {
  10807. str = gb_string_append_rune(str, '(');
  10808. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  10809. str = gb_string_appendc(str, ") ");
  10810. }
  10811. switch (st->kind) {
  10812. case UnionType_no_nil: str = gb_string_appendc(str, "#no_nil "); break;
  10813. case UnionType_shared_nil: str = gb_string_appendc(str, "#shared_nil "); break;
  10814. }
  10815. if (st->align) {
  10816. str = gb_string_appendc(str, "#align ");
  10817. str = write_expr_to_string(str, st->align, shorthand);
  10818. str = gb_string_append_rune(str, ' ');
  10819. }
  10820. str = gb_string_append_rune(str, '{');
  10821. if (shorthand) {
  10822. str = gb_string_appendc(str, "...");
  10823. } else {
  10824. str = write_struct_fields_to_string(str, st->variants);
  10825. }
  10826. str = gb_string_append_rune(str, '}');
  10827. case_end;
  10828. case_ast_node(et, EnumType, node);
  10829. str = gb_string_appendc(str, "enum ");
  10830. if (et->base_type != nullptr) {
  10831. str = write_expr_to_string(str, et->base_type, shorthand);
  10832. str = gb_string_append_rune(str, ' ');
  10833. }
  10834. str = gb_string_append_rune(str, '{');
  10835. if (shorthand) {
  10836. str = gb_string_appendc(str, "...");
  10837. } else {
  10838. for_array(i, et->fields) {
  10839. if (i > 0) {
  10840. str = gb_string_appendc(str, ", ");
  10841. }
  10842. str = write_expr_to_string(str, et->fields[i], shorthand);
  10843. }
  10844. }
  10845. str = gb_string_append_rune(str, '}');
  10846. case_end;
  10847. case_ast_node(rt, RelativeType, node);
  10848. str = write_expr_to_string(str, rt->tag, shorthand);
  10849. str = gb_string_appendc(str, "" );
  10850. str = write_expr_to_string(str, rt->type, shorthand);
  10851. case_end;
  10852. case_ast_node(f, BitFieldField, node);
  10853. str = write_expr_to_string(str, f->name, shorthand);
  10854. str = gb_string_appendc(str, ": ");
  10855. str = write_expr_to_string(str, f->type, shorthand);
  10856. str = gb_string_appendc(str, " | ");
  10857. str = write_expr_to_string(str, f->bit_size, shorthand);
  10858. case_end;
  10859. case_ast_node(bf, BitFieldType, node);
  10860. str = gb_string_appendc(str, "bit_field ");
  10861. if (!shorthand) {
  10862. str = write_expr_to_string(str, bf->backing_type, shorthand);
  10863. }
  10864. str = gb_string_appendc(str, " {");
  10865. if (shorthand) {
  10866. str = gb_string_appendc(str, "...");
  10867. } else {
  10868. for_array(i, bf->fields) {
  10869. if (i > 0) {
  10870. str = gb_string_appendc(str, ", ");
  10871. }
  10872. str = write_expr_to_string(str, bf->fields[i], false);
  10873. }
  10874. }
  10875. str = gb_string_appendc(str, "}");
  10876. case_end;
  10877. case_ast_node(ia, InlineAsmExpr, node);
  10878. str = gb_string_appendc(str, "asm(");
  10879. for_array(i, ia->param_types) {
  10880. if (i > 0) {
  10881. str = gb_string_appendc(str, ", ");
  10882. }
  10883. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  10884. }
  10885. str = gb_string_appendc(str, ")");
  10886. if (ia->return_type != nullptr) {
  10887. str = gb_string_appendc(str, " -> ");
  10888. str = write_expr_to_string(str, ia->return_type, shorthand);
  10889. }
  10890. if (ia->has_side_effects) {
  10891. str = gb_string_appendc(str, " #side_effects");
  10892. }
  10893. if (ia->is_align_stack) {
  10894. str = gb_string_appendc(str, " #stack_align");
  10895. }
  10896. if (ia->dialect) {
  10897. str = gb_string_appendc(str, " #");
  10898. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  10899. }
  10900. str = gb_string_appendc(str, " {");
  10901. if (shorthand) {
  10902. str = gb_string_appendc(str, "...");
  10903. } else {
  10904. str = write_expr_to_string(str, ia->asm_string, shorthand);
  10905. str = gb_string_appendc(str, ", ");
  10906. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  10907. }
  10908. str = gb_string_appendc(str, "}");
  10909. case_end;
  10910. }
  10911. return str;
  10912. }
  10913. gb_internal gbString expr_to_string(Ast *expression) {
  10914. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  10915. }
  10916. gb_internal gbString expr_to_string(Ast *expression, gbAllocator allocator) {
  10917. return write_expr_to_string(gb_string_make(allocator, ""), expression, false);
  10918. }
  10919. gb_internal gbString expr_to_string_shorthand(Ast *expression) {
  10920. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  10921. }