check_expr.cpp 274 KB

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