check_expr.cpp 242 KB

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