check_expr.cpp 251 KB

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