check_expr.cpp 273 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679
  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. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5060. decl->where_clauses_evaluated = true;
  5061. }
  5062. return data;
  5063. }
  5064. } else {
  5065. Ast *ident = operand->expr;
  5066. while (ident->kind == Ast_SelectorExpr) {
  5067. Ast *s = ident->SelectorExpr.selector;
  5068. ident = s;
  5069. }
  5070. Entity *e = entity_of_node(ident);
  5071. CallArgumentData data = {};
  5072. CallArgumentError err = call_checker(c, call, proc_type, e, operands, CallArgumentMode_ShowErrors, &data);
  5073. gb_unused(err);
  5074. Entity *entity_to_use = data.gen_entity != nullptr ? data.gen_entity : e;
  5075. add_entity_use(c, ident, entity_to_use);
  5076. if (entity_to_use != nullptr) {
  5077. update_untyped_expr_type(c, operand->expr, entity_to_use->type, true);
  5078. }
  5079. if (data.gen_entity != nullptr) {
  5080. Entity *e = data.gen_entity;
  5081. DeclInfo *decl = data.gen_entity->decl_info;
  5082. CheckerContext ctx = *c;
  5083. ctx.scope = decl->scope;
  5084. ctx.decl = decl;
  5085. ctx.proc_name = e->token.string;
  5086. ctx.curr_proc_decl = decl;
  5087. ctx.curr_proc_sig = e->type;
  5088. GB_ASSERT(decl->proc_lit->kind == Ast_ProcLit);
  5089. evaluate_where_clauses(&ctx, call, decl->scope, &decl->proc_lit->ProcLit.where_clauses, true);
  5090. decl->where_clauses_evaluated = true;
  5091. }
  5092. return data;
  5093. }
  5094. CallArgumentData data = {};
  5095. data.result_type = t_invalid;
  5096. return data;
  5097. }
  5098. isize lookup_polymorphic_record_parameter(Type *t, String parameter_name) {
  5099. if (!is_type_polymorphic_record(t)) {
  5100. return -1;
  5101. }
  5102. TypeTuple *params = get_record_polymorphic_params(t);
  5103. if (params == nullptr) {
  5104. return -1;
  5105. }
  5106. for_array(i, params->variables) {
  5107. Entity *e = params->variables[i];
  5108. String name = e->token.string;
  5109. if (is_blank_ident(name)) {
  5110. continue;
  5111. }
  5112. if (name == parameter_name) {
  5113. return i;
  5114. }
  5115. }
  5116. return -1;
  5117. }
  5118. CallArgumentError check_polymorphic_record_type(CheckerContext *c, Operand *operand, Ast *call) {
  5119. ast_node(ce, CallExpr, call);
  5120. Type *original_type = operand->type;
  5121. GB_ASSERT(is_type_polymorphic_record(original_type));
  5122. bool show_error = true;
  5123. Array<Operand> operands = {};
  5124. defer (array_free(&operands));
  5125. bool named_fields = false;
  5126. {
  5127. // NOTE(bill, 2019-10-26): Allow a cycle in the parameters but not in the fields themselves
  5128. auto prev_type_path = c->type_path;
  5129. c->type_path = new_checker_type_path();
  5130. defer ({
  5131. destroy_checker_type_path(c->type_path);
  5132. c->type_path = prev_type_path;
  5133. });
  5134. if (is_call_expr_field_value(ce)) {
  5135. named_fields = true;
  5136. operands = array_make<Operand>(heap_allocator(), ce->args.count);
  5137. for_array(i, ce->args) {
  5138. Ast *arg = ce->args[i];
  5139. ast_node(fv, FieldValue, arg);
  5140. if (fv->field->kind == Ast_Ident) {
  5141. String name = fv->field->Ident.token.string;
  5142. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5143. if (index >= 0) {
  5144. TypeTuple *params = get_record_polymorphic_params(original_type);
  5145. Entity *e = params->variables[i];
  5146. if (e->kind == Entity_Constant) {
  5147. check_expr_with_type_hint(c, &operands[i], fv->value, e->type);
  5148. continue;
  5149. }
  5150. }
  5151. }
  5152. check_expr_or_type(c, &operands[i], fv->value);
  5153. }
  5154. bool vari_expand = (ce->ellipsis.pos.line != 0);
  5155. if (vari_expand) {
  5156. error(ce->ellipsis, "Invalid use of '..' in a polymorphic type call'");
  5157. }
  5158. } else {
  5159. operands = array_make<Operand>(heap_allocator(), 0, 2*ce->args.count);
  5160. Entity **lhs = nullptr;
  5161. isize lhs_count = -1;
  5162. TypeTuple *params = get_record_polymorphic_params(original_type);
  5163. if (params != nullptr) {
  5164. lhs = params->variables.data;
  5165. lhs_count = params->variables.count;
  5166. }
  5167. check_unpack_arguments(c, lhs, lhs_count, &operands, ce->args, false, false);
  5168. }
  5169. }
  5170. CallArgumentError err = CallArgumentError_None;
  5171. TypeTuple *tuple = get_record_polymorphic_params(original_type);
  5172. isize param_count = tuple->variables.count;
  5173. isize minimum_param_count = param_count;
  5174. for (; minimum_param_count > 0; minimum_param_count--) {
  5175. Entity *e = tuple->variables[minimum_param_count-1];
  5176. if (e->kind != Entity_Constant) {
  5177. break;
  5178. }
  5179. if (e->Constant.param_value.kind == ParameterValue_Invalid) {
  5180. break;
  5181. }
  5182. }
  5183. Array<Operand> ordered_operands = operands;
  5184. if (!named_fields) {
  5185. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5186. array_copy(&ordered_operands, operands, 0);
  5187. } else {
  5188. bool *visited = gb_alloc_array(temporary_allocator(), bool, param_count);
  5189. // LEAK(bill)
  5190. ordered_operands = array_make<Operand>(permanent_allocator(), param_count);
  5191. for_array(i, ce->args) {
  5192. Ast *arg = ce->args[i];
  5193. ast_node(fv, FieldValue, arg);
  5194. if (fv->field->kind != Ast_Ident) {
  5195. if (show_error) {
  5196. gbString expr_str = expr_to_string(fv->field);
  5197. error(arg, "Invalid parameter name '%s' in polymorphic type call", expr_str);
  5198. gb_string_free(expr_str);
  5199. }
  5200. err = CallArgumentError_InvalidFieldValue;
  5201. continue;
  5202. }
  5203. String name = fv->field->Ident.token.string;
  5204. isize index = lookup_polymorphic_record_parameter(original_type, name);
  5205. if (index < 0) {
  5206. if (show_error) {
  5207. error(arg, "No parameter named '%.*s' for this polymorphic type", LIT(name));
  5208. }
  5209. err = CallArgumentError_ParameterNotFound;
  5210. continue;
  5211. }
  5212. if (visited[index]) {
  5213. if (show_error) {
  5214. error(arg, "Duplicate parameter '%.*s' in polymorphic type", LIT(name));
  5215. }
  5216. err = CallArgumentError_DuplicateParameter;
  5217. continue;
  5218. }
  5219. visited[index] = true;
  5220. ordered_operands[index] = operands[i];
  5221. }
  5222. for (isize i = 0; i < param_count; i++) {
  5223. if (!visited[i]) {
  5224. Entity *e = tuple->variables[i];
  5225. if (is_blank_ident(e->token)) {
  5226. continue;
  5227. }
  5228. if (show_error) {
  5229. if (e->kind == Entity_TypeName) {
  5230. error(call, "Type parameter '%.*s' is missing in polymorphic type call",
  5231. LIT(e->token.string));
  5232. } else {
  5233. gbString str = type_to_string(e->type);
  5234. error(call, "Parameter '%.*s' of type '%s' is missing in polymorphic type call",
  5235. LIT(e->token.string), str);
  5236. gb_string_free(str);
  5237. }
  5238. }
  5239. err = CallArgumentError_ParameterMissing;
  5240. }
  5241. }
  5242. }
  5243. if (err != 0) {
  5244. operand->mode = Addressing_Invalid;
  5245. return err;
  5246. }
  5247. while (ordered_operands.count > 0) {
  5248. if (ordered_operands[ordered_operands.count-1].expr != nullptr) {
  5249. break;
  5250. }
  5251. array_pop(&ordered_operands);
  5252. }
  5253. if (minimum_param_count != param_count) {
  5254. if (param_count < ordered_operands.count) {
  5255. error(call, "Too many polymorphic type arguments, expected a maximum of %td, got %td", param_count, ordered_operands.count);
  5256. err = CallArgumentError_TooManyArguments;
  5257. } else if (minimum_param_count > ordered_operands.count) {
  5258. error(call, "Too few polymorphic type arguments, expected a minimum of %td, got %td", minimum_param_count, ordered_operands.count);
  5259. err = CallArgumentError_TooFewArguments;
  5260. }
  5261. } else {
  5262. if (param_count < ordered_operands.count) {
  5263. error(call, "Too many polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5264. err = CallArgumentError_TooManyArguments;
  5265. } else if (param_count > ordered_operands.count) {
  5266. error(call, "Too few polymorphic type arguments, expected %td, got %td", param_count, ordered_operands.count);
  5267. err = CallArgumentError_TooFewArguments;
  5268. }
  5269. }
  5270. if (err != 0) {
  5271. return err;
  5272. }
  5273. if (minimum_param_count != param_count) {
  5274. array_resize(&ordered_operands, param_count);
  5275. isize missing_count = 0;
  5276. // NOTE(bill): Replace missing operands with the default values (if possible)
  5277. for_array(i, ordered_operands) {
  5278. Operand *o = &ordered_operands[i];
  5279. if (o->expr == nullptr) {
  5280. Entity *e = tuple->variables[i];
  5281. if (e->kind == Entity_Constant) {
  5282. missing_count += 1;
  5283. o->mode = Addressing_Constant;
  5284. o->type = default_type(e->type);
  5285. o->expr = unparen_expr(e->Constant.param_value.original_ast_expr);
  5286. if (e->Constant.param_value.kind == ParameterValue_Constant) {
  5287. o->value = e->Constant.param_value.value;
  5288. }
  5289. } else if (e->kind == Entity_TypeName) {
  5290. missing_count += 1;
  5291. o->mode = Addressing_Type;
  5292. o->type = e->type;
  5293. o->expr = e->identifier;
  5294. }
  5295. }
  5296. }
  5297. }
  5298. isize oo_count = gb_min(param_count, ordered_operands.count);
  5299. i64 score = 0;
  5300. for (isize i = 0; i < oo_count; i++) {
  5301. Entity *e = tuple->variables[i];
  5302. Operand *o = &ordered_operands[i];
  5303. if (o->mode == Addressing_Invalid) {
  5304. continue;
  5305. }
  5306. if (e->kind == Entity_TypeName) {
  5307. if (o->mode != Addressing_Type) {
  5308. if (show_error) {
  5309. error(o->expr, "Expected a type for the argument '%.*s'", LIT(e->token.string));
  5310. }
  5311. err = CallArgumentError_WrongTypes;
  5312. }
  5313. if (are_types_identical(e->type, o->type)) {
  5314. score += assign_score_function(1);
  5315. } else {
  5316. score += assign_score_function(MAXIMUM_TYPE_DISTANCE);
  5317. }
  5318. } else {
  5319. i64 s = 0;
  5320. if (o->type->kind == Type_Generic) {
  5321. // Polymorphic name!
  5322. score += assign_score_function(1);
  5323. continue;
  5324. } else if (!check_is_assignable_to_with_score(c, o, e->type, &s)) {
  5325. if (show_error) {
  5326. check_assignment(c, o, e->type, str_lit("polymorphic type argument"));
  5327. }
  5328. err = CallArgumentError_WrongTypes;
  5329. }
  5330. o->type = e->type;
  5331. if (o->mode != Addressing_Constant) {
  5332. bool valid = false;
  5333. if (is_type_proc(o->type)) {
  5334. Entity *proc_entity = entity_from_expr(o->expr);
  5335. valid = proc_entity != nullptr;
  5336. }
  5337. if (!valid) {
  5338. if (show_error) {
  5339. error(o->expr, "Expected a constant value for this polymorphic type argument");
  5340. }
  5341. err = CallArgumentError_NoneConstantParameter;
  5342. }
  5343. }
  5344. score += s;
  5345. }
  5346. // NOTE(bill): Add type info the parameters
  5347. // TODO(bill, 2022-01-23): why was this line added in the first place? I'm commenting it out for the time being
  5348. // add_type_info_type(c, o->type);
  5349. }
  5350. {
  5351. bool failure = false;
  5352. Entity *found_entity = find_polymorphic_record_entity(c, original_type, param_count, ordered_operands, &failure);
  5353. if (found_entity) {
  5354. operand->mode = Addressing_Type;
  5355. operand->type = found_entity->type;
  5356. return err;
  5357. }
  5358. String generated_name = make_string_c(expr_to_string(call));
  5359. CheckerContext ctx = *c;
  5360. // NOTE(bill): We need to make sure the lookup scope for the record is the same as where it was created
  5361. ctx.scope = polymorphic_record_parent_scope(original_type);
  5362. GB_ASSERT(ctx.scope != nullptr);
  5363. Type *named_type = alloc_type_named(generated_name, nullptr, nullptr);
  5364. Type *bt = base_type(original_type);
  5365. if (bt->kind == Type_Struct) {
  5366. Ast *node = clone_ast(bt->Struct.node);
  5367. Type *struct_type = alloc_type_struct();
  5368. struct_type->Struct.node = node;
  5369. struct_type->Struct.polymorphic_parent = original_type;
  5370. set_base_type(named_type, struct_type);
  5371. check_open_scope(&ctx, node);
  5372. check_struct_type(&ctx, struct_type, node, &ordered_operands, named_type, original_type);
  5373. check_close_scope(&ctx);
  5374. } else if (bt->kind == Type_Union) {
  5375. Ast *node = clone_ast(bt->Union.node);
  5376. Type *union_type = alloc_type_union();
  5377. union_type->Union.node = node;
  5378. union_type->Union.polymorphic_parent = original_type;
  5379. set_base_type(named_type, union_type);
  5380. check_open_scope(&ctx, node);
  5381. check_union_type(&ctx, union_type, node, &ordered_operands, named_type, original_type);
  5382. check_close_scope(&ctx);
  5383. } else {
  5384. GB_PANIC("Unsupported parametric polymorphic record type");
  5385. }
  5386. operand->mode = Addressing_Type;
  5387. operand->type = named_type;
  5388. }
  5389. return err;
  5390. }
  5391. ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Ast *proc, Slice<Ast *> const &args, ProcInlining inlining, Type *type_hint) {
  5392. if (proc != nullptr &&
  5393. proc->kind == Ast_BasicDirective) {
  5394. ast_node(bd, BasicDirective, proc);
  5395. String name = bd->name.string;
  5396. if (
  5397. name == "location" ||
  5398. name == "assert" ||
  5399. name == "panic" ||
  5400. name == "defined" ||
  5401. name == "config" ||
  5402. name == "load" ||
  5403. name == "load_hash" ||
  5404. name == "load_or"
  5405. ) {
  5406. operand->mode = Addressing_Builtin;
  5407. operand->builtin_id = BuiltinProc_DIRECTIVE;
  5408. operand->expr = proc;
  5409. operand->type = t_invalid;
  5410. add_type_and_value(c->info, proc, operand->mode, operand->type, operand->value);
  5411. } else {
  5412. error(proc, "Unknown directive: #%.*s", LIT(name));
  5413. operand->expr = proc;
  5414. operand->type = t_invalid;
  5415. operand->mode = Addressing_Invalid;
  5416. return Expr_Expr;
  5417. }
  5418. if (inlining != ProcInlining_none) {
  5419. error(call, "Inlining operators are not allowed on built-in procedures");
  5420. }
  5421. } else {
  5422. if (proc != nullptr) {
  5423. check_expr_or_type(c, operand, proc);
  5424. } else {
  5425. GB_ASSERT(operand->expr != nullptr);
  5426. }
  5427. }
  5428. if (args.count > 0) {
  5429. bool fail = false;
  5430. bool first_is_field_value = (args[0]->kind == Ast_FieldValue);
  5431. for_array(i, args) {
  5432. Ast *arg = args[i];
  5433. bool mix = false;
  5434. if (first_is_field_value) {
  5435. mix = arg->kind != Ast_FieldValue;
  5436. } else {
  5437. mix = arg->kind == Ast_FieldValue;
  5438. }
  5439. if (mix) {
  5440. error(arg, "Mixture of 'field = value' and value elements in a procedure call is not allowed");
  5441. fail = true;
  5442. }
  5443. }
  5444. if (fail) {
  5445. operand->mode = Addressing_Invalid;
  5446. operand->expr = call;
  5447. return Expr_Stmt;
  5448. }
  5449. }
  5450. if (operand->mode == Addressing_Invalid) {
  5451. for_array(i, args) {
  5452. Ast *arg = args[i];
  5453. if (arg->kind == Ast_FieldValue) {
  5454. arg = arg->FieldValue.value;
  5455. }
  5456. check_expr_base(c, operand, arg, nullptr);
  5457. }
  5458. operand->mode = Addressing_Invalid;
  5459. operand->expr = call;
  5460. return Expr_Stmt;
  5461. }
  5462. if (operand->mode == Addressing_Type) {
  5463. Type *t = operand->type;
  5464. if (is_type_polymorphic_record(t)) {
  5465. if (!is_type_named(t)) {
  5466. gbString s = expr_to_string(operand->expr);
  5467. error(call, "Illegal use of an unnamed polymorphic record, %s", s);
  5468. gb_string_free(s);
  5469. operand->mode = Addressing_Invalid;
  5470. operand->type = t_invalid;;
  5471. return Expr_Expr;
  5472. }
  5473. auto err = check_polymorphic_record_type(c, operand, call);
  5474. if (err == 0) {
  5475. Ast *ident = operand->expr;
  5476. while (ident->kind == Ast_SelectorExpr) {
  5477. Ast *s = ident->SelectorExpr.selector;
  5478. ident = s;
  5479. }
  5480. Type *ot = operand->type;
  5481. GB_ASSERT(ot->kind == Type_Named);
  5482. Entity *e = ot->Named.type_name;
  5483. add_entity_use(c, ident, e);
  5484. add_type_and_value(c->info, call, Addressing_Type, ot, empty_exact_value);
  5485. } else {
  5486. operand->mode = Addressing_Invalid;
  5487. operand->type = t_invalid;
  5488. }
  5489. } else {
  5490. gbString str = type_to_string(t);
  5491. defer (gb_string_free(str));
  5492. operand->mode = Addressing_Invalid;
  5493. isize arg_count = args.count;
  5494. switch (arg_count) {
  5495. case 0: error(call, "Missing argument in conversion to '%s'", str); break;
  5496. default: error(call, "Too many arguments in conversion to '%s'", str); break;
  5497. case 1: {
  5498. Ast *arg = args[0];
  5499. if (arg->kind == Ast_FieldValue) {
  5500. error(call, "'field = value' cannot be used in a type conversion");
  5501. arg = arg->FieldValue.value;
  5502. // NOTE(bill): Carry on the cast regardless
  5503. }
  5504. check_expr_with_type_hint(c, operand, arg, t);
  5505. if (operand->mode != Addressing_Invalid) {
  5506. if (is_type_polymorphic(t)) {
  5507. error(call, "A polymorphic type cannot be used in a type conversion");
  5508. } else {
  5509. // NOTE(bill): Otherwise the compiler can override the polymorphic type
  5510. // as it assumes it is determining the type
  5511. check_cast(c, operand, t);
  5512. }
  5513. }
  5514. operand->type = t;
  5515. operand->expr = call;
  5516. if (operand->mode != Addressing_Invalid) {
  5517. update_untyped_expr_type(c, arg, t, false);
  5518. }
  5519. break;
  5520. }
  5521. }
  5522. }
  5523. return Expr_Expr;
  5524. }
  5525. if (operand->mode == Addressing_Builtin) {
  5526. i32 id = operand->builtin_id;
  5527. if (!check_builtin_procedure(c, operand, call, id, type_hint)) {
  5528. operand->mode = Addressing_Invalid;
  5529. operand->type = t_invalid;
  5530. }
  5531. operand->expr = call;
  5532. return builtin_procs[id].kind;
  5533. }
  5534. Entity *e = entity_of_node(operand->expr);
  5535. if (e != nullptr && e->kind == Entity_Procedure) {
  5536. if (e->Procedure.deferred_procedure.entity != nullptr) {
  5537. call->viral_state_flags |= ViralStateFlag_ContainsDeferredProcedure;
  5538. }
  5539. }
  5540. Type *proc_type = base_type(operand->type);
  5541. if (operand->mode != Addressing_ProcGroup) {
  5542. bool valid_type = (proc_type != nullptr) && is_type_proc(proc_type);
  5543. bool valid_mode = is_operand_value(*operand);
  5544. if (!valid_type || !valid_mode) {
  5545. Ast *e = operand->expr;
  5546. gbString str = expr_to_string(e);
  5547. gbString type_str = type_to_string(operand->type);
  5548. error(e, "Cannot call a non-procedure: '%s' of type '%s'", str, type_str);
  5549. gb_string_free(type_str);
  5550. gb_string_free(str);
  5551. operand->mode = Addressing_Invalid;
  5552. operand->expr = call;
  5553. return Expr_Stmt;
  5554. }
  5555. }
  5556. CallArgumentData data = check_call_arguments(c, operand, proc_type, call, args);
  5557. Type *result_type = data.result_type;
  5558. gb_zero_item(operand);
  5559. operand->expr = call;
  5560. if (result_type == t_invalid) {
  5561. operand->mode = Addressing_Invalid;
  5562. operand->type = t_invalid;
  5563. return Expr_Stmt;
  5564. }
  5565. Type *pt = base_type(proc_type);
  5566. if (pt == t_invalid) {
  5567. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5568. pt = type_of_expr(operand->expr->CallExpr.proc);
  5569. }
  5570. if (pt == t_invalid && data.gen_entity) {
  5571. pt = data.gen_entity->type;
  5572. }
  5573. }
  5574. if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) {
  5575. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  5576. error(call, "'context' has not been defined within this scope, but is required for this procedure call");
  5577. }
  5578. }
  5579. if (result_type == nullptr) {
  5580. operand->mode = Addressing_NoValue;
  5581. } else {
  5582. GB_ASSERT(is_type_tuple(result_type));
  5583. isize count = result_type->Tuple.variables.count;
  5584. switch (count) {
  5585. case 0:
  5586. operand->mode = Addressing_NoValue;
  5587. break;
  5588. case 1:
  5589. operand->mode = Addressing_Value;
  5590. operand->type = result_type->Tuple.variables[0]->type;
  5591. break;
  5592. default:
  5593. operand->mode = Addressing_Value;
  5594. operand->type = result_type;
  5595. break;
  5596. }
  5597. }
  5598. switch (inlining) {
  5599. case ProcInlining_inline:
  5600. if (proc != nullptr) {
  5601. Entity *e = entity_from_expr(proc);
  5602. if (e != nullptr && e->kind == Entity_Procedure) {
  5603. DeclInfo *decl = e->decl_info;
  5604. if (decl->proc_lit) {
  5605. ast_node(pl, ProcLit, decl->proc_lit);
  5606. if (pl->inlining == ProcInlining_no_inline) {
  5607. error(call, "'inline' cannot be applied to a procedure that has be marked as 'no_inline'");
  5608. }
  5609. }
  5610. }
  5611. }
  5612. break;
  5613. case ProcInlining_no_inline:
  5614. break;
  5615. }
  5616. operand->expr = call;
  5617. {
  5618. if (proc_type == t_invalid) {
  5619. // gb_printf_err("%s\n", expr_to_string(operand->expr));
  5620. }
  5621. Type *type = nullptr;
  5622. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5623. type = type_of_expr(operand->expr->CallExpr.proc);
  5624. }
  5625. if (type == nullptr) {
  5626. type = pt;
  5627. }
  5628. type = base_type(type);
  5629. if (type->kind == Type_Proc && type->Proc.optional_ok) {
  5630. operand->mode = Addressing_OptionalOk;
  5631. operand->type = type->Proc.results->Tuple.variables[0]->type;
  5632. if (operand->expr != nullptr && operand->expr->kind == Ast_CallExpr) {
  5633. operand->expr->CallExpr.optional_ok_one = true;
  5634. }
  5635. }
  5636. }
  5637. // add_type_and_value(c->info, operand->expr, operand->mode, operand->type, operand->value);
  5638. return Expr_Expr;
  5639. }
  5640. void check_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *t) {
  5641. check_expr_base(c, o, e, t);
  5642. check_not_tuple(c, o);
  5643. char const *err_str = nullptr;
  5644. switch (o->mode) {
  5645. case Addressing_NoValue:
  5646. err_str = "used as a value";
  5647. break;
  5648. case Addressing_Type:
  5649. if (t == nullptr || !is_type_typeid(t)) {
  5650. err_str = "is not an expression but a type, in this context it is ambiguous";
  5651. }
  5652. break;
  5653. case Addressing_Builtin:
  5654. err_str = "must be called";
  5655. break;
  5656. }
  5657. if (err_str != nullptr) {
  5658. gbString str = expr_to_string(e);
  5659. error(e, "'%s' %s", str, err_str);
  5660. gb_string_free(str);
  5661. o->mode = Addressing_Invalid;
  5662. }
  5663. }
  5664. bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, Type *original_type) {
  5665. switch (t->kind) {
  5666. case Type_Basic:
  5667. if (t->Basic.kind == Basic_string) {
  5668. if (o->mode == Addressing_Constant) {
  5669. *max_count = o->value.value_string.len;
  5670. }
  5671. if (o->mode != Addressing_Constant) {
  5672. o->mode = Addressing_Value;
  5673. }
  5674. o->type = t_u8;
  5675. return true;
  5676. } else if (t->Basic.kind == Basic_UntypedString) {
  5677. if (o->mode == Addressing_Constant) {
  5678. *max_count = o->value.value_string.len;
  5679. o->type = t_u8;
  5680. return true;
  5681. }
  5682. return false;
  5683. }
  5684. break;
  5685. case Type_MultiPointer:
  5686. o->type = t->MultiPointer.elem;
  5687. if (o->mode != Addressing_Constant) {
  5688. o->mode = Addressing_Variable;
  5689. }
  5690. return true;
  5691. case Type_Array:
  5692. *max_count = t->Array.count;
  5693. if (indirection) {
  5694. o->mode = Addressing_Variable;
  5695. } else if (o->mode != Addressing_Variable &&
  5696. o->mode != Addressing_Constant) {
  5697. o->mode = Addressing_Value;
  5698. }
  5699. o->type = t->Array.elem;
  5700. return true;
  5701. case Type_EnumeratedArray:
  5702. *max_count = t->EnumeratedArray.count;
  5703. if (indirection) {
  5704. o->mode = Addressing_Variable;
  5705. } else if (o->mode != Addressing_Variable &&
  5706. o->mode != Addressing_Constant) {
  5707. o->mode = Addressing_Value;
  5708. }
  5709. o->type = t->EnumeratedArray.elem;
  5710. return true;
  5711. case Type_Matrix:
  5712. *max_count = t->Matrix.column_count;
  5713. if (indirection) {
  5714. o->mode = Addressing_Variable;
  5715. } else if (o->mode != Addressing_Variable) {
  5716. o->mode = Addressing_Value;
  5717. }
  5718. o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count);
  5719. return true;
  5720. case Type_Slice:
  5721. o->type = t->Slice.elem;
  5722. if (o->mode != Addressing_Constant) {
  5723. o->mode = Addressing_Variable;
  5724. }
  5725. return true;
  5726. case Type_RelativeSlice:
  5727. {
  5728. Type *slice_type = base_type(t->RelativeSlice.slice_type);
  5729. GB_ASSERT(slice_type->kind == Type_Slice);
  5730. o->type = slice_type->Slice.elem;
  5731. if (o->mode != Addressing_Constant) {
  5732. o->mode = Addressing_Variable;
  5733. }
  5734. }
  5735. return true;
  5736. case Type_DynamicArray:
  5737. o->type = t->DynamicArray.elem;
  5738. if (o->mode != Addressing_Constant) {
  5739. o->mode = Addressing_Variable;
  5740. }
  5741. return true;
  5742. case Type_Struct:
  5743. if (t->Struct.soa_kind != StructSoa_None) {
  5744. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5745. *max_count = t->Struct.soa_count;
  5746. }
  5747. o->type = t->Struct.soa_elem;
  5748. if (o->mode == Addressing_SoaVariable || o->mode == Addressing_Variable) {
  5749. o->mode = Addressing_SoaVariable;
  5750. } else {
  5751. o->mode = Addressing_Value;
  5752. }
  5753. return true;
  5754. }
  5755. return false;
  5756. }
  5757. if (is_type_pointer(original_type) && indirection) {
  5758. Type *ptr = base_type(original_type);
  5759. if (ptr->kind == Type_Pointer && o->mode == Addressing_SoaVariable) {
  5760. o->type = ptr->Pointer.elem;
  5761. o->mode = Addressing_Value;
  5762. return true;
  5763. }
  5764. }
  5765. return false;
  5766. }
  5767. bool ternary_compare_types(Type *x, Type *y) {
  5768. if (is_type_untyped_undef(x) && type_has_undef(y)) {
  5769. return true;
  5770. } else if (is_type_untyped_nil(x) && type_has_nil(y)) {
  5771. return true;
  5772. } else if (is_type_untyped_undef(y) && type_has_undef(x)) {
  5773. return true;
  5774. } else if (is_type_untyped_nil(y) && type_has_nil(x)) {
  5775. return true;
  5776. }
  5777. return are_types_identical(x, y);
  5778. }
  5779. bool check_range(CheckerContext *c, Ast *node, Operand *x, Operand *y, ExactValue *inline_for_depth_, Type *type_hint=nullptr) {
  5780. if (!is_ast_range(node)) {
  5781. return false;
  5782. }
  5783. ast_node(ie, BinaryExpr, node);
  5784. check_expr_with_type_hint(c, x, ie->left, type_hint);
  5785. if (x->mode == Addressing_Invalid) {
  5786. return false;
  5787. }
  5788. check_expr_with_type_hint(c, y, ie->right, type_hint);
  5789. if (y->mode == Addressing_Invalid) {
  5790. return false;
  5791. }
  5792. convert_to_typed(c, x, y->type);
  5793. if (x->mode == Addressing_Invalid) {
  5794. return false;
  5795. }
  5796. convert_to_typed(c, y, x->type);
  5797. if (y->mode == Addressing_Invalid) {
  5798. return false;
  5799. }
  5800. convert_to_typed(c, x, default_type(y->type));
  5801. if (x->mode == Addressing_Invalid) {
  5802. return false;
  5803. }
  5804. convert_to_typed(c, y, default_type(x->type));
  5805. if (y->mode == Addressing_Invalid) {
  5806. return false;
  5807. }
  5808. if (!are_types_identical(x->type, y->type)) {
  5809. if (x->type != t_invalid &&
  5810. y->type != t_invalid) {
  5811. gbString xt = type_to_string(x->type);
  5812. gbString yt = type_to_string(y->type);
  5813. gbString expr_str = expr_to_string(x->expr);
  5814. error(ie->op, "Mismatched types in interval expression '%s' : '%s' vs '%s'", expr_str, xt, yt);
  5815. gb_string_free(expr_str);
  5816. gb_string_free(yt);
  5817. gb_string_free(xt);
  5818. }
  5819. return false;
  5820. }
  5821. Type *type = x->type;
  5822. if (!is_type_integer(type) && !is_type_float(type) && !is_type_pointer(type) && !is_type_enum(type)) {
  5823. error(ie->op, "Only numerical and pointer types are allowed within interval expressions");
  5824. return false;
  5825. }
  5826. if (x->mode == Addressing_Constant &&
  5827. y->mode == Addressing_Constant) {
  5828. ExactValue a = x->value;
  5829. ExactValue b = y->value;
  5830. GB_ASSERT(are_types_identical(x->type, y->type));
  5831. TokenKind op = Token_Lt;
  5832. switch (ie->op.kind) {
  5833. case Token_Ellipsis: op = Token_LtEq; break; // ..
  5834. case Token_RangeFull: op = Token_LtEq; break; // ..=
  5835. case Token_RangeHalf: op = Token_Lt; break; // ..<
  5836. default: error(ie->op, "Invalid range operator"); break;
  5837. }
  5838. bool ok = compare_exact_values(op, a, b);
  5839. if (!ok) {
  5840. // TODO(bill): Better error message
  5841. error(ie->op, "Invalid interval range");
  5842. return false;
  5843. }
  5844. ExactValue inline_for_depth = exact_value_sub(b, a);
  5845. if (ie->op.kind != Token_RangeHalf) {
  5846. inline_for_depth = exact_value_increment_one(inline_for_depth);
  5847. }
  5848. if (inline_for_depth_) *inline_for_depth_ = inline_for_depth;
  5849. } else if (inline_for_depth_ != nullptr) {
  5850. error(ie->op, "Interval expressions must be constant");
  5851. return false;
  5852. }
  5853. add_type_and_value(c->info, ie->left, x->mode, x->type, x->value);
  5854. add_type_and_value(c->info, ie->right, y->mode, y->type, y->value);
  5855. return true;
  5856. }
  5857. bool check_is_operand_compound_lit_constant(CheckerContext *c, Operand *o) {
  5858. if (is_operand_nil(*o)) {
  5859. return true;
  5860. }
  5861. Ast *expr = unparen_expr(o->expr);
  5862. if (expr != nullptr) {
  5863. Entity *e = strip_entity_wrapping(entity_from_expr(expr));
  5864. if (e != nullptr && e->kind == Entity_Procedure) {
  5865. return true;
  5866. }
  5867. if (expr->kind == Ast_ProcLit) {
  5868. add_type_and_value(c->info, expr, Addressing_Constant, type_of_expr(expr), exact_value_procedure(expr));
  5869. return true;
  5870. }
  5871. }
  5872. return o->mode == Addressing_Constant;
  5873. }
  5874. bool attempt_implicit_selector_expr(CheckerContext *c, Operand *o, AstImplicitSelectorExpr *ise, Type *th) {
  5875. if (is_type_enum(th)) {
  5876. Type *enum_type = base_type(th);
  5877. GB_ASSERT(enum_type->kind == Type_Enum);
  5878. String name = ise->selector->Ident.token.string;
  5879. Entity *e = scope_lookup_current(enum_type->Enum.scope, name);
  5880. if (e == nullptr) {
  5881. return false;
  5882. }
  5883. GB_ASSERT(are_types_identical(base_type(e->type), enum_type));
  5884. GB_ASSERT(e->kind == Entity_Constant);
  5885. o->value = e->Constant.value;
  5886. o->mode = Addressing_Constant;
  5887. o->type = e->type;
  5888. return true;
  5889. }
  5890. if (is_type_union(th)) {
  5891. Type *union_type = base_type(th);
  5892. auto operands = array_make<Operand>(temporary_allocator(), 0, union_type->Union.variants.count);
  5893. for_array(i, union_type->Union.variants) {
  5894. Type *vt = union_type->Union.variants[i];
  5895. Operand x = {};
  5896. if (attempt_implicit_selector_expr(c, &x, ise, vt)) {
  5897. array_add(&operands, x);
  5898. }
  5899. }
  5900. if (operands.count == 1) {
  5901. *o = operands[0];
  5902. return true;
  5903. }
  5904. }
  5905. return false;
  5906. }
  5907. ExprKind check_implicit_selector_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5908. ast_node(ise, ImplicitSelectorExpr, node);
  5909. o->type = t_invalid;
  5910. o->expr = node;
  5911. o->mode = Addressing_Invalid;
  5912. Type *th = type_hint;
  5913. if (th == nullptr) {
  5914. gbString str = expr_to_string(node);
  5915. error(node, "Cannot determine type for implicit selector expression '%s'", str);
  5916. gb_string_free(str);
  5917. return Expr_Expr;
  5918. }
  5919. o->type = th;
  5920. bool ok = attempt_implicit_selector_expr(c, o, ise, th);
  5921. if (!ok) {
  5922. String name = ise->selector->Ident.token.string;
  5923. if (is_type_enum(th)) {
  5924. Type *bt = base_type(th);
  5925. GB_ASSERT(bt->kind == Type_Enum);
  5926. gbString typ = type_to_string(th);
  5927. defer (gb_string_free(typ));
  5928. error(node, "Undeclared name '%.*s' for type '%s'", LIT(name), typ);
  5929. check_did_you_mean_type(name, bt->Enum.fields);
  5930. } else {
  5931. gbString typ = type_to_string(th);
  5932. gbString str = expr_to_string(node);
  5933. error(node, "Invalid type '%s' for implicit selector expression '%s'", typ, str);
  5934. gb_string_free(str);
  5935. gb_string_free(typ);
  5936. }
  5937. }
  5938. o->expr = node;
  5939. return Expr_Expr;
  5940. }
  5941. void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, Type **ok_type_) {
  5942. switch (x->mode) {
  5943. case Addressing_MapIndex:
  5944. case Addressing_OptionalOk:
  5945. case Addressing_OptionalOkPtr:
  5946. if (val_type_) *val_type_ = x->type;
  5947. break;
  5948. default:
  5949. if (ok_type_) *ok_type_ = x->type;
  5950. return;
  5951. }
  5952. Ast *expr = unparen_expr(x->expr);
  5953. if (expr->kind == Ast_CallExpr) {
  5954. Type *pt = base_type(type_of_expr(expr->CallExpr.proc));
  5955. if (is_type_proc(pt)) {
  5956. Type *tuple = pt->Proc.results;
  5957. add_type_and_value(c->info, x->expr, x->mode, tuple, x->value);
  5958. if (pt->Proc.result_count >= 2) {
  5959. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  5960. }
  5961. expr->CallExpr.optional_ok_one = false;
  5962. x->type = tuple;
  5963. return;
  5964. }
  5965. }
  5966. Type *tuple = make_optional_ok_type(x->type);
  5967. if (ok_type_) *ok_type_ = tuple->Tuple.variables[1]->type;
  5968. add_type_and_value(c->info, x->expr, x->mode, tuple, x->value);
  5969. x->type = tuple;
  5970. GB_ASSERT(is_type_tuple(type_of_expr(x->expr)));
  5971. }
  5972. void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  5973. ast_node(ie, MatrixIndexExpr, node);
  5974. check_expr(c, o, ie->expr);
  5975. node->viral_state_flags |= ie->expr->viral_state_flags;
  5976. if (o->mode == Addressing_Invalid) {
  5977. o->expr = node;
  5978. return;
  5979. }
  5980. Type *t = base_type(type_deref(o->type));
  5981. bool is_ptr = is_type_pointer(o->type);
  5982. bool is_const = o->mode == Addressing_Constant;
  5983. if (t->kind != Type_Matrix) {
  5984. gbString str = expr_to_string(o->expr);
  5985. gbString type_str = type_to_string(o->type);
  5986. defer (gb_string_free(str));
  5987. defer (gb_string_free(type_str));
  5988. if (is_const) {
  5989. error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str);
  5990. } else {
  5991. error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str);
  5992. }
  5993. o->mode = Addressing_Invalid;
  5994. o->expr = node;
  5995. return;
  5996. }
  5997. o->type = t->Matrix.elem;
  5998. if (is_ptr) {
  5999. o->mode = Addressing_Variable;
  6000. } else if (o->mode != Addressing_Variable) {
  6001. o->mode = Addressing_Value;
  6002. }
  6003. if (ie->row_index == nullptr) {
  6004. gbString str = expr_to_string(o->expr);
  6005. error(o->expr, "Missing row index for '%s'", str);
  6006. gb_string_free(str);
  6007. o->mode = Addressing_Invalid;
  6008. o->expr = node;
  6009. return;
  6010. }
  6011. if (ie->column_index == nullptr) {
  6012. gbString str = expr_to_string(o->expr);
  6013. error(o->expr, "Missing column index for '%s'", str);
  6014. gb_string_free(str);
  6015. o->mode = Addressing_Invalid;
  6016. o->expr = node;
  6017. return;
  6018. }
  6019. i64 row_count = t->Matrix.row_count;
  6020. i64 column_count = t->Matrix.column_count;
  6021. i64 row_index = 0;
  6022. i64 column_index = 0;
  6023. bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr);
  6024. bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr);
  6025. gb_unused(row_ok);
  6026. gb_unused(column_ok);
  6027. }
  6028. ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  6029. u32 prev_state_flags = c->state_flags;
  6030. defer (c->state_flags = prev_state_flags);
  6031. if (node->state_flags != 0) {
  6032. u32 in = node->state_flags;
  6033. u32 out = c->state_flags;
  6034. if (in & StateFlag_no_bounds_check) {
  6035. out |= StateFlag_no_bounds_check;
  6036. out &= ~StateFlag_bounds_check;
  6037. } else if (in & StateFlag_bounds_check) {
  6038. out |= StateFlag_bounds_check;
  6039. out &= ~StateFlag_no_bounds_check;
  6040. }
  6041. c->state_flags = out;
  6042. }
  6043. ExprKind kind = Expr_Stmt;
  6044. o->mode = Addressing_Invalid;
  6045. o->type = t_invalid;
  6046. switch (node->kind) {
  6047. default:
  6048. return kind;
  6049. case_ast_node(be, BadExpr, node)
  6050. return kind;
  6051. case_end;
  6052. case_ast_node(i, Implicit, node)
  6053. switch (i->kind) {
  6054. case Token_context:
  6055. {
  6056. if (c->proc_name.len == 0 && c->curr_proc_sig == nullptr) {
  6057. error(node, "'context' is only allowed within procedures %p", c->curr_proc_decl);
  6058. return kind;
  6059. }
  6060. if (unparen_expr(c->assignment_lhs_hint) == node) {
  6061. c->scope->flags |= ScopeFlag_ContextDefined;
  6062. }
  6063. if ((c->scope->flags & ScopeFlag_ContextDefined) == 0) {
  6064. error(node, "'context' has not been defined within this scope");
  6065. // Continue with value
  6066. }
  6067. init_core_context(c->checker);
  6068. o->mode = Addressing_Context;
  6069. o->type = t_context;
  6070. }
  6071. break;
  6072. default:
  6073. error(node, "Illegal implicit name '%.*s'", LIT(i->string));
  6074. return kind;
  6075. }
  6076. case_end;
  6077. case_ast_node(i, Ident, node);
  6078. check_ident(c, o, node, nullptr, type_hint, false);
  6079. case_end;
  6080. case_ast_node(u, Undef, node);
  6081. o->mode = Addressing_Value;
  6082. o->type = t_untyped_undef;
  6083. case_end;
  6084. case_ast_node(bl, BasicLit, node);
  6085. Type *t = t_invalid;
  6086. switch (node->tav.value.kind) {
  6087. case ExactValue_String: t = t_untyped_string; break;
  6088. case ExactValue_Float: t = t_untyped_float; break;
  6089. case ExactValue_Complex: t = t_untyped_complex; break;
  6090. case ExactValue_Quaternion: t = t_untyped_quaternion; break;
  6091. case ExactValue_Integer:
  6092. t = t_untyped_integer;
  6093. if (bl->token.kind == Token_Rune) {
  6094. t = t_untyped_rune;
  6095. }
  6096. break;
  6097. default:
  6098. GB_PANIC("Unhandled value type for basic literal");
  6099. break;
  6100. }
  6101. o->mode = Addressing_Constant;
  6102. o->type = t;
  6103. o->value = node->tav.value;
  6104. case_end;
  6105. case_ast_node(bd, BasicDirective, node);
  6106. o->mode = Addressing_Constant;
  6107. String name = bd->name.string;
  6108. if (name == "file") {
  6109. o->type = t_untyped_string;
  6110. o->value = exact_value_string(get_file_path_string(bd->token.pos.file_id));
  6111. } else if (name == "line") {
  6112. o->type = t_untyped_integer;
  6113. o->value = exact_value_i64(bd->token.pos.line);
  6114. } else if (name == "procedure") {
  6115. if (c->curr_proc_decl == nullptr) {
  6116. error(node, "#procedure may only be used within procedures");
  6117. o->type = t_untyped_string;
  6118. o->value = exact_value_string(str_lit(""));
  6119. } else {
  6120. o->type = t_untyped_string;
  6121. o->value = exact_value_string(c->proc_name);
  6122. }
  6123. } else if (name == "caller_location") {
  6124. init_core_source_code_location(c->checker);
  6125. error(node, "#caller_location may only be used as a default argument parameter");
  6126. o->type = t_source_code_location;
  6127. o->mode = Addressing_Value;
  6128. } else {
  6129. if (name == "location") {
  6130. init_core_source_code_location(c->checker);
  6131. error(node, "'#%.*s' must be used in a call expression", LIT(name));
  6132. o->type = t_source_code_location;
  6133. o->mode = Addressing_Value;
  6134. } else if (
  6135. name == "assert" ||
  6136. name == "defined" ||
  6137. name == "config" ||
  6138. name == "load" ||
  6139. name == "load_hash" ||
  6140. name == "load_or"
  6141. ) {
  6142. error(node, "'#%.*s' must be used as a call", LIT(name));
  6143. o->type = t_invalid;
  6144. o->mode = Addressing_Invalid;
  6145. } else {
  6146. error(node, "Unknown directive: #%.*s", LIT(name));
  6147. o->type = t_invalid;
  6148. o->mode = Addressing_Invalid;
  6149. }
  6150. }
  6151. case_end;
  6152. case_ast_node(pg, ProcGroup, node);
  6153. error(node, "Illegal use of a procedure group");
  6154. o->mode = Addressing_Invalid;
  6155. case_end;
  6156. case_ast_node(pl, ProcLit, node);
  6157. CheckerContext ctx = *c;
  6158. DeclInfo *decl = nullptr;
  6159. Type *type = alloc_type(Type_Proc);
  6160. check_open_scope(&ctx, pl->type);
  6161. {
  6162. decl = make_decl_info(ctx.scope, ctx.decl);
  6163. decl->proc_lit = node;
  6164. ctx.decl = decl;
  6165. defer (ctx.decl = ctx.decl->parent);
  6166. if (pl->tags != 0) {
  6167. error(node, "A procedure literal cannot have tags");
  6168. pl->tags = 0; // TODO(bill): Should I zero this?!
  6169. }
  6170. check_procedure_type(&ctx, type, pl->type);
  6171. if (!is_type_proc(type)) {
  6172. gbString str = expr_to_string(node);
  6173. error(node, "Invalid procedure literal '%s'", str);
  6174. gb_string_free(str);
  6175. check_close_scope(&ctx);
  6176. return kind;
  6177. }
  6178. if (pl->body == nullptr) {
  6179. error(node, "A procedure literal must have a body");
  6180. return kind;
  6181. }
  6182. pl->decl = decl;
  6183. check_procedure_later(&ctx, ctx.file, empty_token, decl, type, pl->body, pl->tags);
  6184. }
  6185. check_close_scope(&ctx);
  6186. o->mode = Addressing_Value;
  6187. o->type = type;
  6188. case_end;
  6189. case_ast_node(te, TernaryIfExpr, node);
  6190. Operand cond = {Addressing_Invalid};
  6191. check_expr(c, &cond, te->cond);
  6192. node->viral_state_flags |= te->cond->viral_state_flags;
  6193. if (cond.mode != Addressing_Invalid && !is_type_boolean(cond.type)) {
  6194. error(te->cond, "Non-boolean condition in ternary if expression");
  6195. }
  6196. Operand x = {Addressing_Invalid};
  6197. Operand y = {Addressing_Invalid};
  6198. check_expr_or_type(c, &x, te->x, type_hint);
  6199. node->viral_state_flags |= te->x->viral_state_flags;
  6200. if (te->y != nullptr) {
  6201. check_expr_or_type(c, &y, te->y, type_hint);
  6202. node->viral_state_flags |= te->y->viral_state_flags;
  6203. } else {
  6204. error(node, "A ternary expression must have an else clause");
  6205. return kind;
  6206. }
  6207. if (x.type == nullptr || x.type == t_invalid ||
  6208. y.type == nullptr || y.type == t_invalid) {
  6209. return kind;
  6210. }
  6211. convert_to_typed(c, &x, y.type);
  6212. if (x.mode == Addressing_Invalid) {
  6213. return kind;
  6214. }
  6215. convert_to_typed(c, &y, x.type);
  6216. if (y.mode == Addressing_Invalid) {
  6217. x.mode = Addressing_Invalid;
  6218. return kind;
  6219. }
  6220. if (!ternary_compare_types(x.type, y.type)) {
  6221. gbString its = type_to_string(x.type);
  6222. gbString ets = type_to_string(y.type);
  6223. error(node, "Mismatched types in ternary if expression, %s vs %s", its, ets);
  6224. gb_string_free(ets);
  6225. gb_string_free(its);
  6226. return kind;
  6227. }
  6228. o->type = x.type;
  6229. if (is_type_untyped_nil(o->type) || is_type_untyped_undef(o->type)) {
  6230. o->type = y.type;
  6231. }
  6232. o->mode = Addressing_Value;
  6233. o->expr = node;
  6234. if (type_hint != nullptr && is_type_untyped(o->type)) {
  6235. if (check_cast_internal(c, &x, type_hint) &&
  6236. check_cast_internal(c, &y, type_hint)) {
  6237. convert_to_typed(c, o, type_hint);
  6238. update_untyped_expr_type(c, node, type_hint, !is_type_untyped(type_hint));
  6239. }
  6240. }
  6241. case_end;
  6242. case_ast_node(te, TernaryWhenExpr, node);
  6243. Operand cond = {};
  6244. check_expr(c, &cond, te->cond);
  6245. node->viral_state_flags |= te->cond->viral_state_flags;
  6246. if (cond.mode != Addressing_Constant || !is_type_boolean(cond.type)) {
  6247. error(te->cond, "Expected a constant boolean condition in ternary when expression");
  6248. return kind;
  6249. }
  6250. if (cond.value.value_bool) {
  6251. check_expr_or_type(c, o, te->x, type_hint);
  6252. node->viral_state_flags |= te->x->viral_state_flags;
  6253. } else {
  6254. if (te->y != nullptr) {
  6255. check_expr_or_type(c, o, te->y, type_hint);
  6256. node->viral_state_flags |= te->y->viral_state_flags;
  6257. } else {
  6258. error(node, "A ternary when expression must have an else clause");
  6259. return kind;
  6260. }
  6261. }
  6262. case_end;
  6263. case_ast_node(oe, OrElseExpr, node);
  6264. String name = oe->token.string;
  6265. Ast *arg = oe->x;
  6266. Ast *default_value = oe->y;
  6267. Operand x = {};
  6268. Operand y = {};
  6269. check_multi_expr_with_type_hint(c, &x, arg, type_hint);
  6270. if (x.mode == Addressing_Invalid) {
  6271. o->mode = Addressing_Value;
  6272. o->type = t_invalid;
  6273. o->expr = node;
  6274. return Expr_Expr;
  6275. }
  6276. check_multi_expr_with_type_hint(c, &y, default_value, x.type);
  6277. error_operand_no_value(&y);
  6278. if (y.mode == Addressing_Invalid) {
  6279. o->mode = Addressing_Value;
  6280. o->type = t_invalid;
  6281. o->expr = node;
  6282. return Expr_Expr;
  6283. }
  6284. Type *left_type = nullptr;
  6285. Type *right_type = nullptr;
  6286. check_or_else_split_types(c, &x, name, &left_type, &right_type);
  6287. add_type_and_value(&c->checker->info, arg, x.mode, x.type, x.value);
  6288. if (left_type != nullptr) {
  6289. check_assignment(c, &y, left_type, name);
  6290. } else {
  6291. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6292. }
  6293. if (left_type == nullptr) {
  6294. left_type = t_invalid;
  6295. }
  6296. o->mode = Addressing_Value;
  6297. o->type = left_type;
  6298. o->expr = node;
  6299. return Expr_Expr;
  6300. case_end;
  6301. case_ast_node(re, OrReturnExpr, node);
  6302. String name = re->token.string;
  6303. Operand x = {};
  6304. check_multi_expr_with_type_hint(c, &x, re->expr, type_hint);
  6305. if (x.mode == Addressing_Invalid) {
  6306. o->mode = Addressing_Value;
  6307. o->type = t_invalid;
  6308. o->expr = node;
  6309. return Expr_Expr;
  6310. }
  6311. Type *left_type = nullptr;
  6312. Type *right_type = nullptr;
  6313. check_or_return_split_types(c, &x, name, &left_type, &right_type);
  6314. add_type_and_value(&c->checker->info, re->expr, x.mode, x.type, x.value);
  6315. if (right_type == nullptr) {
  6316. check_or_else_expr_no_value_error(c, name, x, type_hint);
  6317. } else {
  6318. Type *proc_type = base_type(c->curr_proc_sig);
  6319. GB_ASSERT(proc_type->kind == Type_Proc);
  6320. Type *result_type = proc_type->Proc.results;
  6321. if (result_type == nullptr) {
  6322. error(node, "'%.*s' requires the current procedure to have at least one return value", LIT(name));
  6323. } else {
  6324. GB_ASSERT(result_type->kind == Type_Tuple);
  6325. auto const &vars = result_type->Tuple.variables;
  6326. Type *end_type = vars[vars.count-1]->type;
  6327. if (vars.count > 1) {
  6328. if (!proc_type->Proc.has_named_results) {
  6329. 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));
  6330. }
  6331. }
  6332. Operand rhs = {};
  6333. rhs.type = right_type;
  6334. rhs.mode = Addressing_Value;
  6335. // TODO(bill): better error message
  6336. if (!check_is_assignable_to(c, &rhs, end_type)) {
  6337. gbString a = type_to_string(right_type);
  6338. gbString b = type_to_string(end_type);
  6339. gbString ret_type = type_to_string(result_type);
  6340. error(node, "Cannot assign end value of type '%s' to '%s' in '%.*s'", a, b, LIT(name));
  6341. if (vars.count == 1) {
  6342. error_line("\tProcedure return value type: %s\n", ret_type);
  6343. } else {
  6344. error_line("\tProcedure return value types: (%s)\n", ret_type);
  6345. }
  6346. gb_string_free(ret_type);
  6347. gb_string_free(b);
  6348. gb_string_free(a);
  6349. }
  6350. }
  6351. }
  6352. o->expr = node;
  6353. o->type = left_type;
  6354. if (left_type != nullptr) {
  6355. o->mode = Addressing_Value;
  6356. } else {
  6357. o->mode = Addressing_NoValue;
  6358. }
  6359. if (c->curr_proc_sig == nullptr) {
  6360. error(node, "'%.*s' can only be used within a procedure", LIT(name));
  6361. }
  6362. if (c->in_defer) {
  6363. error(node, "'or_return' cannot be used within a defer statement");
  6364. }
  6365. return Expr_Expr;
  6366. case_end;
  6367. case_ast_node(cl, CompoundLit, node);
  6368. Type *type = type_hint;
  6369. if (type != nullptr && is_type_untyped(type)) {
  6370. type = nullptr;
  6371. }
  6372. bool is_to_be_determined_array_count = false;
  6373. bool is_constant = true;
  6374. if (cl->type != nullptr) {
  6375. type = nullptr;
  6376. // [?]Type
  6377. if (cl->type->kind == Ast_ArrayType && cl->type->ArrayType.count != nullptr) {
  6378. Ast *count = cl->type->ArrayType.count;
  6379. if (count->kind == Ast_UnaryExpr &&
  6380. count->UnaryExpr.op.kind == Token_Question) {
  6381. type = alloc_type_array(check_type(c, cl->type->ArrayType.elem), -1);
  6382. is_to_be_determined_array_count = true;
  6383. }
  6384. if (cl->elems.count > 0) {
  6385. if (cl->type->ArrayType.tag != nullptr) {
  6386. Ast *tag = cl->type->ArrayType.tag;
  6387. GB_ASSERT(tag->kind == Ast_BasicDirective);
  6388. String name = tag->BasicDirective.name.string;
  6389. if (name == "soa") {
  6390. error(node, "#soa arrays are not supported for compound literals");
  6391. return kind;
  6392. }
  6393. }
  6394. }
  6395. }
  6396. if (cl->type->kind == Ast_DynamicArrayType && cl->type->DynamicArrayType.tag != nullptr) {
  6397. if (cl->elems.count > 0) {
  6398. Ast *tag = cl->type->DynamicArrayType.tag;
  6399. GB_ASSERT(tag->kind == Ast_BasicDirective);
  6400. String name = tag->BasicDirective.name.string;
  6401. if (name == "soa") {
  6402. error(node, "#soa arrays are not supported for compound literals");
  6403. return kind;
  6404. }
  6405. }
  6406. }
  6407. if (type == nullptr) {
  6408. type = check_type(c, cl->type);
  6409. }
  6410. }
  6411. if (type == nullptr) {
  6412. error(node, "Missing type in compound literal");
  6413. return kind;
  6414. }
  6415. Type *t = base_type(type);
  6416. if (is_type_polymorphic(t)) {
  6417. gbString str = type_to_string(type);
  6418. error(node, "Cannot use a polymorphic type for a compound literal, got '%s'", str);
  6419. o->expr = node;
  6420. o->type = type;
  6421. gb_string_free(str);
  6422. return kind;
  6423. }
  6424. switch (t->kind) {
  6425. case Type_Struct: {
  6426. if (cl->elems.count == 0) {
  6427. break; // NOTE(bill): No need to init
  6428. }
  6429. if (t->Struct.is_raw_union) {
  6430. if (cl->elems.count > 0) {
  6431. // NOTE: unions cannot be constant
  6432. is_constant = false;
  6433. if (cl->elems[0]->kind != Ast_FieldValue) {
  6434. gbString type_str = type_to_string(type);
  6435. error(node, "%s ('struct #raw_union') compound literals are only allowed to contain 'field = value' elements", type_str);
  6436. gb_string_free(type_str);
  6437. } else {
  6438. if (cl->elems.count != 1) {
  6439. gbString type_str = type_to_string(type);
  6440. 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);
  6441. gb_string_free(type_str);
  6442. } else {
  6443. Ast *elem = cl->elems[0];
  6444. ast_node(fv, FieldValue, elem);
  6445. if (fv->field->kind != Ast_Ident) {
  6446. gbString expr_str = expr_to_string(fv->field);
  6447. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  6448. gb_string_free(expr_str);
  6449. break;
  6450. }
  6451. String name = fv->field->Ident.token.string;
  6452. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6453. bool is_unknown = sel.entity == nullptr;
  6454. if (is_unknown) {
  6455. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  6456. break;
  6457. }
  6458. if (sel.index.count > 1) {
  6459. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  6460. break;
  6461. }
  6462. Entity *field = t->Struct.fields[sel.index[0]];
  6463. add_entity_use(c, fv->field, field);
  6464. Operand o = {};
  6465. check_expr_or_type(c, &o, fv->value, field->type);
  6466. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6467. }
  6468. }
  6469. }
  6470. break;
  6471. }
  6472. isize field_count = t->Struct.fields.count;
  6473. isize min_field_count = t->Struct.fields.count;
  6474. for (isize i = min_field_count-1; i >= 0; i--) {
  6475. Entity *e = t->Struct.fields[i];
  6476. GB_ASSERT(e->kind == Entity_Variable);
  6477. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  6478. min_field_count--;
  6479. } else {
  6480. break;
  6481. }
  6482. }
  6483. if (cl->elems[0]->kind == Ast_FieldValue) {
  6484. bool *fields_visited = gb_alloc_array(temporary_allocator(), bool, field_count);
  6485. for_array(i, cl->elems) {
  6486. Ast *elem = cl->elems[i];
  6487. if (elem->kind != Ast_FieldValue) {
  6488. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6489. continue;
  6490. }
  6491. ast_node(fv, FieldValue, elem);
  6492. if (fv->field->kind != Ast_Ident) {
  6493. gbString expr_str = expr_to_string(fv->field);
  6494. error(elem, "Invalid field name '%s' in structure literal", expr_str);
  6495. gb_string_free(expr_str);
  6496. continue;
  6497. }
  6498. String name = fv->field->Ident.token.string;
  6499. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6500. bool is_unknown = sel.entity == nullptr;
  6501. if (is_unknown) {
  6502. error(elem, "Unknown field '%.*s' in structure literal", LIT(name));
  6503. continue;
  6504. }
  6505. if (sel.index.count > 1) {
  6506. error(elem, "Cannot assign to an anonymous field '%.*s' in a structure literal (at the moment)", LIT(name));
  6507. continue;
  6508. }
  6509. Entity *field = t->Struct.fields[sel.index[0]];
  6510. add_entity_use(c, fv->field, field);
  6511. if (fields_visited[sel.index[0]]) {
  6512. error(elem, "Duplicate field '%.*s' in structure literal", LIT(name));
  6513. continue;
  6514. }
  6515. fields_visited[sel.index[0]] = true;
  6516. Operand o = {};
  6517. check_expr_or_type(c, &o, fv->value, field->type);
  6518. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  6519. is_constant = false;
  6520. }
  6521. if (is_constant) {
  6522. is_constant = check_is_operand_compound_lit_constant(c, &o);
  6523. }
  6524. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6525. }
  6526. } else {
  6527. bool seen_field_value = false;
  6528. for_array(index, cl->elems) {
  6529. Entity *field = nullptr;
  6530. Ast *elem = cl->elems[index];
  6531. if (elem->kind == Ast_FieldValue) {
  6532. seen_field_value = true;
  6533. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6534. continue;
  6535. } else if (seen_field_value) {
  6536. error(elem, "Value elements cannot be used after a 'field = value'");
  6537. continue;
  6538. }
  6539. if (index >= field_count) {
  6540. error(elem, "Too many values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  6541. break;
  6542. }
  6543. if (field == nullptr) {
  6544. field = t->Struct.fields[index];
  6545. }
  6546. Operand o = {};
  6547. check_expr_or_type(c, &o, elem, field->type);
  6548. if (is_type_any(field->type) || is_type_union(field->type) || is_type_raw_union(field->type) || is_type_typeid(field->type)) {
  6549. is_constant = false;
  6550. }
  6551. if (is_constant) {
  6552. is_constant = check_is_operand_compound_lit_constant(c, &o);
  6553. }
  6554. check_assignment(c, &o, field->type, str_lit("structure literal"));
  6555. }
  6556. if (cl->elems.count < field_count) {
  6557. if (min_field_count < field_count) {
  6558. if (cl->elems.count < min_field_count) {
  6559. error(cl->close, "Too few values in structure literal, expected at least %td, got %td", min_field_count, cl->elems.count);
  6560. }
  6561. } else {
  6562. error(cl->close, "Too few values in structure literal, expected %td, got %td", field_count, cl->elems.count);
  6563. }
  6564. }
  6565. }
  6566. break;
  6567. }
  6568. case Type_Slice:
  6569. case Type_Array:
  6570. case Type_DynamicArray:
  6571. case Type_SimdVector:
  6572. case Type_Matrix:
  6573. {
  6574. Type *elem_type = nullptr;
  6575. String context_name = {};
  6576. i64 max_type_count = -1;
  6577. if (t->kind == Type_Slice) {
  6578. elem_type = t->Slice.elem;
  6579. context_name = str_lit("slice literal");
  6580. } else if (t->kind == Type_Array) {
  6581. elem_type = t->Array.elem;
  6582. context_name = str_lit("array literal");
  6583. if (!is_to_be_determined_array_count) {
  6584. max_type_count = t->Array.count;
  6585. }
  6586. } else if (t->kind == Type_DynamicArray) {
  6587. elem_type = t->DynamicArray.elem;
  6588. context_name = str_lit("dynamic array literal");
  6589. is_constant = false;
  6590. if (!build_context.no_dynamic_literals) {
  6591. add_package_dependency(c, "runtime", "__dynamic_array_reserve");
  6592. add_package_dependency(c, "runtime", "__dynamic_array_append");
  6593. }
  6594. } else if (t->kind == Type_SimdVector) {
  6595. elem_type = t->SimdVector.elem;
  6596. context_name = str_lit("simd vector literal");
  6597. max_type_count = t->SimdVector.count;
  6598. } else if (t->kind == Type_Matrix) {
  6599. elem_type = t->Matrix.elem;
  6600. context_name = str_lit("matrix literal");
  6601. max_type_count = t->Matrix.row_count*t->Matrix.column_count;
  6602. } else {
  6603. GB_PANIC("unreachable");
  6604. }
  6605. i64 max = 0;
  6606. Type *bet = base_type(elem_type);
  6607. if (!elem_type_can_be_constant(bet)) {
  6608. is_constant = false;
  6609. }
  6610. if (bet == t_invalid) {
  6611. break;
  6612. }
  6613. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  6614. if (is_type_simd_vector(t)) {
  6615. error(cl->elems[0], "'field = value' is not allowed for SIMD vector literals");
  6616. } else {
  6617. RangeCache rc = range_cache_make(heap_allocator());
  6618. defer (range_cache_destroy(&rc));
  6619. for_array(i, cl->elems) {
  6620. Ast *elem = cl->elems[i];
  6621. if (elem->kind != Ast_FieldValue) {
  6622. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6623. continue;
  6624. }
  6625. ast_node(fv, FieldValue, elem);
  6626. if (is_ast_range(fv->field)) {
  6627. Token op = fv->field->BinaryExpr.op;
  6628. Operand x = {};
  6629. Operand y = {};
  6630. bool ok = check_range(c, fv->field, &x, &y, nullptr);
  6631. if (!ok) {
  6632. continue;
  6633. }
  6634. if (x.mode != Addressing_Constant || !is_type_integer(core_type(x.type))) {
  6635. error(x.expr, "Expected a constant integer as an array field");
  6636. continue;
  6637. }
  6638. if (y.mode != Addressing_Constant || !is_type_integer(core_type(y.type))) {
  6639. error(y.expr, "Expected a constant integer as an array field");
  6640. continue;
  6641. }
  6642. i64 lo = exact_value_to_i64(x.value);
  6643. i64 hi = exact_value_to_i64(y.value);
  6644. i64 max_index = hi;
  6645. if (op.kind == Token_RangeHalf) { // ..< (exclusive)
  6646. hi -= 1;
  6647. } else { // .. (inclusive)
  6648. max_index += 1;
  6649. }
  6650. bool new_range = range_cache_add_range(&rc, lo, hi);
  6651. if (!new_range) {
  6652. error(elem, "Overlapping field range index %lld %.*s %lld for %.*s", lo, LIT(op.string), hi, LIT(context_name));
  6653. continue;
  6654. }
  6655. if (max_type_count >= 0 && (lo < 0 || lo >= max_type_count)) {
  6656. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", lo, max_type_count, LIT(context_name));
  6657. continue;
  6658. }
  6659. if (max_type_count >= 0 && (hi < 0 || hi >= max_type_count)) {
  6660. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", hi, max_type_count, LIT(context_name));
  6661. continue;
  6662. }
  6663. if (max < hi) {
  6664. max = max_index;
  6665. }
  6666. Operand operand = {};
  6667. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6668. check_assignment(c, &operand, elem_type, context_name);
  6669. is_constant = is_constant && operand.mode == Addressing_Constant;
  6670. } else {
  6671. Operand op_index = {};
  6672. check_expr(c, &op_index, fv->field);
  6673. if (op_index.mode != Addressing_Constant || !is_type_integer(core_type(op_index.type))) {
  6674. error(elem, "Expected a constant integer as an array field");
  6675. continue;
  6676. }
  6677. // add_type_and_value(c->info, op_index.expr, op_index.mode, op_index.type, op_index.value);
  6678. i64 index = exact_value_to_i64(op_index.value);
  6679. if (max_type_count >= 0 && (index < 0 || index >= max_type_count)) {
  6680. error(elem, "Index %lld is out of bounds (0..<%lld) for %.*s", index, max_type_count, LIT(context_name));
  6681. continue;
  6682. }
  6683. bool new_index = range_cache_add_index(&rc, index);
  6684. if (!new_index) {
  6685. error(elem, "Duplicate field index %lld for %.*s", index, LIT(context_name));
  6686. continue;
  6687. }
  6688. if (max < index+1) {
  6689. max = index+1;
  6690. }
  6691. Operand operand = {};
  6692. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6693. check_assignment(c, &operand, elem_type, context_name);
  6694. is_constant = is_constant && operand.mode == Addressing_Constant;
  6695. }
  6696. }
  6697. cl->max_count = max;
  6698. }
  6699. } else {
  6700. isize index = 0;
  6701. for (; index < cl->elems.count; index++) {
  6702. Ast *e = cl->elems[index];
  6703. if (e == nullptr) {
  6704. error(node, "Invalid literal element");
  6705. continue;
  6706. }
  6707. if (e->kind == Ast_FieldValue) {
  6708. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6709. continue;
  6710. }
  6711. if (0 <= max_type_count && max_type_count <= index) {
  6712. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  6713. }
  6714. Operand operand = {};
  6715. check_expr_with_type_hint(c, &operand, e, elem_type);
  6716. check_assignment(c, &operand, elem_type, context_name);
  6717. is_constant = is_constant && operand.mode == Addressing_Constant;
  6718. }
  6719. if (max < index) {
  6720. max = index;
  6721. }
  6722. }
  6723. if (t->kind == Type_Array) {
  6724. if (is_to_be_determined_array_count) {
  6725. t->Array.count = max;
  6726. } else if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  6727. if (0 < max && max < t->Array.count) {
  6728. error(node, "Expected %lld values for this array literal, got %lld", cast(long long)t->Array.count, cast(long long)max);
  6729. }
  6730. }
  6731. }
  6732. if (t->kind == Type_SimdVector) {
  6733. if (!is_constant) {
  6734. error(node, "Expected all constant elements for a simd vector");
  6735. }
  6736. }
  6737. if (t->kind == Type_DynamicArray) {
  6738. if (build_context.no_dynamic_literals && cl->elems.count) {
  6739. error(node, "Compound literals of dynamic types have been disabled");
  6740. }
  6741. }
  6742. if (t->kind == Type_Matrix) {
  6743. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  6744. if (0 < max && max < max_type_count) {
  6745. error(node, "Expected %lld values for this matrix literal, got %lld", cast(long long)max_type_count, cast(long long)max);
  6746. }
  6747. }
  6748. }
  6749. break;
  6750. }
  6751. case Type_EnumeratedArray:
  6752. {
  6753. Type *elem_type = t->EnumeratedArray.elem;
  6754. Type *index_type = t->EnumeratedArray.index;
  6755. String context_name = str_lit("enumerated array literal");
  6756. i64 max_type_count = t->EnumeratedArray.count;
  6757. gbString index_type_str = type_to_string(index_type);
  6758. defer (gb_string_free(index_type_str));
  6759. i64 total_lo = exact_value_to_i64(*t->EnumeratedArray.min_value);
  6760. i64 total_hi = exact_value_to_i64(*t->EnumeratedArray.max_value);
  6761. String total_lo_string = {};
  6762. String total_hi_string = {};
  6763. GB_ASSERT(is_type_enum(index_type));
  6764. {
  6765. Type *bt = base_type(index_type);
  6766. GB_ASSERT(bt->kind == Type_Enum);
  6767. for_array(i, bt->Enum.fields) {
  6768. Entity *f = bt->Enum.fields[i];
  6769. if (f->kind != Entity_Constant) {
  6770. continue;
  6771. }
  6772. if (total_lo_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.min_value)) {
  6773. total_lo_string = f->token.string;
  6774. }
  6775. if (total_hi_string.len == 0 && compare_exact_values(Token_CmpEq, f->Constant.value, *t->EnumeratedArray.max_value)) {
  6776. total_hi_string = f->token.string;
  6777. }
  6778. if (total_lo_string.len != 0 && total_hi_string.len != 0) {
  6779. break;
  6780. }
  6781. }
  6782. }
  6783. i64 max = 0;
  6784. Type *bet = base_type(elem_type);
  6785. if (!elem_type_can_be_constant(bet)) {
  6786. is_constant = false;
  6787. }
  6788. if (bet == t_invalid) {
  6789. break;
  6790. }
  6791. if (cl->elems.count > 0 && cl->elems[0]->kind == Ast_FieldValue) {
  6792. RangeCache rc = range_cache_make(heap_allocator());
  6793. defer (range_cache_destroy(&rc));
  6794. for_array(i, cl->elems) {
  6795. Ast *elem = cl->elems[i];
  6796. if (elem->kind != Ast_FieldValue) {
  6797. error(elem, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6798. continue;
  6799. }
  6800. ast_node(fv, FieldValue, elem);
  6801. if (is_ast_range(fv->field)) {
  6802. Token op = fv->field->BinaryExpr.op;
  6803. Operand x = {};
  6804. Operand y = {};
  6805. bool ok = check_range(c, fv->field, &x, &y, nullptr, index_type);
  6806. if (!ok) {
  6807. continue;
  6808. }
  6809. if (x.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  6810. error(x.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6811. continue;
  6812. }
  6813. if (y.mode != Addressing_Constant || !are_types_identical(x.type, index_type)) {
  6814. error(y.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6815. continue;
  6816. }
  6817. i64 lo = exact_value_to_i64(x.value);
  6818. i64 hi = exact_value_to_i64(y.value);
  6819. i64 max_index = hi;
  6820. if (op.kind == Token_RangeHalf) {
  6821. hi -= 1;
  6822. }
  6823. bool new_range = range_cache_add_range(&rc, lo, hi);
  6824. if (!new_range) {
  6825. gbString lo_str = expr_to_string(x.expr);
  6826. gbString hi_str = expr_to_string(y.expr);
  6827. error(elem, "Overlapping field range index %s %.*s %s for %.*s", lo_str, LIT(op.string), hi_str, LIT(context_name));
  6828. gb_string_free(hi_str);
  6829. gb_string_free(lo_str);
  6830. continue;
  6831. }
  6832. // NOTE(bill): These are sanity checks for invalid enum values
  6833. if (max_type_count >= 0 && (lo < total_lo || lo > total_hi)) {
  6834. gbString lo_str = expr_to_string(x.expr);
  6835. 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));
  6836. gb_string_free(lo_str);
  6837. continue;
  6838. }
  6839. if (max_type_count >= 0 && (hi < 0 || hi > total_hi)) {
  6840. gbString hi_str = expr_to_string(y.expr);
  6841. 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));
  6842. gb_string_free(hi_str);
  6843. continue;
  6844. }
  6845. if (max < hi) {
  6846. max = max_index;
  6847. }
  6848. Operand operand = {};
  6849. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6850. check_assignment(c, &operand, elem_type, context_name);
  6851. is_constant = is_constant && operand.mode == Addressing_Constant;
  6852. } else {
  6853. Operand op_index = {};
  6854. check_expr_with_type_hint(c, &op_index, fv->field, index_type);
  6855. if (op_index.mode != Addressing_Constant || !are_types_identical(op_index.type, index_type)) {
  6856. error(op_index.expr, "Expected a constant enum of type '%s' as an array field", index_type_str);
  6857. continue;
  6858. }
  6859. i64 index = exact_value_to_i64(op_index.value);
  6860. if (max_type_count >= 0 && (index < total_lo || index > total_hi)) {
  6861. gbString idx_str = expr_to_string(op_index.expr);
  6862. 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));
  6863. gb_string_free(idx_str);
  6864. continue;
  6865. }
  6866. bool new_index = range_cache_add_index(&rc, index);
  6867. if (!new_index) {
  6868. gbString idx_str = expr_to_string(op_index.expr);
  6869. error(elem, "Duplicate field index %s for %.*s", idx_str, LIT(context_name));
  6870. gb_string_free(idx_str);
  6871. continue;
  6872. }
  6873. if (max < index+1) {
  6874. max = index+1;
  6875. }
  6876. Operand operand = {};
  6877. check_expr_with_type_hint(c, &operand, fv->value, elem_type);
  6878. check_assignment(c, &operand, elem_type, context_name);
  6879. is_constant = is_constant && operand.mode == Addressing_Constant;
  6880. }
  6881. }
  6882. cl->max_count = max;
  6883. } else {
  6884. isize index = 0;
  6885. for (; index < cl->elems.count; index++) {
  6886. Ast *e = cl->elems[index];
  6887. if (e == nullptr) {
  6888. error(node, "Invalid literal element");
  6889. continue;
  6890. }
  6891. if (e->kind == Ast_FieldValue) {
  6892. error(e, "Mixture of 'field = value' and value elements in a literal is not allowed");
  6893. continue;
  6894. }
  6895. if (0 <= max_type_count && max_type_count <= index) {
  6896. error(e, "Index %lld is out of bounds (>= %lld) for %.*s", index, max_type_count, LIT(context_name));
  6897. }
  6898. Operand operand = {};
  6899. check_expr_with_type_hint(c, &operand, e, elem_type);
  6900. check_assignment(c, &operand, elem_type, context_name);
  6901. is_constant = is_constant && operand.mode == Addressing_Constant;
  6902. }
  6903. if (max < index) {
  6904. max = index;
  6905. }
  6906. }
  6907. if (cl->elems.count > 0 && cl->elems[0]->kind != Ast_FieldValue) {
  6908. if (0 < max && max < t->EnumeratedArray.count) {
  6909. error(node, "Expected %lld values for this enumerated array literal, got %lld", cast(long long)t->EnumeratedArray.count, cast(long long)max);
  6910. } else {
  6911. error(node, "Enumerated array literals must only have 'field = value' elements, bare elements are not allowed");
  6912. }
  6913. }
  6914. break;
  6915. }
  6916. case Type_Basic: {
  6917. if (!is_type_any(t)) {
  6918. if (cl->elems.count != 0) {
  6919. error(node, "Illegal compound literal");
  6920. }
  6921. break;
  6922. }
  6923. if (cl->elems.count == 0) {
  6924. break; // NOTE(bill): No need to init
  6925. }
  6926. { // Checker values
  6927. Type *field_types[2] = {t_rawptr, t_typeid};
  6928. isize field_count = 2;
  6929. if (cl->elems[0]->kind == Ast_FieldValue) {
  6930. bool fields_visited[2] = {};
  6931. for_array(i, cl->elems) {
  6932. Ast *elem = cl->elems[i];
  6933. if (elem->kind != Ast_FieldValue) {
  6934. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  6935. continue;
  6936. }
  6937. ast_node(fv, FieldValue, elem);
  6938. if (fv->field->kind != Ast_Ident) {
  6939. gbString expr_str = expr_to_string(fv->field);
  6940. error(elem, "Invalid field name '%s' in 'any' literal", expr_str);
  6941. gb_string_free(expr_str);
  6942. continue;
  6943. }
  6944. String name = fv->field->Ident.token.string;
  6945. Selection sel = lookup_field(type, name, o->mode == Addressing_Type);
  6946. if (sel.entity == nullptr) {
  6947. error(elem, "Unknown field '%.*s' in 'any' literal", LIT(name));
  6948. continue;
  6949. }
  6950. isize index = sel.index[0];
  6951. if (fields_visited[index]) {
  6952. error(elem, "Duplicate field '%.*s' in 'any' literal", LIT(name));
  6953. continue;
  6954. }
  6955. fields_visited[index] = true;
  6956. check_expr(c, o, fv->value);
  6957. // NOTE(bill): 'any' literals can never be constant
  6958. is_constant = false;
  6959. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  6960. }
  6961. } else {
  6962. for_array(index, cl->elems) {
  6963. Ast *elem = cl->elems[index];
  6964. if (elem->kind == Ast_FieldValue) {
  6965. error(elem, "Mixture of 'field = value' and value elements in a 'any' literal is not allowed");
  6966. continue;
  6967. }
  6968. check_expr(c, o, elem);
  6969. if (index >= field_count) {
  6970. error(o->expr, "Too many values in 'any' literal, expected %td", field_count);
  6971. break;
  6972. }
  6973. // NOTE(bill): 'any' literals can never be constant
  6974. is_constant = false;
  6975. check_assignment(c, o, field_types[index], str_lit("'any' literal"));
  6976. }
  6977. if (cl->elems.count < field_count) {
  6978. error(cl->close, "Too few values in 'any' literal, expected %td, got %td", field_count, cl->elems.count);
  6979. }
  6980. }
  6981. }
  6982. break;
  6983. }
  6984. case Type_Map: {
  6985. if (cl->elems.count == 0) {
  6986. break;
  6987. }
  6988. is_constant = false;
  6989. { // Checker values
  6990. bool key_is_typeid = is_type_typeid(t->Map.key);
  6991. bool value_is_typeid = is_type_typeid(t->Map.value);
  6992. for_array(i, cl->elems) {
  6993. Ast *elem = cl->elems[i];
  6994. if (elem->kind != Ast_FieldValue) {
  6995. error(elem, "Only 'field = value' elements are allowed in a map literal");
  6996. continue;
  6997. }
  6998. ast_node(fv, FieldValue, elem);
  6999. if (key_is_typeid) {
  7000. check_expr_or_type(c, o, fv->field, t->Map.key);
  7001. } else {
  7002. check_expr_with_type_hint(c, o, fv->field, t->Map.key);
  7003. }
  7004. check_assignment(c, o, t->Map.key, str_lit("map literal"));
  7005. if (o->mode == Addressing_Invalid) {
  7006. continue;
  7007. }
  7008. if (value_is_typeid) {
  7009. check_expr_or_type(c, o, fv->value, t->Map.value);
  7010. } else {
  7011. check_expr_with_type_hint(c, o, fv->value, t->Map.value);
  7012. }
  7013. check_assignment(c, o, t->Map.value, str_lit("map literal"));
  7014. }
  7015. }
  7016. if (build_context.no_dynamic_literals && cl->elems.count) {
  7017. error(node, "Compound literals of dynamic types have been disabled");
  7018. } else {
  7019. add_package_dependency(c, "runtime", "__dynamic_map_reserve");
  7020. add_package_dependency(c, "runtime", "__dynamic_map_set");
  7021. }
  7022. break;
  7023. }
  7024. case Type_BitSet: {
  7025. if (cl->elems.count == 0) {
  7026. break; // NOTE(bill): No need to init
  7027. }
  7028. Type *et = base_type(t->BitSet.elem);
  7029. isize field_count = 0;
  7030. if (et->kind == Type_Enum) {
  7031. field_count = et->Enum.fields.count;
  7032. }
  7033. if (cl->elems[0]->kind == Ast_FieldValue) {
  7034. error(cl->elems[0], "'field = value' in a bit_set a literal is not allowed");
  7035. is_constant = false;
  7036. } else {
  7037. for_array(index, cl->elems) {
  7038. Ast *elem = cl->elems[index];
  7039. if (elem->kind == Ast_FieldValue) {
  7040. error(elem, "'field = value' in a bit_set a literal is not allowed");
  7041. continue;
  7042. }
  7043. check_expr_with_type_hint(c, o, elem, et);
  7044. if (is_constant) {
  7045. is_constant = o->mode == Addressing_Constant;
  7046. }
  7047. check_assignment(c, o, t->BitSet.elem, str_lit("bit_set literal"));
  7048. if (o->mode == Addressing_Constant) {
  7049. i64 lower = t->BitSet.lower;
  7050. i64 upper = t->BitSet.upper;
  7051. i64 v = exact_value_to_i64(o->value);
  7052. if (lower <= v && v <= upper) {
  7053. // okay
  7054. } else {
  7055. error(elem, "Bit field value out of bounds, %lld not in the range %lld .. %lld", v, lower, upper);
  7056. continue;
  7057. }
  7058. }
  7059. }
  7060. }
  7061. break;
  7062. }
  7063. default: {
  7064. if (cl->elems.count == 0) {
  7065. break; // NOTE(bill): No need to init
  7066. }
  7067. gbString str = type_to_string(type);
  7068. error(node, "Invalid compound literal type '%s'", str);
  7069. gb_string_free(str);
  7070. return kind;
  7071. }
  7072. }
  7073. if (is_constant) {
  7074. o->mode = Addressing_Constant;
  7075. if (is_type_bit_set(type)) {
  7076. // NOTE(bill): Encode as an integer
  7077. i64 lower = base_type(type)->BitSet.lower;
  7078. u64 bits = 0;
  7079. for_array(index, cl->elems) {
  7080. Ast *elem = cl->elems[index];
  7081. GB_ASSERT(elem->kind != Ast_FieldValue);
  7082. TypeAndValue tav = elem->tav;
  7083. ExactValue i = exact_value_to_integer(tav.value);
  7084. if (i.kind != ExactValue_Integer) {
  7085. continue;
  7086. }
  7087. i64 val = big_int_to_i64(&i.value_integer);
  7088. val -= lower;
  7089. u64 bit = u64(1ll<<val);
  7090. bits |= bit;
  7091. }
  7092. o->value = exact_value_u64(bits);
  7093. } else if (is_type_constant_type(type) && cl->elems.count == 0) {
  7094. ExactValue value = exact_value_compound(node);
  7095. Type *bt = core_type(type);
  7096. if (bt->kind == Type_Basic) {
  7097. if (bt->Basic.flags & BasicFlag_Boolean) {
  7098. value = exact_value_bool(false);
  7099. } else if (bt->Basic.flags & BasicFlag_Integer) {
  7100. value = exact_value_i64(0);
  7101. } else if (bt->Basic.flags & BasicFlag_Unsigned) {
  7102. value = exact_value_i64(0);
  7103. } else if (bt->Basic.flags & BasicFlag_Float) {
  7104. value = exact_value_float(0);
  7105. } else if (bt->Basic.flags & BasicFlag_Complex) {
  7106. value = exact_value_complex(0, 0);
  7107. } else if (bt->Basic.flags & BasicFlag_Quaternion) {
  7108. value = exact_value_quaternion(0, 0, 0, 0);
  7109. } else if (bt->Basic.flags & BasicFlag_Pointer) {
  7110. value = exact_value_pointer(0);
  7111. } else if (bt->Basic.flags & BasicFlag_String) {
  7112. String empty_string = {};
  7113. value = exact_value_string(empty_string);
  7114. } else if (bt->Basic.flags & BasicFlag_Rune) {
  7115. value = exact_value_i64(0);
  7116. }
  7117. }
  7118. o->value = value;
  7119. } else {
  7120. o->value = exact_value_compound(node);
  7121. }
  7122. } else {
  7123. o->mode = Addressing_Value;
  7124. }
  7125. o->type = type;
  7126. case_end;
  7127. case_ast_node(pe, ParenExpr, node);
  7128. kind = check_expr_base(c, o, pe->expr, type_hint);
  7129. node->viral_state_flags |= pe->expr->viral_state_flags;
  7130. o->expr = node;
  7131. case_end;
  7132. case_ast_node(te, TagExpr, node);
  7133. String name = te->name.string;
  7134. error(node, "Unknown tag expression, #%.*s", LIT(name));
  7135. if (te->expr) {
  7136. kind = check_expr_base(c, o, te->expr, type_hint);
  7137. node->viral_state_flags |= te->expr->viral_state_flags;
  7138. }
  7139. o->expr = node;
  7140. case_end;
  7141. case_ast_node(ta, TypeAssertion, node);
  7142. check_expr(c, o, ta->expr);
  7143. node->viral_state_flags |= ta->expr->viral_state_flags;
  7144. if (o->mode == Addressing_Invalid) {
  7145. o->expr = node;
  7146. return kind;
  7147. }
  7148. if (o->mode == Addressing_Constant) {
  7149. gbString expr_str = expr_to_string(o->expr);
  7150. error(o->expr, "A type assertion cannot be applied to a constant expression: '%s'", expr_str);
  7151. gb_string_free(expr_str);
  7152. o->mode = Addressing_Invalid;
  7153. o->expr = node;
  7154. return kind;
  7155. }
  7156. if (is_type_untyped(o->type)) {
  7157. gbString expr_str = expr_to_string(o->expr);
  7158. error(o->expr, "A type assertion cannot be applied to an untyped expression: '%s'", expr_str);
  7159. gb_string_free(expr_str);
  7160. o->mode = Addressing_Invalid;
  7161. o->expr = node;
  7162. return kind;
  7163. }
  7164. Type *src = type_deref(o->type);
  7165. Type *bsrc = base_type(src);
  7166. if (ta->type != nullptr && ta->type->kind == Ast_UnaryExpr && ta->type->UnaryExpr.op.kind == Token_Question) {
  7167. if (!is_type_union(src)) {
  7168. gbString str = type_to_string(o->type);
  7169. error(o->expr, "Type assertions with .? can only operate on unions, got %s", str);
  7170. gb_string_free(str);
  7171. o->mode = Addressing_Invalid;
  7172. o->expr = node;
  7173. return kind;
  7174. }
  7175. if (bsrc->Union.variants.count != 1 && type_hint != nullptr) {
  7176. bool allowed = false;
  7177. for_array(i, bsrc->Union.variants) {
  7178. Type *vt = bsrc->Union.variants[i];
  7179. if (are_types_identical(vt, type_hint)) {
  7180. allowed = true;
  7181. add_type_info_type(c, vt);
  7182. break;
  7183. }
  7184. }
  7185. if (allowed) {
  7186. add_type_info_type(c, o->type);
  7187. o->type = type_hint;
  7188. o->mode = Addressing_OptionalOk;
  7189. return kind;
  7190. }
  7191. }
  7192. if (bsrc->Union.variants.count != 1) {
  7193. error(o->expr, "Type assertions with .? can only operate on unions with 1 variant, got %lld", cast(long long)bsrc->Union.variants.count);
  7194. o->mode = Addressing_Invalid;
  7195. o->expr = node;
  7196. return kind;
  7197. }
  7198. add_type_info_type(c, o->type);
  7199. add_type_info_type(c, bsrc->Union.variants[0]);
  7200. o->type = bsrc->Union.variants[0];
  7201. o->mode = Addressing_OptionalOk;
  7202. } else {
  7203. Type *t = check_type(c, ta->type);
  7204. Type *dst = t;
  7205. if (is_type_union(src)) {
  7206. bool ok = false;
  7207. for_array(i, bsrc->Union.variants) {
  7208. Type *vt = bsrc->Union.variants[i];
  7209. if (are_types_identical(vt, dst)) {
  7210. ok = true;
  7211. break;
  7212. }
  7213. }
  7214. if (!ok) {
  7215. gbString expr_str = expr_to_string(o->expr);
  7216. gbString dst_type_str = type_to_string(t);
  7217. defer (gb_string_free(expr_str));
  7218. defer (gb_string_free(dst_type_str));
  7219. if (bsrc->Union.variants.count == 0) {
  7220. error(o->expr, "Cannot type assert '%s' to '%s' as this is an empty union", expr_str, dst_type_str);
  7221. } else {
  7222. error(o->expr, "Cannot type assert '%s' to '%s' as it is not a variant of that union", expr_str, dst_type_str);
  7223. }
  7224. o->mode = Addressing_Invalid;
  7225. o->expr = node;
  7226. return kind;
  7227. }
  7228. add_type_info_type(c, o->type);
  7229. add_type_info_type(c, t);
  7230. o->type = t;
  7231. o->mode = Addressing_OptionalOk;
  7232. } else if (is_type_any(src)) {
  7233. o->type = t;
  7234. o->mode = Addressing_OptionalOk;
  7235. add_type_info_type(c, o->type);
  7236. add_type_info_type(c, t);
  7237. } else {
  7238. gbString str = type_to_string(o->type);
  7239. error(o->expr, "Type assertions can only operate on unions and 'any', got %s", str);
  7240. gb_string_free(str);
  7241. o->mode = Addressing_Invalid;
  7242. o->expr = node;
  7243. return kind;
  7244. }
  7245. }
  7246. add_package_dependency(c, "runtime", "type_assertion_check");
  7247. add_package_dependency(c, "runtime", "type_assertion_check2");
  7248. case_end;
  7249. case_ast_node(tc, TypeCast, node);
  7250. check_expr_or_type(c, o, tc->type);
  7251. if (o->mode != Addressing_Type) {
  7252. gbString str = expr_to_string(tc->type);
  7253. error(tc->type, "Expected a type, got %s", str);
  7254. gb_string_free(str);
  7255. o->mode = Addressing_Invalid;
  7256. }
  7257. if (o->mode == Addressing_Invalid) {
  7258. o->expr = node;
  7259. return kind;
  7260. }
  7261. Type *type = o->type;
  7262. check_expr_base(c, o, tc->expr, type);
  7263. node->viral_state_flags |= tc->expr->viral_state_flags;
  7264. if (o->mode != Addressing_Invalid) {
  7265. switch (tc->token.kind) {
  7266. case Token_transmute:
  7267. check_transmute(c, node, o, type);
  7268. break;
  7269. case Token_cast:
  7270. check_cast(c, o, type);
  7271. break;
  7272. default:
  7273. error(node, "Invalid AST: Invalid casting expression");
  7274. o->mode = Addressing_Invalid;
  7275. break;
  7276. }
  7277. }
  7278. return Expr_Expr;
  7279. case_end;
  7280. case_ast_node(ac, AutoCast, node);
  7281. check_expr_base(c, o, ac->expr, type_hint);
  7282. node->viral_state_flags |= ac->expr->viral_state_flags;
  7283. if (o->mode == Addressing_Invalid) {
  7284. o->expr = node;
  7285. return kind;
  7286. }
  7287. if (type_hint) {
  7288. Type *type = type_of_expr(ac->expr);
  7289. check_cast(c, o, type_hint);
  7290. if (is_type_typed(type) && are_types_identical(type, type_hint)) {
  7291. if (build_context.vet_extra) {
  7292. error(node, "Redundant 'auto_cast' applied to expression");
  7293. }
  7294. }
  7295. }
  7296. o->expr = node;
  7297. return Expr_Expr;
  7298. case_end;
  7299. case_ast_node(ue, UnaryExpr, node);
  7300. Type *th = type_hint;
  7301. if (ue->op.kind == Token_And) {
  7302. th = type_deref(th);
  7303. }
  7304. check_expr_base(c, o, ue->expr, th);
  7305. node->viral_state_flags |= ue->expr->viral_state_flags;
  7306. if (o->mode != Addressing_Invalid) {
  7307. check_unary_expr(c, o, ue->op, node);
  7308. }
  7309. o->expr = node;
  7310. return kind;
  7311. case_end;
  7312. case_ast_node(be, BinaryExpr, node);
  7313. check_binary_expr(c, o, node, type_hint, true);
  7314. if (o->mode == Addressing_Invalid) {
  7315. o->expr = node;
  7316. return kind;
  7317. }
  7318. case_end;
  7319. case_ast_node(se, SelectorExpr, node);
  7320. check_selector(c, o, node, type_hint);
  7321. node->viral_state_flags |= se->expr->viral_state_flags;
  7322. case_end;
  7323. case_ast_node(se, SelectorCallExpr, node);
  7324. // IMPORTANT NOTE(bill, 2020-05-22): This is a complete hack to get a shorthand which is extremely useful for vtables
  7325. // COM APIs is a great example of where this kind of thing is extremely useful
  7326. // General idea:
  7327. //
  7328. // x->y(123) == x.y(x, 123)
  7329. //
  7330. // How this has been implemented at the moment is quite hacky but it's done so to reduce need for huge backend changes
  7331. // Just regenerating a new AST aids things
  7332. //
  7333. // TODO(bill): Is this a good hack or not?
  7334. //
  7335. // NOTE(bill, 2020-05-22): I'm going to regret this decision, ain't I?
  7336. if (se->modified_call) {
  7337. // Prevent double evaluation
  7338. o->expr = node;
  7339. o->type = node->tav.type;
  7340. o->value = node->tav.value;
  7341. o->mode = node->tav.mode;
  7342. return Expr_Expr;
  7343. }
  7344. bool allow_arrow_right_selector_expr;
  7345. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  7346. c->allow_arrow_right_selector_expr = true;
  7347. Operand x = {};
  7348. ExprKind kind = check_expr_base(c, &x, se->expr, nullptr);
  7349. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  7350. if (x.mode == Addressing_Invalid || x.type == t_invalid) {
  7351. o->mode = Addressing_Invalid;
  7352. o->type = t_invalid;
  7353. o->expr = node;
  7354. return kind;
  7355. }
  7356. if (!is_type_proc(x.type)) {
  7357. gbString type_str = type_to_string(x.type);
  7358. error(se->call, "Selector call expressions expect a procedure type for the call, got '%s'", type_str);
  7359. gb_string_free(type_str);
  7360. o->mode = Addressing_Invalid;
  7361. o->type = t_invalid;
  7362. o->expr = node;
  7363. return Expr_Stmt;
  7364. }
  7365. ast_node(ce, CallExpr, se->call);
  7366. GB_ASSERT(x.expr->kind == Ast_SelectorExpr);
  7367. Ast *first_arg = x.expr->SelectorExpr.expr;
  7368. GB_ASSERT(first_arg != nullptr);
  7369. Type *pt = base_type(x.type);
  7370. GB_ASSERT(pt->kind == Type_Proc);
  7371. Type *first_type = nullptr;
  7372. String first_arg_name = {};
  7373. if (pt->Proc.param_count > 0) {
  7374. Entity *f = pt->Proc.params->Tuple.variables[0];
  7375. first_type = f->type;
  7376. first_arg_name = f->token.string;
  7377. }
  7378. if (first_arg_name.len == 0) {
  7379. first_arg_name = str_lit("_");
  7380. }
  7381. if (first_type == nullptr) {
  7382. error(se->call, "Selector call expressions expect a procedure type for the call with at least 1 parameter");
  7383. o->mode = Addressing_Invalid;
  7384. o->type = t_invalid;
  7385. o->expr = node;
  7386. return Expr_Stmt;
  7387. }
  7388. Operand y = {};
  7389. y.mode = first_arg->tav.mode;
  7390. y.type = first_arg->tav.type;
  7391. y.value = first_arg->tav.value;
  7392. if (check_is_assignable_to(c, &y, first_type)) {
  7393. // Do nothing, it's valid
  7394. } else {
  7395. Operand z = y;
  7396. z.type = type_deref(y.type);
  7397. if (check_is_assignable_to(c, &z, first_type)) {
  7398. // NOTE(bill): AST GENERATION HACK!
  7399. Token op = {Token_Pointer};
  7400. first_arg = ast_deref_expr(first_arg->file(), first_arg, op);
  7401. } else if (y.mode == Addressing_Variable) {
  7402. Operand w = y;
  7403. w.type = alloc_type_pointer(y.type);
  7404. if (check_is_assignable_to(c, &w, first_type)) {
  7405. // NOTE(bill): AST GENERATION HACK!
  7406. Token op = {Token_And};
  7407. first_arg = ast_unary_expr(first_arg->file(), op, first_arg);
  7408. }
  7409. }
  7410. }
  7411. if (ce->args.count > 0) {
  7412. bool fail = false;
  7413. bool first_is_field_value = (ce->args[0]->kind == Ast_FieldValue);
  7414. for_array(i, ce->args) {
  7415. Ast *arg = ce->args[i];
  7416. bool mix = false;
  7417. if (first_is_field_value) {
  7418. mix = arg->kind != Ast_FieldValue;
  7419. } else {
  7420. mix = arg->kind == Ast_FieldValue;
  7421. }
  7422. if (mix) {
  7423. fail = true;
  7424. break;
  7425. }
  7426. }
  7427. if (!fail && first_is_field_value) {
  7428. Token op = {Token_Eq};
  7429. AstFile *f = first_arg->file();
  7430. first_arg = ast_field_value(f, ast_ident(f, make_token_ident(first_arg_name)), first_arg, op);
  7431. }
  7432. }
  7433. auto modified_args = slice_make<Ast *>(heap_allocator(), ce->args.count+1);
  7434. modified_args[0] = first_arg;
  7435. slice_copy(&modified_args, ce->args, 1);
  7436. ce->args = modified_args;
  7437. se->modified_call = true;
  7438. allow_arrow_right_selector_expr = c->allow_arrow_right_selector_expr;
  7439. c->allow_arrow_right_selector_expr = true;
  7440. check_expr_base(c, o, se->call, type_hint);
  7441. c->allow_arrow_right_selector_expr = allow_arrow_right_selector_expr;
  7442. o->expr = node;
  7443. return Expr_Expr;
  7444. case_end;
  7445. case_ast_node(ise, ImplicitSelectorExpr, node);
  7446. return check_implicit_selector_expr(c, o, node, type_hint);
  7447. case_end;
  7448. case_ast_node(ie, IndexExpr, node);
  7449. check_expr(c, o, ie->expr);
  7450. node->viral_state_flags |= ie->expr->viral_state_flags;
  7451. if (o->mode == Addressing_Invalid) {
  7452. o->expr = node;
  7453. return kind;
  7454. }
  7455. Type *t = base_type(type_deref(o->type));
  7456. bool is_ptr = is_type_pointer(o->type);
  7457. bool is_const = o->mode == Addressing_Constant;
  7458. if (is_type_map(t)) {
  7459. Operand key = {};
  7460. if (is_type_typeid(t->Map.key)) {
  7461. check_expr_or_type(c, &key, ie->index, t->Map.key);
  7462. } else {
  7463. check_expr_with_type_hint(c, &key, ie->index, t->Map.key);
  7464. }
  7465. check_assignment(c, &key, t->Map.key, str_lit("map index"));
  7466. if (key.mode == Addressing_Invalid) {
  7467. o->mode = Addressing_Invalid;
  7468. o->expr = node;
  7469. return kind;
  7470. }
  7471. o->mode = Addressing_MapIndex;
  7472. o->type = t->Map.value;
  7473. o->expr = node;
  7474. add_package_dependency(c, "runtime", "__dynamic_map_get");
  7475. add_package_dependency(c, "runtime", "__dynamic_map_set");
  7476. return Expr_Expr;
  7477. }
  7478. i64 max_count = -1;
  7479. bool valid = check_set_index_data(o, t, is_ptr, &max_count, o->type);
  7480. if (is_const) {
  7481. if (is_type_array(t)) {
  7482. // OKay
  7483. } else if (is_type_slice(t)) {
  7484. // Okay
  7485. } else if (is_type_enumerated_array(t)) {
  7486. // Okay
  7487. } else if (is_type_string(t)) {
  7488. // Okay
  7489. } else if (is_type_relative_slice(t)) {
  7490. // Okay
  7491. } else if (is_type_matrix(t)) {
  7492. // Okay
  7493. } else {
  7494. valid = false;
  7495. }
  7496. }
  7497. if (!valid) {
  7498. gbString str = expr_to_string(o->expr);
  7499. gbString type_str = type_to_string(o->type);
  7500. defer (gb_string_free(str));
  7501. defer (gb_string_free(type_str));
  7502. if (is_const) {
  7503. error(o->expr, "Cannot index constant '%s' of type '%s'", str, type_str);
  7504. } else {
  7505. error(o->expr, "Cannot index '%s' of type '%s'", str, type_str);
  7506. }
  7507. o->mode = Addressing_Invalid;
  7508. o->expr = node;
  7509. return kind;
  7510. }
  7511. if (ie->index == nullptr) {
  7512. gbString str = expr_to_string(o->expr);
  7513. error(o->expr, "Missing index for '%s'", str);
  7514. gb_string_free(str);
  7515. o->mode = Addressing_Invalid;
  7516. o->expr = node;
  7517. return kind;
  7518. }
  7519. Type *index_type_hint = nullptr;
  7520. if (is_type_enumerated_array(t)) {
  7521. Type *bt = base_type(t);
  7522. GB_ASSERT(bt->kind == Type_EnumeratedArray);
  7523. index_type_hint = bt->EnumeratedArray.index;
  7524. }
  7525. i64 index = 0;
  7526. bool ok = check_index_value(c, t, false, ie->index, max_count, &index, index_type_hint);
  7527. if (is_const) {
  7528. if (index < 0) {
  7529. gbString str = expr_to_string(o->expr);
  7530. error(o->expr, "Cannot index a constant '%s'", str);
  7531. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7532. gb_string_free(str);
  7533. o->mode = Addressing_Invalid;
  7534. o->expr = node;
  7535. return kind;
  7536. } else if (ok) {
  7537. ExactValue value = type_and_value_of_expr(ie->expr).value;
  7538. o->mode = Addressing_Constant;
  7539. bool success = false;
  7540. bool finish = false;
  7541. o->value = get_constant_field_single(c, value, cast(i32)index, &success, &finish);
  7542. if (!success) {
  7543. gbString str = expr_to_string(o->expr);
  7544. error(o->expr, "Cannot index a constant '%s' with index %lld", str, cast(long long)index);
  7545. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7546. gb_string_free(str);
  7547. o->mode = Addressing_Invalid;
  7548. o->expr = node;
  7549. return kind;
  7550. }
  7551. }
  7552. }
  7553. if (type_hint != nullptr && is_type_matrix(t)) {
  7554. // TODO(bill): allow matrix columns to be assignable to other types which are the same internally
  7555. // if a type hint exists
  7556. }
  7557. case_end;
  7558. case_ast_node(se, SliceExpr, node);
  7559. check_expr(c, o, se->expr);
  7560. node->viral_state_flags |= se->expr->viral_state_flags;
  7561. if (o->mode == Addressing_Invalid) {
  7562. o->mode = Addressing_Invalid;
  7563. o->expr = node;
  7564. return kind;
  7565. }
  7566. bool valid = false;
  7567. i64 max_count = -1;
  7568. Type *t = base_type(type_deref(o->type));
  7569. switch (t->kind) {
  7570. case Type_Basic:
  7571. if (t->Basic.kind == Basic_string || t->Basic.kind == Basic_UntypedString) {
  7572. valid = true;
  7573. if (o->mode == Addressing_Constant) {
  7574. max_count = o->value.value_string.len;
  7575. }
  7576. o->type = type_deref(o->type);
  7577. }
  7578. break;
  7579. case Type_Array:
  7580. valid = true;
  7581. max_count = t->Array.count;
  7582. if (o->mode != Addressing_Variable && !is_type_pointer(o->type)) {
  7583. gbString str = expr_to_string(node);
  7584. error(node, "Cannot slice array '%s', value is not addressable", str);
  7585. gb_string_free(str);
  7586. o->mode = Addressing_Invalid;
  7587. o->expr = node;
  7588. return kind;
  7589. }
  7590. o->type = alloc_type_slice(t->Array.elem);
  7591. break;
  7592. case Type_MultiPointer:
  7593. valid = true;
  7594. o->type = type_deref(o->type);
  7595. break;
  7596. case Type_Slice:
  7597. valid = true;
  7598. o->type = type_deref(o->type);
  7599. break;
  7600. case Type_DynamicArray:
  7601. valid = true;
  7602. o->type = alloc_type_slice(t->DynamicArray.elem);
  7603. break;
  7604. case Type_Struct:
  7605. if (is_type_soa_struct(t)) {
  7606. valid = true;
  7607. o->type = make_soa_struct_slice(c, nullptr, nullptr, t->Struct.soa_elem);
  7608. }
  7609. break;
  7610. case Type_RelativeSlice:
  7611. valid = true;
  7612. o->type = t->RelativeSlice.slice_type;
  7613. if (o->mode != Addressing_Variable) {
  7614. gbString str = expr_to_string(node);
  7615. error(node, "Cannot relative slice '%s', value is not addressable", str);
  7616. gb_string_free(str);
  7617. o->mode = Addressing_Invalid;
  7618. o->expr = node;
  7619. return kind;
  7620. }
  7621. break;
  7622. }
  7623. if (!valid) {
  7624. gbString str = expr_to_string(o->expr);
  7625. gbString type_str = type_to_string(o->type);
  7626. error(o->expr, "Cannot slice '%s' of type '%s'", str, type_str);
  7627. gb_string_free(type_str);
  7628. gb_string_free(str);
  7629. o->mode = Addressing_Invalid;
  7630. o->expr = node;
  7631. return kind;
  7632. }
  7633. if (se->low == nullptr && se->high != nullptr) {
  7634. // It is okay to continue as it will assume the 1st index is zero
  7635. }
  7636. i64 indices[2] = {};
  7637. Ast *nodes[2] = {se->low, se->high};
  7638. for (isize i = 0; i < gb_count_of(nodes); i++) {
  7639. i64 index = max_count;
  7640. if (nodes[i] != nullptr) {
  7641. i64 capacity = -1;
  7642. if (max_count >= 0) {
  7643. capacity = max_count;
  7644. }
  7645. i64 j = 0;
  7646. if (check_index_value(c, t, true, nodes[i], capacity, &j)) {
  7647. index = j;
  7648. }
  7649. node->viral_state_flags |= nodes[i]->viral_state_flags;
  7650. } else if (i == 0) {
  7651. index = 0;
  7652. }
  7653. indices[i] = index;
  7654. }
  7655. for (isize i = 0; i < gb_count_of(indices); i++) {
  7656. i64 a = indices[i];
  7657. for (isize j = i+1; j < gb_count_of(indices); j++) {
  7658. i64 b = indices[j];
  7659. if (a > b && b >= 0) {
  7660. error(se->close, "Invalid slice indices: [%td > %td]", a, b);
  7661. }
  7662. }
  7663. }
  7664. if (max_count < 0) {
  7665. if (o->mode == Addressing_Constant) {
  7666. gbString s = expr_to_string(se->expr);
  7667. error(se->expr, "Cannot slice constant value '%s'", s);
  7668. gb_string_free(s);
  7669. }
  7670. }
  7671. if (t->kind == Type_MultiPointer && se->high != nullptr) {
  7672. /*
  7673. x[:] -> [^]T
  7674. x[i:] -> [^]T
  7675. x[:n] -> []T
  7676. x[i:n] -> []T
  7677. */
  7678. o->type = alloc_type_slice(t->MultiPointer.elem);
  7679. }
  7680. o->mode = Addressing_Value;
  7681. if (is_type_string(t) && max_count >= 0) {
  7682. bool all_constant = true;
  7683. for (isize i = 0; i < gb_count_of(nodes); i++) {
  7684. if (nodes[i] != nullptr) {
  7685. TypeAndValue tav = type_and_value_of_expr(nodes[i]);
  7686. if (tav.mode != Addressing_Constant) {
  7687. all_constant = false;
  7688. break;
  7689. }
  7690. }
  7691. }
  7692. if (!all_constant) {
  7693. gbString str = expr_to_string(o->expr);
  7694. error(o->expr, "Cannot slice '%s' with non-constant indices", str);
  7695. error_line("\tSuggestion: store the constant into a variable in order to index it with a variable index\n");
  7696. gb_string_free(str);
  7697. o->mode = Addressing_Value; // NOTE(bill): Keep subsequent values going without erring
  7698. o->expr = node;
  7699. return kind;
  7700. }
  7701. String s = {};
  7702. if (o->value.kind == ExactValue_String) {
  7703. s = o->value.value_string;
  7704. }
  7705. o->mode = Addressing_Constant;
  7706. o->type = t;
  7707. o->value = exact_value_string(substring(s, cast(isize)indices[0], cast(isize)indices[1]));
  7708. }
  7709. case_end;
  7710. case_ast_node(mie, MatrixIndexExpr, node);
  7711. check_matrix_index_expr(c, o, node, type_hint);
  7712. o->expr = node;
  7713. return Expr_Expr;
  7714. case_end;
  7715. case_ast_node(ce, CallExpr, node);
  7716. return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint);
  7717. case_end;
  7718. case_ast_node(de, DerefExpr, node);
  7719. check_expr_or_type(c, o, de->expr);
  7720. node->viral_state_flags |= de->expr->viral_state_flags;
  7721. if (o->mode == Addressing_Invalid) {
  7722. o->mode = Addressing_Invalid;
  7723. o->expr = node;
  7724. return kind;
  7725. } else {
  7726. Type *t = base_type(o->type);
  7727. if (t->kind == Type_Pointer && !is_type_empty_union(t->Pointer.elem)) {
  7728. o->mode = Addressing_Variable;
  7729. o->type = t->Pointer.elem;
  7730. } else if (t->kind == Type_RelativePointer) {
  7731. if (o->mode != Addressing_Variable) {
  7732. gbString str = expr_to_string(o->expr);
  7733. gbString typ = type_to_string(o->type);
  7734. error(o->expr, "Cannot dereference relative pointer '%s' of type '%s' as it does not have a variable addressing mode", str, typ);
  7735. gb_string_free(typ);
  7736. gb_string_free(str);
  7737. }
  7738. // NOTE(bill): This is required because when dereferencing, the original type has been lost
  7739. add_type_info_type(c, o->type);
  7740. Type *ptr_type = base_type(t->RelativePointer.pointer_type);
  7741. GB_ASSERT(ptr_type->kind == Type_Pointer);
  7742. o->mode = Addressing_Variable;
  7743. o->type = ptr_type->Pointer.elem;
  7744. } else {
  7745. gbString str = expr_to_string(o->expr);
  7746. gbString typ = type_to_string(o->type);
  7747. error(o->expr, "Cannot dereference '%s' of type '%s'", str, typ);
  7748. gb_string_free(typ);
  7749. gb_string_free(str);
  7750. o->mode = Addressing_Invalid;
  7751. o->expr = node;
  7752. return kind;
  7753. }
  7754. }
  7755. case_end;
  7756. case_ast_node(ia, InlineAsmExpr, node);
  7757. if (c->curr_proc_decl == nullptr) {
  7758. error(node, "Inline asm expressions are only allowed within a procedure body");
  7759. }
  7760. auto param_types = array_make<Type *>(heap_allocator(), ia->param_types.count);
  7761. Type *return_type = nullptr;
  7762. for_array(i, ia->param_types) {
  7763. param_types[i] = check_type(c, ia->param_types[i]);
  7764. }
  7765. if (ia->return_type != nullptr) {
  7766. return_type = check_type(c, ia->return_type);
  7767. }
  7768. Operand x = {};
  7769. check_expr(c, &x, ia->asm_string);
  7770. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  7771. error(x.expr, "Expected a constant string for the inline asm main parameter");
  7772. }
  7773. check_expr(c, &x, ia->constraints_string);
  7774. if (x.mode != Addressing_Constant || !is_type_string(x.type)) {
  7775. error(x.expr, "Expected a constant string for the inline asm constraints parameter");
  7776. }
  7777. Scope *scope = create_scope(c->info, c->scope);
  7778. scope->flags |= ScopeFlag_Proc;
  7779. Type *params = alloc_type_tuple();
  7780. Type *results = alloc_type_tuple();
  7781. if (param_types.count != 0) {
  7782. slice_init(&params->Tuple.variables, heap_allocator(), param_types.count);
  7783. for_array(i, param_types) {
  7784. params->Tuple.variables[i] = alloc_entity_param(scope, blank_token, param_types[i], false, true);
  7785. }
  7786. }
  7787. if (return_type != nullptr) {
  7788. slice_init(&results->Tuple.variables, heap_allocator(), 1);
  7789. results->Tuple.variables[0] = alloc_entity_param(scope, blank_token, return_type, false, true);
  7790. }
  7791. Type *pt = alloc_type_proc(scope, params, param_types.count, results, return_type != nullptr ? 1 : 0, false, ProcCC_InlineAsm);
  7792. o->type = pt;
  7793. o->mode = Addressing_Value;
  7794. o->expr = node;
  7795. return Expr_Expr;
  7796. case_end;
  7797. case Ast_TypeidType:
  7798. case Ast_PolyType:
  7799. case Ast_ProcType:
  7800. case Ast_PointerType:
  7801. case Ast_MultiPointerType:
  7802. case Ast_ArrayType:
  7803. case Ast_DynamicArrayType:
  7804. case Ast_StructType:
  7805. case Ast_UnionType:
  7806. case Ast_EnumType:
  7807. case Ast_MapType:
  7808. case Ast_BitSetType:
  7809. case Ast_MatrixType:
  7810. o->mode = Addressing_Type;
  7811. o->type = check_type(c, node);
  7812. break;
  7813. }
  7814. kind = Expr_Expr;
  7815. o->expr = node;
  7816. return kind;
  7817. }
  7818. ExprKind check_expr_base(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) {
  7819. ExprKind kind = check_expr_base_internal(c, o, node, type_hint);
  7820. if (o->type != nullptr && core_type(o->type) == nullptr) {
  7821. o->type = t_invalid;
  7822. gbString xs = expr_to_string(o->expr);
  7823. if (o->mode == Addressing_Type) {
  7824. error(o->expr, "Invalid type usage '%s'", xs);
  7825. } else {
  7826. error(o->expr, "Invalid expression '%s'", xs);
  7827. }
  7828. gb_string_free(xs);
  7829. }
  7830. if (o->type != nullptr && is_type_untyped(o->type)) {
  7831. add_untyped(c, node, o->mode, o->type, o->value);
  7832. }
  7833. add_type_and_value(c->info, node, o->mode, o->type, o->value);
  7834. return kind;
  7835. }
  7836. void check_multi_expr_or_type(CheckerContext *c, Operand *o, Ast *e) {
  7837. check_expr_base(c, o, e, nullptr);
  7838. switch (o->mode) {
  7839. default:
  7840. return; // NOTE(bill): Valid
  7841. case Addressing_NoValue:
  7842. error_operand_no_value(o);
  7843. break;
  7844. }
  7845. o->mode = Addressing_Invalid;
  7846. }
  7847. void check_multi_expr(CheckerContext *c, Operand *o, Ast *e) {
  7848. check_expr_base(c, o, e, nullptr);
  7849. switch (o->mode) {
  7850. default:
  7851. return; // NOTE(bill): Valid
  7852. case Addressing_NoValue:
  7853. error_operand_no_value(o);
  7854. break;
  7855. case Addressing_Type:
  7856. error_operand_not_expression(o);
  7857. break;
  7858. }
  7859. o->mode = Addressing_Invalid;
  7860. }
  7861. void check_multi_expr_with_type_hint(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  7862. check_expr_base(c, o, e, type_hint);
  7863. switch (o->mode) {
  7864. default:
  7865. return; // NOTE(bill): Valid
  7866. case Addressing_NoValue:
  7867. error_operand_no_value(o);
  7868. break;
  7869. case Addressing_Type:
  7870. error_operand_not_expression(o);
  7871. break;
  7872. }
  7873. o->mode = Addressing_Invalid;
  7874. }
  7875. void check_not_tuple(CheckerContext *c, Operand *o) {
  7876. if (o->mode == Addressing_Value) {
  7877. // NOTE(bill): Tuples are not first class thus never named
  7878. if (o->type->kind == Type_Tuple) {
  7879. isize count = o->type->Tuple.variables.count;
  7880. error(o->expr,
  7881. "%td-valued expression found where single value expected", count);
  7882. o->mode = Addressing_Invalid;
  7883. GB_ASSERT(count != 1);
  7884. }
  7885. }
  7886. }
  7887. void check_expr(CheckerContext *c, Operand *o, Ast *e) {
  7888. check_multi_expr(c, o, e);
  7889. check_not_tuple(c, o);
  7890. }
  7891. void check_expr_or_type(CheckerContext *c, Operand *o, Ast *e, Type *type_hint) {
  7892. check_expr_base(c, o, e, type_hint);
  7893. check_not_tuple(c, o);
  7894. error_operand_no_value(o);
  7895. }
  7896. bool is_exact_value_zero(ExactValue const &v) {
  7897. switch (v.kind) {
  7898. case ExactValue_Invalid:
  7899. return true;
  7900. case ExactValue_Bool:
  7901. return !v.value_bool;
  7902. case ExactValue_String:
  7903. return v.value_string.len == 0;
  7904. case ExactValue_Integer:
  7905. return big_int_is_zero(&v.value_integer);
  7906. case ExactValue_Float:
  7907. return v.value_float == 0.0;
  7908. case ExactValue_Complex:
  7909. if (v.value_complex) {
  7910. return v.value_complex->real == 0.0 && v.value_complex->imag == 0.0;
  7911. }
  7912. return true;
  7913. case ExactValue_Quaternion:
  7914. if (v.value_quaternion) {
  7915. return v.value_quaternion->real == 0.0 &&
  7916. v.value_quaternion->imag == 0.0 &&
  7917. v.value_quaternion->jmag == 0.0 &&
  7918. v.value_quaternion->kmag == 0.0;
  7919. }
  7920. return true;
  7921. case ExactValue_Pointer:
  7922. return v.value_pointer == 0;
  7923. case ExactValue_Compound:
  7924. if (v.value_compound == nullptr) {
  7925. return true;
  7926. } else {
  7927. ast_node(cl, CompoundLit, v.value_compound);
  7928. if (cl->elems.count == 0) {
  7929. return true;
  7930. } else {
  7931. for_array(i, cl->elems) {
  7932. Ast *elem = cl->elems[i];
  7933. if (elem->tav.mode != Addressing_Constant) {
  7934. // if (elem->tav.value.kind != ExactValue_Invalid) {
  7935. return false;
  7936. // }
  7937. }
  7938. if (!is_exact_value_zero(elem->tav.value)) {
  7939. return false;
  7940. }
  7941. }
  7942. return true;
  7943. }
  7944. }
  7945. case ExactValue_Procedure:
  7946. return v.value_procedure == nullptr;
  7947. case ExactValue_Typeid:
  7948. return v.value_typeid == nullptr;
  7949. }
  7950. return true;
  7951. }
  7952. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand);
  7953. gbString write_struct_fields_to_string(gbString str, Slice<Ast *> const &params) {
  7954. for_array(i, params) {
  7955. if (i > 0) {
  7956. str = gb_string_appendc(str, ", ");
  7957. }
  7958. str = write_expr_to_string(str, params[i], false);
  7959. }
  7960. return str;
  7961. }
  7962. gbString string_append_string(gbString str, String string) {
  7963. if (string.len > 0) {
  7964. return gb_string_append_length(str, &string[0], string.len);
  7965. }
  7966. return str;
  7967. }
  7968. gbString string_append_token(gbString str, Token token) {
  7969. str = string_append_string(str, token.string);
  7970. return str;
  7971. }
  7972. gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) {
  7973. if (node == nullptr)
  7974. return str;
  7975. if (is_ast_stmt(node)) {
  7976. GB_ASSERT("stmt passed to write_expr_to_string");
  7977. }
  7978. switch (node->kind) {
  7979. default:
  7980. str = gb_string_appendc(str, "(BadExpr)");
  7981. break;
  7982. case_ast_node(i, Ident, node);
  7983. str = string_append_token(str, i->token);
  7984. case_end;
  7985. case_ast_node(i, Implicit, node);
  7986. str = string_append_token(str, *i);
  7987. case_end;
  7988. case_ast_node(bl, BasicLit, node);
  7989. str = string_append_token(str, bl->token);
  7990. case_end;
  7991. case_ast_node(bd, BasicDirective, node);
  7992. str = gb_string_append_rune(str, '#');
  7993. str = string_append_string(str, bd->name.string);
  7994. case_end;
  7995. case_ast_node(ud, Undef, node);
  7996. str = gb_string_appendc(str, "---");
  7997. case_end;
  7998. case_ast_node(pg, ProcGroup, node);
  7999. str = gb_string_appendc(str, "proc{");
  8000. for_array(i, pg->args) {
  8001. if (i > 0) str = gb_string_appendc(str, ", ");
  8002. str = write_expr_to_string(str, pg->args[i], shorthand);
  8003. }
  8004. str = gb_string_append_rune(str, '}');
  8005. case_end;
  8006. case_ast_node(pl, ProcLit, node);
  8007. str = write_expr_to_string(str, pl->type, shorthand);
  8008. if (pl->body) {
  8009. str = gb_string_appendc(str, " {...}");
  8010. } else {
  8011. str = gb_string_appendc(str, " ---");
  8012. }
  8013. case_end;
  8014. case_ast_node(cl, CompoundLit, node);
  8015. str = write_expr_to_string(str, cl->type, shorthand);
  8016. str = gb_string_append_rune(str, '{');
  8017. if (shorthand) {
  8018. str = gb_string_appendc(str, "...");
  8019. } else {
  8020. for_array(i, cl->elems) {
  8021. if (i > 0) str = gb_string_appendc(str, ", ");
  8022. str = write_expr_to_string(str, cl->elems[i], shorthand);
  8023. }
  8024. }
  8025. str = gb_string_append_rune(str, '}');
  8026. case_end;
  8027. case_ast_node(te, TagExpr, node);
  8028. str = gb_string_append_rune(str, '#');
  8029. str = string_append_token(str, te->name);
  8030. str = write_expr_to_string(str, te->expr, shorthand);
  8031. case_end;
  8032. case_ast_node(ue, UnaryExpr, node);
  8033. str = string_append_token(str, ue->op);
  8034. str = write_expr_to_string(str, ue->expr, shorthand);
  8035. case_end;
  8036. case_ast_node(de, DerefExpr, node);
  8037. str = write_expr_to_string(str, de->expr, shorthand);
  8038. str = gb_string_append_rune(str, '^');
  8039. case_end;
  8040. case_ast_node(be, BinaryExpr, node);
  8041. str = write_expr_to_string(str, be->left, shorthand);
  8042. str = gb_string_append_rune(str, ' ');
  8043. str = string_append_token(str, be->op);
  8044. str = gb_string_append_rune(str, ' ');
  8045. str = write_expr_to_string(str, be->right, shorthand);
  8046. case_end;
  8047. case_ast_node(te, TernaryIfExpr, node);
  8048. TokenPos x = ast_token(te->x).pos;
  8049. TokenPos cond = ast_token(te->cond).pos;
  8050. if (x < cond) {
  8051. str = write_expr_to_string(str, te->x, shorthand);
  8052. str = gb_string_appendc(str, " if ");
  8053. str = write_expr_to_string(str, te->cond, shorthand);
  8054. str = gb_string_appendc(str, " else ");
  8055. str = write_expr_to_string(str, te->y, shorthand);
  8056. } else {
  8057. str = write_expr_to_string(str, te->cond, shorthand);
  8058. str = gb_string_appendc(str, " ? ");
  8059. str = write_expr_to_string(str, te->x, shorthand);
  8060. str = gb_string_appendc(str, " : ");
  8061. str = write_expr_to_string(str, te->y, shorthand);
  8062. }
  8063. case_end;
  8064. case_ast_node(te, TernaryWhenExpr, node);
  8065. str = write_expr_to_string(str, te->x, shorthand);
  8066. str = gb_string_appendc(str, " when ");
  8067. str = write_expr_to_string(str, te->cond, shorthand);
  8068. str = gb_string_appendc(str, " else ");
  8069. str = write_expr_to_string(str, te->y, shorthand);
  8070. case_end;
  8071. case_ast_node(oe, OrElseExpr, node);
  8072. str = write_expr_to_string(str, oe->x, shorthand);
  8073. str = gb_string_appendc(str, " or_else ");
  8074. str = write_expr_to_string(str, oe->y, shorthand);
  8075. case_end;
  8076. case_ast_node(oe, OrReturnExpr, node);
  8077. str = write_expr_to_string(str, oe->expr, shorthand);
  8078. str = gb_string_appendc(str, " or_return");
  8079. case_end;
  8080. case_ast_node(pe, ParenExpr, node);
  8081. str = gb_string_append_rune(str, '(');
  8082. str = write_expr_to_string(str, pe->expr, shorthand);
  8083. str = gb_string_append_rune(str, ')');
  8084. case_end;
  8085. case_ast_node(se, SelectorExpr, node);
  8086. str = write_expr_to_string(str, se->expr, shorthand);
  8087. str = string_append_token(str, se->token);
  8088. str = write_expr_to_string(str, se->selector, shorthand);
  8089. case_end;
  8090. case_ast_node(se, ImplicitSelectorExpr, node);
  8091. str = gb_string_append_rune(str, '.');
  8092. str = write_expr_to_string(str, se->selector, shorthand);
  8093. case_end;
  8094. case_ast_node(se, SelectorCallExpr, node);
  8095. str = write_expr_to_string(str, se->expr, shorthand);
  8096. str = gb_string_appendc(str, "(");
  8097. ast_node(ce, CallExpr, se->call);
  8098. isize start = se->modified_call ? 1 : 0;
  8099. for (isize i = start; i < ce->args.count; i++) {
  8100. Ast *arg = ce->args[i];
  8101. if (i > start) {
  8102. str = gb_string_appendc(str, ", ");
  8103. }
  8104. str = write_expr_to_string(str, arg, shorthand);
  8105. }
  8106. str = gb_string_appendc(str, ")");
  8107. case_end;
  8108. case_ast_node(ta, TypeAssertion, node);
  8109. str = write_expr_to_string(str, ta->expr, shorthand);
  8110. if (ta->type != nullptr &&
  8111. ta->type->kind == Ast_UnaryExpr &&
  8112. ta->type->UnaryExpr.op.kind == Token_Question) {
  8113. str = gb_string_appendc(str, ".?");
  8114. } else {
  8115. str = gb_string_appendc(str, ".(");
  8116. str = write_expr_to_string(str, ta->type, shorthand);
  8117. str = gb_string_append_rune(str, ')');
  8118. }
  8119. case_end;
  8120. case_ast_node(tc, TypeCast, node);
  8121. str = string_append_token(str, tc->token);
  8122. str = gb_string_append_rune(str, '(');
  8123. str = write_expr_to_string(str, tc->type, shorthand);
  8124. str = gb_string_append_rune(str, ')');
  8125. str = write_expr_to_string(str, tc->expr, shorthand);
  8126. case_end;
  8127. case_ast_node(ac, AutoCast, node);
  8128. str = string_append_token(str, ac->token);
  8129. str = gb_string_append_rune(str, ' ');
  8130. str = write_expr_to_string(str, ac->expr, shorthand);
  8131. case_end;
  8132. case_ast_node(ie, IndexExpr, node);
  8133. str = write_expr_to_string(str, ie->expr, shorthand);
  8134. str = gb_string_append_rune(str, '[');
  8135. str = write_expr_to_string(str, ie->index, shorthand);
  8136. str = gb_string_append_rune(str, ']');
  8137. case_end;
  8138. case_ast_node(se, SliceExpr, node);
  8139. str = write_expr_to_string(str, se->expr, shorthand);
  8140. str = gb_string_append_rune(str, '[');
  8141. str = write_expr_to_string(str, se->low, shorthand);
  8142. str = string_append_token(str, se->interval);
  8143. str = write_expr_to_string(str, se->high, shorthand);
  8144. str = gb_string_append_rune(str, ']');
  8145. case_end;
  8146. case_ast_node(mie, MatrixIndexExpr, node);
  8147. str = write_expr_to_string(str, mie->expr, shorthand);
  8148. str = gb_string_append_rune(str, '[');
  8149. str = write_expr_to_string(str, mie->row_index, shorthand);
  8150. str = gb_string_appendc(str, ", ");
  8151. str = write_expr_to_string(str, mie->column_index, shorthand);
  8152. str = gb_string_append_rune(str, ']');
  8153. case_end;
  8154. case_ast_node(e, Ellipsis, node);
  8155. str = gb_string_appendc(str, "..");
  8156. str = write_expr_to_string(str, e->expr, shorthand);
  8157. case_end;
  8158. case_ast_node(fv, FieldValue, node);
  8159. str = write_expr_to_string(str, fv->field, shorthand);
  8160. str = gb_string_appendc(str, " = ");
  8161. str = write_expr_to_string(str, fv->value, shorthand);
  8162. case_end;
  8163. case_ast_node(ht, HelperType, node);
  8164. str = gb_string_appendc(str, "#type ");
  8165. str = write_expr_to_string(str, ht->type, shorthand);
  8166. case_end;
  8167. case_ast_node(ht, DistinctType, node);
  8168. str = gb_string_appendc(str, "distinct ");
  8169. str = write_expr_to_string(str, ht->type, shorthand);
  8170. case_end;
  8171. case_ast_node(pt, PolyType, node);
  8172. str = gb_string_append_rune(str, '$');
  8173. str = write_expr_to_string(str, pt->type, shorthand);
  8174. if (pt->specialization != nullptr) {
  8175. str = gb_string_append_rune(str, '/');
  8176. str = write_expr_to_string(str, pt->specialization, shorthand);
  8177. }
  8178. case_end;
  8179. case_ast_node(pt, PointerType, node);
  8180. str = gb_string_append_rune(str, '^');
  8181. str = write_expr_to_string(str, pt->type, shorthand);
  8182. case_end;
  8183. case_ast_node(pt, MultiPointerType, node);
  8184. str = gb_string_appendc(str, "[^]");
  8185. str = write_expr_to_string(str, pt->type, shorthand);
  8186. case_end;
  8187. case_ast_node(at, ArrayType, node);
  8188. str = gb_string_append_rune(str, '[');
  8189. if (at->count != nullptr &&
  8190. at->count->kind == Ast_UnaryExpr &&
  8191. at->count->UnaryExpr.op.kind == Token_Question) {
  8192. str = gb_string_appendc(str, "?");
  8193. } else {
  8194. str = write_expr_to_string(str, at->count, shorthand);
  8195. }
  8196. str = gb_string_append_rune(str, ']');
  8197. str = write_expr_to_string(str, at->elem, shorthand);
  8198. case_end;
  8199. case_ast_node(at, DynamicArrayType, node);
  8200. str = gb_string_appendc(str, "[dynamic]");
  8201. str = write_expr_to_string(str, at->elem, shorthand);
  8202. case_end;
  8203. case_ast_node(bs, BitSetType, node);
  8204. str = gb_string_appendc(str, "bit_set[");
  8205. str = write_expr_to_string(str, bs->elem, shorthand);
  8206. str = gb_string_appendc(str, "]");
  8207. case_end;
  8208. case_ast_node(mt, MapType, node);
  8209. str = gb_string_appendc(str, "map[");
  8210. str = write_expr_to_string(str, mt->key, shorthand);
  8211. str = gb_string_append_rune(str, ']');
  8212. str = write_expr_to_string(str, mt->value, shorthand);
  8213. case_end;
  8214. case_ast_node(mt, MatrixType, node);
  8215. str = gb_string_appendc(str, "matrix[");
  8216. str = write_expr_to_string(str, mt->row_count, shorthand);
  8217. str = gb_string_appendc(str, ", ");
  8218. str = write_expr_to_string(str, mt->column_count, shorthand);
  8219. str = gb_string_append_rune(str, ']');
  8220. str = write_expr_to_string(str, mt->elem, shorthand);
  8221. case_end;
  8222. case_ast_node(f, Field, node);
  8223. if (f->flags&FieldFlag_using) {
  8224. str = gb_string_appendc(str, "using ");
  8225. }
  8226. if (f->flags&FieldFlag_no_alias) {
  8227. str = gb_string_appendc(str, "#no_alias ");
  8228. }
  8229. if (f->flags&FieldFlag_c_vararg) {
  8230. str = gb_string_appendc(str, "#c_vararg ");
  8231. }
  8232. if (f->flags&FieldFlag_auto_cast) {
  8233. str = gb_string_appendc(str, "auto_cast ");
  8234. }
  8235. if (f->flags&FieldFlag_any_int) {
  8236. str = gb_string_appendc(str, "#any_int ");
  8237. }
  8238. if (f->flags&FieldFlag_const) {
  8239. str = gb_string_appendc(str, "#const ");
  8240. }
  8241. for_array(i, f->names) {
  8242. Ast *name = f->names[i];
  8243. if (i > 0) str = gb_string_appendc(str, ", ");
  8244. str = write_expr_to_string(str, name, shorthand);
  8245. }
  8246. if (f->names.count > 0) {
  8247. if (f->type == nullptr && f->default_value != nullptr) {
  8248. str = gb_string_append_rune(str, ' ');
  8249. }
  8250. str = gb_string_appendc(str, ":");
  8251. }
  8252. if (f->type != nullptr) {
  8253. str = gb_string_append_rune(str, ' ');
  8254. str = write_expr_to_string(str, f->type, shorthand);
  8255. }
  8256. if (f->default_value != nullptr) {
  8257. if (f->type != nullptr) {
  8258. str = gb_string_append_rune(str, ' ');
  8259. }
  8260. str = gb_string_appendc(str, "= ");
  8261. str = write_expr_to_string(str, f->default_value, shorthand);
  8262. }
  8263. case_end;
  8264. case_ast_node(f, FieldList, node);
  8265. bool has_name = false;
  8266. for_array(i, f->list) {
  8267. ast_node(field, Field, f->list[i]);
  8268. if (field->names.count > 1) {
  8269. has_name = true;
  8270. break;
  8271. }
  8272. if (field->names.count == 0) {
  8273. continue;
  8274. }
  8275. if (!is_blank_ident(field->names[0])) {
  8276. has_name = true;
  8277. break;
  8278. }
  8279. }
  8280. for_array(i, f->list) {
  8281. if (i > 0) str = gb_string_appendc(str, ", ");
  8282. if (has_name) {
  8283. str = write_expr_to_string(str, f->list[i], shorthand);
  8284. } else {
  8285. ast_node(field, Field, f->list[i]);
  8286. if (field->flags&FieldFlag_using) {
  8287. str = gb_string_appendc(str, "using ");
  8288. }
  8289. if (field->flags&FieldFlag_no_alias) {
  8290. str = gb_string_appendc(str, "#no_alias ");
  8291. }
  8292. if (field->flags&FieldFlag_c_vararg) {
  8293. str = gb_string_appendc(str, "#c_vararg ");
  8294. }
  8295. str = write_expr_to_string(str, field->type, shorthand);
  8296. }
  8297. }
  8298. case_end;
  8299. case_ast_node(ce, CallExpr, node);
  8300. switch (ce->inlining) {
  8301. case ProcInlining_inline:
  8302. str = gb_string_appendc(str, "#force_inline ");
  8303. break;
  8304. case ProcInlining_no_inline:
  8305. str = gb_string_appendc(str, "#force_no_inline ");
  8306. break;
  8307. }
  8308. str = write_expr_to_string(str, ce->proc, shorthand);
  8309. str = gb_string_appendc(str, "(");
  8310. for_array(i, ce->args) {
  8311. Ast *arg = ce->args[i];
  8312. if (i > 0) {
  8313. str = gb_string_appendc(str, ", ");
  8314. }
  8315. str = write_expr_to_string(str, arg, shorthand);
  8316. }
  8317. str = gb_string_appendc(str, ")");
  8318. case_end;
  8319. case_ast_node(tt, TypeidType, node);
  8320. str = gb_string_appendc(str, "typeid");
  8321. if (tt->specialization) {
  8322. str = gb_string_appendc(str, "/");
  8323. str = write_expr_to_string(str, tt->specialization, shorthand);
  8324. }
  8325. case_end;
  8326. case_ast_node(pt, ProcType, node);
  8327. str = gb_string_appendc(str, "proc(");
  8328. str = write_expr_to_string(str, pt->params, shorthand);
  8329. str = gb_string_appendc(str, ")");
  8330. if (pt->results != nullptr) {
  8331. str = gb_string_appendc(str, " -> ");
  8332. bool parens_needed = false;
  8333. if (pt->results && pt->results->kind == Ast_FieldList) {
  8334. for_array(i, pt->results->FieldList.list) {
  8335. Ast *field = pt->results->FieldList.list[i];
  8336. ast_node(f, Field, field);
  8337. if (f->names.count != 0) {
  8338. parens_needed = true;
  8339. break;
  8340. }
  8341. }
  8342. }
  8343. if (parens_needed) {
  8344. str = gb_string_append_rune(str, '(');
  8345. }
  8346. str = write_expr_to_string(str, pt->results, shorthand);
  8347. if (parens_needed) {
  8348. str = gb_string_append_rune(str, ')');
  8349. }
  8350. }
  8351. case_end;
  8352. case_ast_node(st, StructType, node);
  8353. str = gb_string_appendc(str, "struct ");
  8354. if (st->polymorphic_params) {
  8355. str = gb_string_append_rune(str, '(');
  8356. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  8357. str = gb_string_appendc(str, ") ");
  8358. }
  8359. if (st->is_packed) str = gb_string_appendc(str, "#packed ");
  8360. if (st->is_raw_union) str = gb_string_appendc(str, "#raw_union ");
  8361. if (st->align) {
  8362. str = gb_string_appendc(str, "#align ");
  8363. str = write_expr_to_string(str, st->align, shorthand);
  8364. str = gb_string_append_rune(str, ' ');
  8365. }
  8366. str = gb_string_append_rune(str, '{');
  8367. if (shorthand) {
  8368. str = gb_string_appendc(str, "...");
  8369. } else {
  8370. str = write_struct_fields_to_string(str, st->fields);
  8371. }
  8372. str = gb_string_append_rune(str, '}');
  8373. case_end;
  8374. case_ast_node(st, UnionType, node);
  8375. str = gb_string_appendc(str, "union ");
  8376. if (st->polymorphic_params) {
  8377. str = gb_string_append_rune(str, '(');
  8378. str = write_expr_to_string(str, st->polymorphic_params, shorthand);
  8379. str = gb_string_appendc(str, ") ");
  8380. }
  8381. if (st->no_nil) str = gb_string_appendc(str, "#no_nil ");
  8382. if (st->maybe) str = gb_string_appendc(str, "#maybe ");
  8383. if (st->align) {
  8384. str = gb_string_appendc(str, "#align ");
  8385. str = write_expr_to_string(str, st->align, shorthand);
  8386. str = gb_string_append_rune(str, ' ');
  8387. }
  8388. str = gb_string_append_rune(str, '{');
  8389. if (shorthand) {
  8390. str = gb_string_appendc(str, "...");
  8391. } else {
  8392. str = write_struct_fields_to_string(str, st->variants);
  8393. }
  8394. str = gb_string_append_rune(str, '}');
  8395. case_end;
  8396. case_ast_node(et, EnumType, node);
  8397. str = gb_string_appendc(str, "enum ");
  8398. if (et->base_type != nullptr) {
  8399. str = write_expr_to_string(str, et->base_type, shorthand);
  8400. str = gb_string_append_rune(str, ' ');
  8401. }
  8402. str = gb_string_append_rune(str, '{');
  8403. if (shorthand) {
  8404. str = gb_string_appendc(str, "...");
  8405. } else {
  8406. for_array(i, et->fields) {
  8407. if (i > 0) {
  8408. str = gb_string_appendc(str, ", ");
  8409. }
  8410. str = write_expr_to_string(str, et->fields[i], shorthand);
  8411. }
  8412. }
  8413. str = gb_string_append_rune(str, '}');
  8414. case_end;
  8415. case_ast_node(rt, RelativeType, node);
  8416. str = write_expr_to_string(str, rt->tag, shorthand);
  8417. str = gb_string_appendc(str, "" );
  8418. str = write_expr_to_string(str, rt->type, shorthand);
  8419. case_end;
  8420. case_ast_node(ia, InlineAsmExpr, node);
  8421. str = gb_string_appendc(str, "asm(");
  8422. for_array(i, ia->param_types) {
  8423. if (i > 0) {
  8424. str = gb_string_appendc(str, ", ");
  8425. }
  8426. str = write_expr_to_string(str, ia->param_types[i], shorthand);
  8427. }
  8428. str = gb_string_appendc(str, ")");
  8429. if (ia->return_type != nullptr) {
  8430. str = gb_string_appendc(str, " -> ");
  8431. str = write_expr_to_string(str, ia->return_type, shorthand);
  8432. }
  8433. if (ia->has_side_effects) {
  8434. str = gb_string_appendc(str, " #side_effects");
  8435. }
  8436. if (ia->is_align_stack) {
  8437. str = gb_string_appendc(str, " #stack_align");
  8438. }
  8439. if (ia->dialect) {
  8440. str = gb_string_appendc(str, " #");
  8441. str = gb_string_appendc(str, inline_asm_dialect_strings[ia->dialect]);
  8442. }
  8443. str = gb_string_appendc(str, " {");
  8444. if (shorthand) {
  8445. str = gb_string_appendc(str, "...");
  8446. } else {
  8447. str = write_expr_to_string(str, ia->asm_string, shorthand);
  8448. str = gb_string_appendc(str, ", ");
  8449. str = write_expr_to_string(str, ia->constraints_string, shorthand);
  8450. }
  8451. str = gb_string_appendc(str, "}");
  8452. case_end;
  8453. }
  8454. return str;
  8455. }
  8456. gbString expr_to_string(Ast *expression) {
  8457. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, false);
  8458. }
  8459. gbString expr_to_string_shorthand(Ast *expression) {
  8460. return write_expr_to_string(gb_string_make(heap_allocator(), ""), expression, true);
  8461. }