check_expr.cpp 234 KB

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