check_expr.cpp 243 KB

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