check_expr.cpp 262 KB

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