check_expr.cpp 197 KB

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