check_expr.cpp 252 KB

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