check_expr.cpp 281 KB

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