check_expr.cpp 264 KB

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