check_expr.cpp 257 KB

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