checker.py 340 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819
  1. """Mypy type checker."""
  2. from __future__ import annotations
  3. import itertools
  4. from collections import defaultdict
  5. from contextlib import contextmanager, nullcontext
  6. from typing import (
  7. AbstractSet,
  8. Callable,
  9. Dict,
  10. Final,
  11. Generic,
  12. Iterable,
  13. Iterator,
  14. Mapping,
  15. NamedTuple,
  16. Optional,
  17. Sequence,
  18. Tuple,
  19. TypeVar,
  20. Union,
  21. cast,
  22. overload,
  23. )
  24. from typing_extensions import TypeAlias as _TypeAlias
  25. import mypy.checkexpr
  26. from mypy import errorcodes as codes, message_registry, nodes, operators
  27. from mypy.binder import ConditionalTypeBinder, Frame, get_declaration
  28. from mypy.checkmember import (
  29. MemberContext,
  30. analyze_decorator_or_funcbase_access,
  31. analyze_descriptor_access,
  32. analyze_member_access,
  33. type_object_type,
  34. )
  35. from mypy.checkpattern import PatternChecker
  36. from mypy.constraints import SUPERTYPE_OF
  37. from mypy.erasetype import erase_type, erase_typevars, remove_instance_last_known_values
  38. from mypy.errorcodes import TYPE_VAR, UNUSED_AWAITABLE, UNUSED_COROUTINE, ErrorCode
  39. from mypy.errors import Errors, ErrorWatcher, report_internal_error
  40. from mypy.expandtype import expand_self_type, expand_type, expand_type_by_instance
  41. from mypy.join import join_types
  42. from mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash
  43. from mypy.maptype import map_instance_to_supertype
  44. from mypy.meet import is_overlapping_erased_types, is_overlapping_types
  45. from mypy.message_registry import ErrorMessage
  46. from mypy.messages import (
  47. SUGGESTED_TEST_FIXTURES,
  48. MessageBuilder,
  49. append_invariance_notes,
  50. format_type,
  51. format_type_bare,
  52. format_type_distinctly,
  53. make_inferred_type_note,
  54. pretty_seq,
  55. )
  56. from mypy.mro import MroError, calculate_mro
  57. from mypy.nodes import (
  58. ARG_NAMED,
  59. ARG_POS,
  60. ARG_STAR,
  61. CONTRAVARIANT,
  62. COVARIANT,
  63. FUNC_NO_INFO,
  64. GDEF,
  65. IMPLICITLY_ABSTRACT,
  66. INVARIANT,
  67. IS_ABSTRACT,
  68. LDEF,
  69. LITERAL_TYPE,
  70. MDEF,
  71. NOT_ABSTRACT,
  72. AssertStmt,
  73. AssignmentExpr,
  74. AssignmentStmt,
  75. Block,
  76. BreakStmt,
  77. BytesExpr,
  78. CallExpr,
  79. ClassDef,
  80. ComparisonExpr,
  81. Context,
  82. ContinueStmt,
  83. Decorator,
  84. DelStmt,
  85. EllipsisExpr,
  86. Expression,
  87. ExpressionStmt,
  88. FloatExpr,
  89. ForStmt,
  90. FuncBase,
  91. FuncDef,
  92. FuncItem,
  93. IfStmt,
  94. Import,
  95. ImportAll,
  96. ImportBase,
  97. ImportFrom,
  98. IndexExpr,
  99. IntExpr,
  100. LambdaExpr,
  101. ListExpr,
  102. Lvalue,
  103. MatchStmt,
  104. MemberExpr,
  105. MypyFile,
  106. NameExpr,
  107. Node,
  108. OperatorAssignmentStmt,
  109. OpExpr,
  110. OverloadedFuncDef,
  111. PassStmt,
  112. PromoteExpr,
  113. RaiseStmt,
  114. RefExpr,
  115. ReturnStmt,
  116. StarExpr,
  117. Statement,
  118. StrExpr,
  119. SymbolNode,
  120. SymbolTable,
  121. SymbolTableNode,
  122. TempNode,
  123. TryStmt,
  124. TupleExpr,
  125. TypeAlias,
  126. TypeInfo,
  127. TypeVarExpr,
  128. UnaryExpr,
  129. Var,
  130. WhileStmt,
  131. WithStmt,
  132. is_final_node,
  133. )
  134. from mypy.options import Options
  135. from mypy.patterns import AsPattern, StarredPattern
  136. from mypy.plugin import CheckerPluginInterface, Plugin
  137. from mypy.plugins import dataclasses as dataclasses_plugin
  138. from mypy.scope import Scope
  139. from mypy.semanal import is_trivial_body, refers_to_fullname, set_callable_name
  140. from mypy.semanal_enum import ENUM_BASES, ENUM_SPECIAL_PROPS
  141. from mypy.sharedparse import BINARY_MAGIC_METHODS
  142. from mypy.state import state
  143. from mypy.subtypes import (
  144. find_member,
  145. is_callable_compatible,
  146. is_equivalent,
  147. is_more_precise,
  148. is_proper_subtype,
  149. is_same_type,
  150. is_subtype,
  151. restrict_subtype_away,
  152. unify_generic_callable,
  153. )
  154. from mypy.traverser import TraverserVisitor, all_return_statements, has_return_statement
  155. from mypy.treetransform import TransformVisitor
  156. from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type, make_optional_type
  157. from mypy.typeops import (
  158. bind_self,
  159. coerce_to_literal,
  160. custom_special_method,
  161. erase_def_to_union_or_bound,
  162. erase_to_bound,
  163. erase_to_union_or_bound,
  164. false_only,
  165. fixup_partial_type,
  166. function_type,
  167. get_type_vars,
  168. is_literal_type_like,
  169. is_singleton_type,
  170. make_simplified_union,
  171. map_type_from_supertype,
  172. true_only,
  173. try_expanding_sum_type_to_union,
  174. try_getting_int_literals_from_type,
  175. try_getting_str_literals,
  176. try_getting_str_literals_from_type,
  177. tuple_fallback,
  178. )
  179. from mypy.types import (
  180. ANY_STRATEGY,
  181. MYPYC_NATIVE_INT_NAMES,
  182. OVERLOAD_NAMES,
  183. AnyType,
  184. BoolTypeQuery,
  185. CallableType,
  186. DeletedType,
  187. ErasedType,
  188. FunctionLike,
  189. Instance,
  190. LiteralType,
  191. NoneType,
  192. Overloaded,
  193. PartialType,
  194. ProperType,
  195. TupleType,
  196. Type,
  197. TypeAliasType,
  198. TypedDictType,
  199. TypeGuardedType,
  200. TypeOfAny,
  201. TypeTranslator,
  202. TypeType,
  203. TypeVarId,
  204. TypeVarLikeType,
  205. TypeVarType,
  206. UnboundType,
  207. UninhabitedType,
  208. UnionType,
  209. flatten_nested_unions,
  210. get_proper_type,
  211. get_proper_types,
  212. is_literal_type,
  213. is_named_instance,
  214. )
  215. from mypy.types_utils import is_optional, remove_optional, store_argument_type, strip_type
  216. from mypy.typetraverser import TypeTraverserVisitor
  217. from mypy.typevars import fill_typevars, fill_typevars_with_any, has_no_typevars
  218. from mypy.util import is_dunder, is_sunder, is_typeshed_file
  219. from mypy.visitor import NodeVisitor
  220. T = TypeVar("T")
  221. DEFAULT_LAST_PASS: Final = 1 # Pass numbers start at 0
  222. DeferredNodeType: _TypeAlias = Union[FuncDef, LambdaExpr, OverloadedFuncDef, Decorator]
  223. FineGrainedDeferredNodeType: _TypeAlias = Union[FuncDef, MypyFile, OverloadedFuncDef]
  224. # A node which is postponed to be processed during the next pass.
  225. # In normal mode one can defer functions and methods (also decorated and/or overloaded)
  226. # and lambda expressions. Nested functions can't be deferred -- only top-level functions
  227. # and methods of classes not defined within a function can be deferred.
  228. class DeferredNode(NamedTuple):
  229. node: DeferredNodeType
  230. # And its TypeInfo (for semantic analysis self type handling
  231. active_typeinfo: TypeInfo | None
  232. # Same as above, but for fine-grained mode targets. Only top-level functions/methods
  233. # and module top levels are allowed as such.
  234. class FineGrainedDeferredNode(NamedTuple):
  235. node: FineGrainedDeferredNodeType
  236. active_typeinfo: TypeInfo | None
  237. # Data structure returned by find_isinstance_check representing
  238. # information learned from the truth or falsehood of a condition. The
  239. # dict maps nodes representing expressions like 'a[0].x' to their
  240. # refined types under the assumption that the condition has a
  241. # particular truth value. A value of None means that the condition can
  242. # never have that truth value.
  243. # NB: The keys of this dict are nodes in the original source program,
  244. # which are compared by reference equality--effectively, being *the
  245. # same* expression of the program, not just two identical expressions
  246. # (such as two references to the same variable). TODO: it would
  247. # probably be better to have the dict keyed by the nodes' literal_hash
  248. # field instead.
  249. TypeMap: _TypeAlias = Optional[Dict[Expression, Type]]
  250. # An object that represents either a precise type or a type with an upper bound;
  251. # it is important for correct type inference with isinstance.
  252. class TypeRange(NamedTuple):
  253. item: Type
  254. is_upper_bound: bool # False => precise type
  255. # Keeps track of partial types in a single scope. In fine-grained incremental
  256. # mode partial types initially defined at the top level cannot be completed in
  257. # a function, and we use the 'is_function' attribute to enforce this.
  258. class PartialTypeScope(NamedTuple):
  259. map: dict[Var, Context]
  260. is_function: bool
  261. is_local: bool
  262. class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
  263. """Mypy type checker.
  264. Type check mypy source files that have been semantically analyzed.
  265. You must create a separate instance for each source file.
  266. """
  267. # Are we type checking a stub?
  268. is_stub = False
  269. # Error message reporter
  270. errors: Errors
  271. # Utility for generating messages
  272. msg: MessageBuilder
  273. # Types of type checked nodes. The first item is the "master" type
  274. # map that will store the final, exported types. Additional items
  275. # are temporary type maps used during type inference, and these
  276. # will be eventually popped and either discarded or merged into
  277. # the master type map.
  278. #
  279. # Avoid accessing this directly, but prefer the lookup_type(),
  280. # has_type() etc. helpers instead.
  281. _type_maps: list[dict[Expression, Type]]
  282. # Helper for managing conditional types
  283. binder: ConditionalTypeBinder
  284. # Helper for type checking expressions
  285. expr_checker: mypy.checkexpr.ExpressionChecker
  286. pattern_checker: PatternChecker
  287. tscope: Scope
  288. scope: CheckerScope
  289. # Stack of function return types
  290. return_types: list[Type]
  291. # Flags; true for dynamically typed functions
  292. dynamic_funcs: list[bool]
  293. # Stack of collections of variables with partial types
  294. partial_types: list[PartialTypeScope]
  295. # Vars for which partial type errors are already reported
  296. # (to avoid logically duplicate errors with different error context).
  297. partial_reported: set[Var]
  298. globals: SymbolTable
  299. modules: dict[str, MypyFile]
  300. # Nodes that couldn't be checked because some types weren't available. We'll run
  301. # another pass and try these again.
  302. deferred_nodes: list[DeferredNode]
  303. # Type checking pass number (0 = first pass)
  304. pass_num = 0
  305. # Last pass number to take
  306. last_pass = DEFAULT_LAST_PASS
  307. # Have we deferred the current function? If yes, don't infer additional
  308. # types during this pass within the function.
  309. current_node_deferred = False
  310. # Is this file a typeshed stub?
  311. is_typeshed_stub = False
  312. options: Options
  313. # Used for collecting inferred attribute types so that they can be checked
  314. # for consistency.
  315. inferred_attribute_types: dict[Var, Type] | None = None
  316. # Don't infer partial None types if we are processing assignment from Union
  317. no_partial_types: bool = False
  318. # The set of all dependencies (suppressed or not) that this module accesses, either
  319. # directly or indirectly.
  320. module_refs: set[str]
  321. # A map from variable nodes to a snapshot of the frame ids of the
  322. # frames that were active when the variable was declared. This can
  323. # be used to determine nearest common ancestor frame of a variable's
  324. # declaration and the current frame, which lets us determine if it
  325. # was declared in a different branch of the same `if` statement
  326. # (if that frame is a conditional_frame).
  327. var_decl_frames: dict[Var, set[int]]
  328. # Plugin that provides special type checking rules for specific library
  329. # functions such as open(), etc.
  330. plugin: Plugin
  331. def __init__(
  332. self,
  333. errors: Errors,
  334. modules: dict[str, MypyFile],
  335. options: Options,
  336. tree: MypyFile,
  337. path: str,
  338. plugin: Plugin,
  339. per_line_checking_time_ns: dict[int, int],
  340. ) -> None:
  341. """Construct a type checker.
  342. Use errors to report type check errors.
  343. """
  344. self.errors = errors
  345. self.modules = modules
  346. self.options = options
  347. self.tree = tree
  348. self.path = path
  349. self.msg = MessageBuilder(errors, modules)
  350. self.plugin = plugin
  351. self.tscope = Scope()
  352. self.scope = CheckerScope(tree)
  353. self.binder = ConditionalTypeBinder()
  354. self.globals = tree.names
  355. self.return_types = []
  356. self.dynamic_funcs = []
  357. self.partial_types = []
  358. self.partial_reported = set()
  359. self.var_decl_frames = {}
  360. self.deferred_nodes = []
  361. self._type_maps = [{}]
  362. self.module_refs = set()
  363. self.pass_num = 0
  364. self.current_node_deferred = False
  365. self.is_stub = tree.is_stub
  366. self.is_typeshed_stub = is_typeshed_file(options.abs_custom_typeshed_dir, path)
  367. self.inferred_attribute_types = None
  368. # If True, process function definitions. If False, don't. This is used
  369. # for processing module top levels in fine-grained incremental mode.
  370. self.recurse_into_functions = True
  371. # This internal flag is used to track whether we a currently type-checking
  372. # a final declaration (assignment), so that some errors should be suppressed.
  373. # Should not be set manually, use get_final_context/enter_final_context instead.
  374. # NOTE: we use the context manager to avoid "threading" an additional `is_final_def`
  375. # argument through various `checker` and `checkmember` functions.
  376. self._is_final_def = False
  377. # This flag is set when we run type-check or attribute access check for the purpose
  378. # of giving a note on possibly missing "await". It is used to avoid infinite recursion.
  379. self.checking_missing_await = False
  380. # While this is True, allow passing an abstract class where Type[T] is expected.
  381. # although this is technically unsafe, this is desirable in some context, for
  382. # example when type-checking class decorators.
  383. self.allow_abstract_call = False
  384. # Child checker objects for specific AST node types
  385. self.expr_checker = mypy.checkexpr.ExpressionChecker(
  386. self, self.msg, self.plugin, per_line_checking_time_ns
  387. )
  388. self.pattern_checker = PatternChecker(self, self.msg, self.plugin, options)
  389. @property
  390. def type_context(self) -> list[Type | None]:
  391. return self.expr_checker.type_context
  392. def reset(self) -> None:
  393. """Cleanup stale state that might be left over from a typechecking run.
  394. This allows us to reuse TypeChecker objects in fine-grained
  395. incremental mode.
  396. """
  397. # TODO: verify this is still actually worth it over creating new checkers
  398. self.partial_reported.clear()
  399. self.module_refs.clear()
  400. self.binder = ConditionalTypeBinder()
  401. self._type_maps[1:] = []
  402. self._type_maps[0].clear()
  403. self.temp_type_map = None
  404. self.expr_checker.reset()
  405. assert self.inferred_attribute_types is None
  406. assert self.partial_types == []
  407. assert self.deferred_nodes == []
  408. assert len(self.scope.stack) == 1
  409. assert self.partial_types == []
  410. def check_first_pass(self) -> None:
  411. """Type check the entire file, but defer functions with unresolved references.
  412. Unresolved references are forward references to variables
  413. whose types haven't been inferred yet. They may occur later
  414. in the same file or in a different file that's being processed
  415. later (usually due to an import cycle).
  416. Deferred functions will be processed by check_second_pass().
  417. """
  418. self.recurse_into_functions = True
  419. with state.strict_optional_set(self.options.strict_optional):
  420. self.errors.set_file(
  421. self.path, self.tree.fullname, scope=self.tscope, options=self.options
  422. )
  423. with self.tscope.module_scope(self.tree.fullname):
  424. with self.enter_partial_types(), self.binder.top_frame_context():
  425. for d in self.tree.defs:
  426. if self.binder.is_unreachable():
  427. if not self.should_report_unreachable_issues():
  428. break
  429. if not self.is_noop_for_reachability(d):
  430. self.msg.unreachable_statement(d)
  431. break
  432. else:
  433. self.accept(d)
  434. assert not self.current_node_deferred
  435. all_ = self.globals.get("__all__")
  436. if all_ is not None and all_.type is not None:
  437. all_node = all_.node
  438. assert all_node is not None
  439. seq_str = self.named_generic_type(
  440. "typing.Sequence", [self.named_type("builtins.str")]
  441. )
  442. if not is_subtype(all_.type, seq_str):
  443. str_seq_s, all_s = format_type_distinctly(
  444. seq_str, all_.type, options=self.options
  445. )
  446. self.fail(
  447. message_registry.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s), all_node
  448. )
  449. def check_second_pass(
  450. self, todo: Sequence[DeferredNode | FineGrainedDeferredNode] | None = None
  451. ) -> bool:
  452. """Run second or following pass of type checking.
  453. This goes through deferred nodes, returning True if there were any.
  454. """
  455. self.recurse_into_functions = True
  456. with state.strict_optional_set(self.options.strict_optional):
  457. if not todo and not self.deferred_nodes:
  458. return False
  459. self.errors.set_file(
  460. self.path, self.tree.fullname, scope=self.tscope, options=self.options
  461. )
  462. with self.tscope.module_scope(self.tree.fullname):
  463. self.pass_num += 1
  464. if not todo:
  465. todo = self.deferred_nodes
  466. else:
  467. assert not self.deferred_nodes
  468. self.deferred_nodes = []
  469. done: set[DeferredNodeType | FineGrainedDeferredNodeType] = set()
  470. for node, active_typeinfo in todo:
  471. if node in done:
  472. continue
  473. # This is useful for debugging:
  474. # print("XXX in pass %d, class %s, function %s" %
  475. # (self.pass_num, type_name, node.fullname or node.name))
  476. done.add(node)
  477. with self.tscope.class_scope(
  478. active_typeinfo
  479. ) if active_typeinfo else nullcontext():
  480. with self.scope.push_class(
  481. active_typeinfo
  482. ) if active_typeinfo else nullcontext():
  483. self.check_partial(node)
  484. return True
  485. def check_partial(self, node: DeferredNodeType | FineGrainedDeferredNodeType) -> None:
  486. if isinstance(node, MypyFile):
  487. self.check_top_level(node)
  488. else:
  489. self.recurse_into_functions = True
  490. if isinstance(node, LambdaExpr):
  491. self.expr_checker.accept(node)
  492. else:
  493. self.accept(node)
  494. def check_top_level(self, node: MypyFile) -> None:
  495. """Check only the top-level of a module, skipping function definitions."""
  496. self.recurse_into_functions = False
  497. with self.enter_partial_types():
  498. with self.binder.top_frame_context():
  499. for d in node.defs:
  500. d.accept(self)
  501. assert not self.current_node_deferred
  502. # TODO: Handle __all__
  503. def defer_node(self, node: DeferredNodeType, enclosing_class: TypeInfo | None) -> None:
  504. """Defer a node for processing during next type-checking pass.
  505. Args:
  506. node: function/method being deferred
  507. enclosing_class: for methods, the class where the method is defined
  508. NOTE: this can't handle nested functions/methods.
  509. """
  510. # We don't freeze the entire scope since only top-level functions and methods
  511. # can be deferred. Only module/class level scope information is needed.
  512. # Module-level scope information is preserved in the TypeChecker instance.
  513. self.deferred_nodes.append(DeferredNode(node, enclosing_class))
  514. def handle_cannot_determine_type(self, name: str, context: Context) -> None:
  515. node = self.scope.top_non_lambda_function()
  516. if self.pass_num < self.last_pass and isinstance(node, FuncDef):
  517. # Don't report an error yet. Just defer. Note that we don't defer
  518. # lambdas because they are coupled to the surrounding function
  519. # through the binder and the inferred type of the lambda, so it
  520. # would get messy.
  521. enclosing_class = self.scope.enclosing_class()
  522. self.defer_node(node, enclosing_class)
  523. # Set a marker so that we won't infer additional types in this
  524. # function. Any inferred types could be bogus, because there's at
  525. # least one type that we don't know.
  526. self.current_node_deferred = True
  527. else:
  528. self.msg.cannot_determine_type(name, context)
  529. def accept(self, stmt: Statement) -> None:
  530. """Type check a node in the given type context."""
  531. try:
  532. stmt.accept(self)
  533. except Exception as err:
  534. report_internal_error(err, self.errors.file, stmt.line, self.errors, self.options)
  535. def accept_loop(
  536. self,
  537. body: Statement,
  538. else_body: Statement | None = None,
  539. *,
  540. exit_condition: Expression | None = None,
  541. ) -> None:
  542. """Repeatedly type check a loop body until the frame doesn't change.
  543. If exit_condition is set, assume it must be False on exit from the loop.
  544. Then check the else_body.
  545. """
  546. # The outer frame accumulates the results of all iterations
  547. with self.binder.frame_context(can_skip=False, conditional_frame=True):
  548. while True:
  549. with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):
  550. self.accept(body)
  551. if not self.binder.last_pop_changed:
  552. break
  553. if exit_condition:
  554. _, else_map = self.find_isinstance_check(exit_condition)
  555. self.push_type_map(else_map)
  556. if else_body:
  557. self.accept(else_body)
  558. #
  559. # Definitions
  560. #
  561. def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
  562. if not self.recurse_into_functions:
  563. return
  564. with self.tscope.function_scope(defn):
  565. self._visit_overloaded_func_def(defn)
  566. def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
  567. num_abstract = 0
  568. if not defn.items:
  569. # In this case we have already complained about none of these being
  570. # valid overloads.
  571. return None
  572. if len(defn.items) == 1:
  573. self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn)
  574. if defn.is_property:
  575. # HACK: Infer the type of the property.
  576. assert isinstance(defn.items[0], Decorator)
  577. self.visit_decorator(defn.items[0])
  578. for fdef in defn.items:
  579. assert isinstance(fdef, Decorator)
  580. self.check_func_item(fdef.func, name=fdef.func.name, allow_empty=True)
  581. if fdef.func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT):
  582. num_abstract += 1
  583. if num_abstract not in (0, len(defn.items)):
  584. self.fail(message_registry.INCONSISTENT_ABSTRACT_OVERLOAD, defn)
  585. if defn.impl:
  586. defn.impl.accept(self)
  587. if defn.info:
  588. found_method_base_classes = self.check_method_override(defn)
  589. if (
  590. defn.is_explicit_override
  591. and not found_method_base_classes
  592. and found_method_base_classes is not None
  593. ):
  594. self.msg.no_overridable_method(defn.name, defn)
  595. self.check_explicit_override_decorator(defn, found_method_base_classes, defn.impl)
  596. self.check_inplace_operator_method(defn)
  597. if not defn.is_property:
  598. self.check_overlapping_overloads(defn)
  599. return None
  600. def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:
  601. # At this point we should have set the impl already, and all remaining
  602. # items are decorators
  603. if self.msg.errors.file in self.msg.errors.ignored_files:
  604. # This is a little hacky, however, the quadratic check here is really expensive, this
  605. # method has no side effects, so we should skip it if we aren't going to report
  606. # anything. In some other places we swallow errors in stubs, but this error is very
  607. # useful for stubs!
  608. return
  609. # Compute some info about the implementation (if it exists) for use below
  610. impl_type: CallableType | None = None
  611. if defn.impl:
  612. if isinstance(defn.impl, FuncDef):
  613. inner_type: Type | None = defn.impl.type
  614. elif isinstance(defn.impl, Decorator):
  615. inner_type = defn.impl.var.type
  616. else:
  617. assert False, "Impl isn't the right type"
  618. # This can happen if we've got an overload with a different
  619. # decorator or if the implementation is untyped -- we gave up on the types.
  620. inner_type = get_proper_type(inner_type)
  621. if inner_type is not None and not isinstance(inner_type, AnyType):
  622. if isinstance(inner_type, CallableType):
  623. impl_type = inner_type
  624. elif isinstance(inner_type, Instance):
  625. inner_call = get_proper_type(
  626. analyze_member_access(
  627. name="__call__",
  628. typ=inner_type,
  629. context=defn.impl,
  630. is_lvalue=False,
  631. is_super=False,
  632. is_operator=True,
  633. msg=self.msg,
  634. original_type=inner_type,
  635. chk=self,
  636. )
  637. )
  638. if isinstance(inner_call, CallableType):
  639. impl_type = inner_call
  640. if impl_type is None:
  641. self.msg.not_callable(inner_type, defn.impl)
  642. is_descriptor_get = defn.info and defn.name == "__get__"
  643. for i, item in enumerate(defn.items):
  644. # TODO overloads involving decorators
  645. assert isinstance(item, Decorator)
  646. sig1 = self.function_type(item.func)
  647. assert isinstance(sig1, CallableType)
  648. for j, item2 in enumerate(defn.items[i + 1 :]):
  649. assert isinstance(item2, Decorator)
  650. sig2 = self.function_type(item2.func)
  651. assert isinstance(sig2, CallableType)
  652. if not are_argument_counts_overlapping(sig1, sig2):
  653. continue
  654. if overload_can_never_match(sig1, sig2):
  655. self.msg.overloaded_signature_will_never_match(i + 1, i + j + 2, item2.func)
  656. elif not is_descriptor_get:
  657. # Note: we force mypy to check overload signatures in strict-optional mode
  658. # so we don't incorrectly report errors when a user tries typing an overload
  659. # that happens to have a 'if the argument is None' fallback.
  660. #
  661. # For example, the following is fine in strict-optional mode but would throw
  662. # the unsafe overlap error when strict-optional is disabled:
  663. #
  664. # @overload
  665. # def foo(x: None) -> int: ...
  666. # @overload
  667. # def foo(x: str) -> str: ...
  668. #
  669. # See Python 2's map function for a concrete example of this kind of overload.
  670. with state.strict_optional_set(True):
  671. if is_unsafe_overlapping_overload_signatures(sig1, sig2):
  672. self.msg.overloaded_signatures_overlap(i + 1, i + j + 2, item.func)
  673. if impl_type is not None:
  674. assert defn.impl is not None
  675. # We perform a unification step that's very similar to what
  676. # 'is_callable_compatible' would have done if we had set
  677. # 'unify_generics' to True -- the only difference is that
  678. # we check and see if the impl_type's return value is a
  679. # *supertype* of the overload alternative, not a *subtype*.
  680. #
  681. # This is to match the direction the implementation's return
  682. # needs to be compatible in.
  683. if impl_type.variables:
  684. impl: CallableType | None = unify_generic_callable(
  685. # Normalize both before unifying
  686. impl_type.with_unpacked_kwargs(),
  687. sig1.with_unpacked_kwargs(),
  688. ignore_return=False,
  689. return_constraint_direction=SUPERTYPE_OF,
  690. )
  691. if impl is None:
  692. self.msg.overloaded_signatures_typevar_specific(i + 1, defn.impl)
  693. continue
  694. else:
  695. impl = impl_type
  696. # Prevent extra noise from inconsistent use of @classmethod by copying
  697. # the first arg from the method being checked against.
  698. if sig1.arg_types and defn.info:
  699. impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:])
  700. # Is the overload alternative's arguments subtypes of the implementation's?
  701. if not is_callable_compatible(
  702. impl, sig1, is_compat=is_subtype, ignore_return=True
  703. ):
  704. self.msg.overloaded_signatures_arg_specific(i + 1, defn.impl)
  705. # Is the overload alternative's return type a subtype of the implementation's?
  706. if not (
  707. is_subtype(sig1.ret_type, impl.ret_type)
  708. or is_subtype(impl.ret_type, sig1.ret_type)
  709. ):
  710. self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl)
  711. # Here's the scoop about generators and coroutines.
  712. #
  713. # There are two kinds of generators: classic generators (functions
  714. # with `yield` or `yield from` in the body) and coroutines
  715. # (functions declared with `async def`). The latter are specified
  716. # in PEP 492 and only available in Python >= 3.5.
  717. #
  718. # Classic generators can be parameterized with three types:
  719. # - ty is the Yield type (the type of y in `yield y`)
  720. # - tc is the type reCeived by yield (the type of c in `c = yield`).
  721. # - tr is the Return type (the type of r in `return r`)
  722. #
  723. # A classic generator must define a return type that's either
  724. # `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or
  725. # object or Any). If tc/tr are not given, both are None.
  726. #
  727. # A coroutine must define a return type corresponding to tr; the
  728. # other two are unconstrained. The "external" return type (seen
  729. # by the caller) is Awaitable[tr].
  730. #
  731. # In addition, there's the synthetic type AwaitableGenerator: it
  732. # inherits from both Awaitable and Generator and can be used both
  733. # in `yield from` and in `await`. This type is set automatically
  734. # for functions decorated with `@types.coroutine` or
  735. # `@asyncio.coroutine`. Its single parameter corresponds to tr.
  736. #
  737. # PEP 525 adds a new type, the asynchronous generator, which was
  738. # first released in Python 3.6. Async generators are `async def`
  739. # functions that can also `yield` values. They can be parameterized
  740. # with two types, ty and tc, because they cannot return a value.
  741. #
  742. # There are several useful methods, each taking a type t and a
  743. # flag c indicating whether it's for a generator or coroutine:
  744. #
  745. # - is_generator_return_type(t, c) returns whether t is a Generator,
  746. # Iterator, Iterable (if not c), or Awaitable (if c), or
  747. # AwaitableGenerator (regardless of c).
  748. # - is_async_generator_return_type(t) returns whether t is an
  749. # AsyncGenerator.
  750. # - get_generator_yield_type(t, c) returns ty.
  751. # - get_generator_receive_type(t, c) returns tc.
  752. # - get_generator_return_type(t, c) returns tr.
  753. def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
  754. """Is `typ` a valid type for a generator/coroutine?
  755. True if `typ` is a *supertype* of Generator or Awaitable.
  756. Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
  757. """
  758. typ = get_proper_type(typ)
  759. if is_coroutine:
  760. # This means we're in Python 3.5 or later.
  761. at = self.named_generic_type("typing.Awaitable", [AnyType(TypeOfAny.special_form)])
  762. if is_subtype(at, typ):
  763. return True
  764. else:
  765. any_type = AnyType(TypeOfAny.special_form)
  766. gt = self.named_generic_type("typing.Generator", [any_type, any_type, any_type])
  767. if is_subtype(gt, typ):
  768. return True
  769. return isinstance(typ, Instance) and typ.type.fullname == "typing.AwaitableGenerator"
  770. def is_async_generator_return_type(self, typ: Type) -> bool:
  771. """Is `typ` a valid type for an async generator?
  772. True if `typ` is a supertype of AsyncGenerator.
  773. """
  774. try:
  775. any_type = AnyType(TypeOfAny.special_form)
  776. agt = self.named_generic_type("typing.AsyncGenerator", [any_type, any_type])
  777. except KeyError:
  778. # we're running on a version of typing that doesn't have AsyncGenerator yet
  779. return False
  780. return is_subtype(agt, typ)
  781. def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type:
  782. """Given the declared return type of a generator (t), return the type it yields (ty)."""
  783. return_type = get_proper_type(return_type)
  784. if isinstance(return_type, AnyType):
  785. return AnyType(TypeOfAny.from_another_any, source_any=return_type)
  786. elif isinstance(return_type, UnionType):
  787. return make_simplified_union(
  788. [self.get_generator_yield_type(item, is_coroutine) for item in return_type.items]
  789. )
  790. elif not self.is_generator_return_type(
  791. return_type, is_coroutine
  792. ) and not self.is_async_generator_return_type(return_type):
  793. # If the function doesn't have a proper Generator (or
  794. # Awaitable) return type, anything is permissible.
  795. return AnyType(TypeOfAny.from_error)
  796. elif not isinstance(return_type, Instance):
  797. # Same as above, but written as a separate branch so the typechecker can understand.
  798. return AnyType(TypeOfAny.from_error)
  799. elif return_type.type.fullname == "typing.Awaitable":
  800. # Awaitable: ty is Any.
  801. return AnyType(TypeOfAny.special_form)
  802. elif return_type.args:
  803. # AwaitableGenerator, Generator, AsyncGenerator, Iterator, or Iterable; ty is args[0].
  804. ret_type = return_type.args[0]
  805. # TODO not best fix, better have dedicated yield token
  806. return ret_type
  807. else:
  808. # If the function's declared supertype of Generator has no type
  809. # parameters (i.e. is `object`), then the yielded values can't
  810. # be accessed so any type is acceptable. IOW, ty is Any.
  811. # (However, see https://github.com/python/mypy/issues/1933)
  812. return AnyType(TypeOfAny.special_form)
  813. def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type:
  814. """Given a declared generator return type (t), return the type its yield receives (tc)."""
  815. return_type = get_proper_type(return_type)
  816. if isinstance(return_type, AnyType):
  817. return AnyType(TypeOfAny.from_another_any, source_any=return_type)
  818. elif isinstance(return_type, UnionType):
  819. return make_simplified_union(
  820. [self.get_generator_receive_type(item, is_coroutine) for item in return_type.items]
  821. )
  822. elif not self.is_generator_return_type(
  823. return_type, is_coroutine
  824. ) and not self.is_async_generator_return_type(return_type):
  825. # If the function doesn't have a proper Generator (or
  826. # Awaitable) return type, anything is permissible.
  827. return AnyType(TypeOfAny.from_error)
  828. elif not isinstance(return_type, Instance):
  829. # Same as above, but written as a separate branch so the typechecker can understand.
  830. return AnyType(TypeOfAny.from_error)
  831. elif return_type.type.fullname == "typing.Awaitable":
  832. # Awaitable, AwaitableGenerator: tc is Any.
  833. return AnyType(TypeOfAny.special_form)
  834. elif (
  835. return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator")
  836. and len(return_type.args) >= 3
  837. ):
  838. # Generator: tc is args[1].
  839. return return_type.args[1]
  840. elif return_type.type.fullname == "typing.AsyncGenerator" and len(return_type.args) >= 2:
  841. return return_type.args[1]
  842. else:
  843. # `return_type` is a supertype of Generator, so callers won't be able to send it
  844. # values. IOW, tc is None.
  845. return NoneType()
  846. def get_coroutine_return_type(self, return_type: Type) -> Type:
  847. return_type = get_proper_type(return_type)
  848. if isinstance(return_type, AnyType):
  849. return AnyType(TypeOfAny.from_another_any, source_any=return_type)
  850. assert isinstance(return_type, Instance), "Should only be called on coroutine functions."
  851. # Note: return type is the 3rd type parameter of Coroutine.
  852. return return_type.args[2]
  853. def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type:
  854. """Given the declared return type of a generator (t), return the type it returns (tr)."""
  855. return_type = get_proper_type(return_type)
  856. if isinstance(return_type, AnyType):
  857. return AnyType(TypeOfAny.from_another_any, source_any=return_type)
  858. elif isinstance(return_type, UnionType):
  859. return make_simplified_union(
  860. [self.get_generator_return_type(item, is_coroutine) for item in return_type.items]
  861. )
  862. elif not self.is_generator_return_type(return_type, is_coroutine):
  863. # If the function doesn't have a proper Generator (or
  864. # Awaitable) return type, anything is permissible.
  865. return AnyType(TypeOfAny.from_error)
  866. elif not isinstance(return_type, Instance):
  867. # Same as above, but written as a separate branch so the typechecker can understand.
  868. return AnyType(TypeOfAny.from_error)
  869. elif return_type.type.fullname == "typing.Awaitable" and len(return_type.args) == 1:
  870. # Awaitable: tr is args[0].
  871. return return_type.args[0]
  872. elif (
  873. return_type.type.fullname in ("typing.Generator", "typing.AwaitableGenerator")
  874. and len(return_type.args) >= 3
  875. ):
  876. # AwaitableGenerator, Generator: tr is args[2].
  877. return return_type.args[2]
  878. else:
  879. # Supertype of Generator (Iterator, Iterable, object): tr is any.
  880. return AnyType(TypeOfAny.special_form)
  881. def visit_func_def(self, defn: FuncDef) -> None:
  882. if not self.recurse_into_functions:
  883. return
  884. with self.tscope.function_scope(defn):
  885. self._visit_func_def(defn)
  886. def _visit_func_def(self, defn: FuncDef) -> None:
  887. """Type check a function definition."""
  888. self.check_func_item(defn, name=defn.name)
  889. if defn.info:
  890. if not defn.is_dynamic() and not defn.is_overload and not defn.is_decorated:
  891. # If the definition is the implementation for an
  892. # overload, the legality of the override has already
  893. # been typechecked, and decorated methods will be
  894. # checked when the decorator is.
  895. found_method_base_classes = self.check_method_override(defn)
  896. self.check_explicit_override_decorator(defn, found_method_base_classes)
  897. self.check_inplace_operator_method(defn)
  898. if defn.original_def:
  899. # Override previous definition.
  900. new_type = self.function_type(defn)
  901. if isinstance(defn.original_def, FuncDef):
  902. # Function definition overrides function definition.
  903. old_type = self.function_type(defn.original_def)
  904. if not is_same_type(new_type, old_type):
  905. self.msg.incompatible_conditional_function_def(defn, old_type, new_type)
  906. else:
  907. # Function definition overrides a variable initialized via assignment or a
  908. # decorated function.
  909. orig_type = defn.original_def.type
  910. if orig_type is None:
  911. # If other branch is unreachable, we don't type check it and so we might
  912. # not have a type for the original definition
  913. return
  914. if isinstance(orig_type, PartialType):
  915. if orig_type.type is None:
  916. # Ah this is a partial type. Give it the type of the function.
  917. orig_def = defn.original_def
  918. if isinstance(orig_def, Decorator):
  919. var = orig_def.var
  920. else:
  921. var = orig_def
  922. partial_types = self.find_partial_types(var)
  923. if partial_types is not None:
  924. var.type = new_type
  925. del partial_types[var]
  926. else:
  927. # Trying to redefine something like partial empty list as function.
  928. self.fail(message_registry.INCOMPATIBLE_REDEFINITION, defn)
  929. else:
  930. name_expr = NameExpr(defn.name)
  931. name_expr.node = defn.original_def
  932. self.binder.assign_type(name_expr, new_type, orig_type)
  933. self.check_subtype(
  934. new_type,
  935. orig_type,
  936. defn,
  937. message_registry.INCOMPATIBLE_REDEFINITION,
  938. "redefinition with type",
  939. "original type",
  940. )
  941. def check_func_item(
  942. self,
  943. defn: FuncItem,
  944. type_override: CallableType | None = None,
  945. name: str | None = None,
  946. allow_empty: bool = False,
  947. ) -> None:
  948. """Type check a function.
  949. If type_override is provided, use it as the function type.
  950. """
  951. self.dynamic_funcs.append(defn.is_dynamic() and not type_override)
  952. with self.enter_partial_types(is_function=True):
  953. typ = self.function_type(defn)
  954. if type_override:
  955. typ = type_override.copy_modified(line=typ.line, column=typ.column)
  956. if isinstance(typ, CallableType):
  957. with self.enter_attribute_inference_context():
  958. self.check_func_def(defn, typ, name, allow_empty)
  959. else:
  960. raise RuntimeError("Not supported")
  961. self.dynamic_funcs.pop()
  962. self.current_node_deferred = False
  963. if name == "__exit__":
  964. self.check__exit__return_type(defn)
  965. if name == "__post_init__":
  966. if dataclasses_plugin.is_processed_dataclass(defn.info):
  967. dataclasses_plugin.check_post_init(self, defn, defn.info)
  968. @contextmanager
  969. def enter_attribute_inference_context(self) -> Iterator[None]:
  970. old_types = self.inferred_attribute_types
  971. self.inferred_attribute_types = {}
  972. yield None
  973. self.inferred_attribute_types = old_types
  974. def check_func_def(
  975. self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False
  976. ) -> None:
  977. """Type check a function definition."""
  978. # Expand type variables with value restrictions to ordinary types.
  979. expanded = self.expand_typevars(defn, typ)
  980. for item, typ in expanded:
  981. old_binder = self.binder
  982. self.binder = ConditionalTypeBinder()
  983. with self.binder.top_frame_context():
  984. defn.expanded.append(item)
  985. # We may be checking a function definition or an anonymous
  986. # function. In the first case, set up another reference with the
  987. # precise type.
  988. if isinstance(item, FuncDef):
  989. fdef = item
  990. # Check if __init__ has an invalid return type.
  991. if (
  992. fdef.info
  993. and fdef.name in ("__init__", "__init_subclass__")
  994. and not isinstance(
  995. get_proper_type(typ.ret_type), (NoneType, UninhabitedType)
  996. )
  997. and not self.dynamic_funcs[-1]
  998. ):
  999. self.fail(
  1000. message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item
  1001. )
  1002. # Check validity of __new__ signature
  1003. if fdef.info and fdef.name == "__new__":
  1004. self.check___new___signature(fdef, typ)
  1005. self.check_for_missing_annotations(fdef)
  1006. if self.options.disallow_any_unimported:
  1007. if fdef.type and isinstance(fdef.type, CallableType):
  1008. ret_type = fdef.type.ret_type
  1009. if has_any_from_unimported_type(ret_type):
  1010. self.msg.unimported_type_becomes_any("Return type", ret_type, fdef)
  1011. for idx, arg_type in enumerate(fdef.type.arg_types):
  1012. if has_any_from_unimported_type(arg_type):
  1013. prefix = f'Argument {idx + 1} to "{fdef.name}"'
  1014. self.msg.unimported_type_becomes_any(prefix, arg_type, fdef)
  1015. check_for_explicit_any(
  1016. fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef
  1017. )
  1018. if name: # Special method names
  1019. if defn.info and self.is_reverse_op_method(name):
  1020. self.check_reverse_op_method(item, typ, name, defn)
  1021. elif name in ("__getattr__", "__getattribute__"):
  1022. self.check_getattr_method(typ, defn, name)
  1023. elif name == "__setattr__":
  1024. self.check_setattr_method(typ, defn)
  1025. # Refuse contravariant return type variable
  1026. if isinstance(typ.ret_type, TypeVarType):
  1027. if typ.ret_type.variance == CONTRAVARIANT:
  1028. self.fail(
  1029. message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT, typ.ret_type
  1030. )
  1031. self.check_unbound_return_typevar(typ)
  1032. # Check that Generator functions have the appropriate return type.
  1033. if defn.is_generator:
  1034. if defn.is_async_generator:
  1035. if not self.is_async_generator_return_type(typ.ret_type):
  1036. self.fail(
  1037. message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR, typ
  1038. )
  1039. else:
  1040. if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine):
  1041. self.fail(message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)
  1042. # Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
  1043. if defn.is_awaitable_coroutine:
  1044. # Update the return type to AwaitableGenerator.
  1045. # (This doesn't exist in typing.py, only in typing.pyi.)
  1046. t = typ.ret_type
  1047. c = defn.is_coroutine
  1048. ty = self.get_generator_yield_type(t, c)
  1049. tc = self.get_generator_receive_type(t, c)
  1050. if c:
  1051. tr = self.get_coroutine_return_type(t)
  1052. else:
  1053. tr = self.get_generator_return_type(t, c)
  1054. ret_type = self.named_generic_type(
  1055. "typing.AwaitableGenerator", [ty, tc, tr, t]
  1056. )
  1057. typ = typ.copy_modified(ret_type=ret_type)
  1058. defn.type = typ
  1059. # Push return type.
  1060. self.return_types.append(typ.ret_type)
  1061. # Store argument types.
  1062. for i in range(len(typ.arg_types)):
  1063. arg_type = typ.arg_types[i]
  1064. with self.scope.push_function(defn):
  1065. # We temporary push the definition to get the self type as
  1066. # visible from *inside* of this function/method.
  1067. ref_type: Type | None = self.scope.active_self_type()
  1068. if (
  1069. isinstance(defn, FuncDef)
  1070. and ref_type is not None
  1071. and i == 0
  1072. and (not defn.is_static or defn.name == "__new__")
  1073. and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]
  1074. ):
  1075. if defn.is_class or defn.name == "__new__":
  1076. ref_type = mypy.types.TypeType.make_normalized(ref_type)
  1077. erased = get_proper_type(erase_to_bound(arg_type))
  1078. if not is_subtype(ref_type, erased, ignore_type_params=True):
  1079. if (
  1080. isinstance(erased, Instance)
  1081. and erased.type.is_protocol
  1082. or isinstance(erased, TypeType)
  1083. and isinstance(erased.item, Instance)
  1084. and erased.item.type.is_protocol
  1085. ):
  1086. # We allow the explicit self-type to be not a supertype of
  1087. # the current class if it is a protocol. For such cases
  1088. # the consistency check will be performed at call sites.
  1089. msg = None
  1090. elif typ.arg_names[i] in {"self", "cls"}:
  1091. msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(
  1092. erased.str_with_options(self.options),
  1093. ref_type.str_with_options(self.options),
  1094. )
  1095. else:
  1096. msg = message_registry.MISSING_OR_INVALID_SELF_TYPE
  1097. if msg:
  1098. self.fail(msg, defn)
  1099. elif isinstance(arg_type, TypeVarType):
  1100. # Refuse covariant parameter type variables
  1101. # TODO: check recursively for inner type variables
  1102. if (
  1103. arg_type.variance == COVARIANT
  1104. and defn.name not in ("__init__", "__new__", "__post_init__")
  1105. and not is_private(defn.name) # private methods are not inherited
  1106. ):
  1107. ctx: Context = arg_type
  1108. if ctx.line < 0:
  1109. ctx = typ
  1110. self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx)
  1111. # Need to store arguments again for the expanded item.
  1112. store_argument_type(item, i, typ, self.named_generic_type)
  1113. # Type check initialization expressions.
  1114. body_is_trivial = is_trivial_body(defn.body)
  1115. self.check_default_args(item, body_is_trivial)
  1116. # Type check body in a new scope.
  1117. with self.binder.top_frame_context():
  1118. # Copy some type narrowings from an outer function when it seems safe enough
  1119. # (i.e. we can't find an assignment that might change the type of the
  1120. # variable afterwards).
  1121. new_frame: Frame | None = None
  1122. for frame in old_binder.frames:
  1123. for key, narrowed_type in frame.types.items():
  1124. key_var = extract_var_from_literal_hash(key)
  1125. if key_var is not None and not self.is_var_redefined_in_outer_context(
  1126. key_var, defn.line
  1127. ):
  1128. # It seems safe to propagate the type narrowing to a nested scope.
  1129. if new_frame is None:
  1130. new_frame = self.binder.push_frame()
  1131. new_frame.types[key] = narrowed_type
  1132. self.binder.declarations[key] = old_binder.declarations[key]
  1133. with self.scope.push_function(defn):
  1134. # We suppress reachability warnings when we use TypeVars with value
  1135. # restrictions: we only want to report a warning if a certain statement is
  1136. # marked as being suppressed in *all* of the expansions, but we currently
  1137. # have no good way of doing this.
  1138. #
  1139. # TODO: Find a way of working around this limitation
  1140. if len(expanded) >= 2:
  1141. self.binder.suppress_unreachable_warnings()
  1142. self.accept(item.body)
  1143. unreachable = self.binder.is_unreachable()
  1144. if new_frame is not None:
  1145. self.binder.pop_frame(True, 0)
  1146. if not unreachable:
  1147. if defn.is_generator or is_named_instance(
  1148. self.return_types[-1], "typing.AwaitableGenerator"
  1149. ):
  1150. return_type = self.get_generator_return_type(
  1151. self.return_types[-1], defn.is_coroutine
  1152. )
  1153. elif defn.is_coroutine:
  1154. return_type = self.get_coroutine_return_type(self.return_types[-1])
  1155. else:
  1156. return_type = self.return_types[-1]
  1157. return_type = get_proper_type(return_type)
  1158. allow_empty = allow_empty or self.options.allow_empty_bodies
  1159. show_error = (
  1160. not body_is_trivial
  1161. or
  1162. # Allow empty bodies for abstract methods, overloads, in tests and stubs.
  1163. (
  1164. not allow_empty
  1165. and not (
  1166. isinstance(defn, FuncDef) and defn.abstract_status != NOT_ABSTRACT
  1167. )
  1168. and not self.is_stub
  1169. )
  1170. )
  1171. # Ignore plugin generated methods, these usually don't need any bodies.
  1172. if defn.info is not FUNC_NO_INFO and (
  1173. defn.name not in defn.info.names or defn.info.names[defn.name].plugin_generated
  1174. ):
  1175. show_error = False
  1176. # Ignore also definitions that appear in `if TYPE_CHECKING: ...` blocks.
  1177. # These can't be called at runtime anyway (similar to plugin-generated).
  1178. if isinstance(defn, FuncDef) and defn.is_mypy_only:
  1179. show_error = False
  1180. # We want to minimize the fallout from checking empty bodies
  1181. # that was absent in many mypy versions.
  1182. if body_is_trivial and is_subtype(NoneType(), return_type):
  1183. show_error = False
  1184. may_be_abstract = (
  1185. body_is_trivial
  1186. and defn.info is not FUNC_NO_INFO
  1187. and defn.info.metaclass_type is not None
  1188. and defn.info.metaclass_type.type.has_base("abc.ABCMeta")
  1189. )
  1190. if self.options.warn_no_return:
  1191. if (
  1192. not self.current_node_deferred
  1193. and not isinstance(return_type, (NoneType, AnyType))
  1194. and show_error
  1195. ):
  1196. # Control flow fell off the end of a function that was
  1197. # declared to return a non-None type.
  1198. if isinstance(return_type, UninhabitedType):
  1199. # This is a NoReturn function
  1200. msg = message_registry.INVALID_IMPLICIT_RETURN
  1201. else:
  1202. msg = message_registry.MISSING_RETURN_STATEMENT
  1203. if body_is_trivial:
  1204. msg = msg._replace(code=codes.EMPTY_BODY)
  1205. self.fail(msg, defn)
  1206. if may_be_abstract:
  1207. self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)
  1208. elif show_error:
  1209. msg = message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE
  1210. if body_is_trivial:
  1211. msg = msg._replace(code=codes.EMPTY_BODY)
  1212. # similar to code in check_return_stmt
  1213. if (
  1214. not self.check_subtype(
  1215. subtype_label="implicitly returns",
  1216. subtype=NoneType(),
  1217. supertype_label="expected",
  1218. supertype=return_type,
  1219. context=defn,
  1220. msg=msg,
  1221. )
  1222. and may_be_abstract
  1223. ):
  1224. self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)
  1225. self.return_types.pop()
  1226. self.binder = old_binder
  1227. def is_var_redefined_in_outer_context(self, v: Var, after_line: int) -> bool:
  1228. """Can the variable be assigned to at module top level or outer function?
  1229. Note that this doesn't do a full CFG analysis but uses a line number based
  1230. heuristic that isn't correct in some (rare) cases.
  1231. """
  1232. outers = self.tscope.outer_functions()
  1233. if not outers:
  1234. # Top-level function -- outer context is top level, and we can't reason about
  1235. # globals
  1236. return True
  1237. for outer in outers:
  1238. if isinstance(outer, FuncDef):
  1239. if find_last_var_assignment_line(outer.body, v) >= after_line:
  1240. return True
  1241. return False
  1242. def check_unbound_return_typevar(self, typ: CallableType) -> None:
  1243. """Fails when the return typevar is not defined in arguments."""
  1244. if isinstance(typ.ret_type, TypeVarType) and typ.ret_type in typ.variables:
  1245. arg_type_visitor = CollectArgTypeVarTypes()
  1246. for argtype in typ.arg_types:
  1247. argtype.accept(arg_type_visitor)
  1248. if typ.ret_type not in arg_type_visitor.arg_types:
  1249. self.fail(message_registry.UNBOUND_TYPEVAR, typ.ret_type, code=TYPE_VAR)
  1250. upper_bound = get_proper_type(typ.ret_type.upper_bound)
  1251. if not (
  1252. isinstance(upper_bound, Instance)
  1253. and upper_bound.type.fullname == "builtins.object"
  1254. ):
  1255. self.note(
  1256. "Consider using the upper bound "
  1257. f"{format_type(typ.ret_type.upper_bound, self.options)} instead",
  1258. context=typ.ret_type,
  1259. )
  1260. def check_default_args(self, item: FuncItem, body_is_trivial: bool) -> None:
  1261. for arg in item.arguments:
  1262. if arg.initializer is None:
  1263. continue
  1264. if body_is_trivial and isinstance(arg.initializer, EllipsisExpr):
  1265. continue
  1266. name = arg.variable.name
  1267. msg = "Incompatible default for "
  1268. if name.startswith("__tuple_arg_"):
  1269. msg += f"tuple argument {name[12:]}"
  1270. else:
  1271. msg += f'argument "{name}"'
  1272. if (
  1273. not self.options.implicit_optional
  1274. and isinstance(arg.initializer, NameExpr)
  1275. and arg.initializer.fullname == "builtins.None"
  1276. ):
  1277. notes = [
  1278. "PEP 484 prohibits implicit Optional. "
  1279. "Accordingly, mypy has changed its default to no_implicit_optional=True",
  1280. "Use https://github.com/hauntsaninja/no_implicit_optional to automatically "
  1281. "upgrade your codebase",
  1282. ]
  1283. else:
  1284. notes = None
  1285. self.check_simple_assignment(
  1286. arg.variable.type,
  1287. arg.initializer,
  1288. context=arg.initializer,
  1289. msg=ErrorMessage(msg, code=codes.ASSIGNMENT),
  1290. lvalue_name="argument",
  1291. rvalue_name="default",
  1292. notes=notes,
  1293. )
  1294. def is_forward_op_method(self, method_name: str) -> bool:
  1295. return method_name in operators.reverse_op_methods
  1296. def is_reverse_op_method(self, method_name: str) -> bool:
  1297. return method_name in operators.reverse_op_method_set
  1298. def check_for_missing_annotations(self, fdef: FuncItem) -> None:
  1299. # Check for functions with unspecified/not fully specified types.
  1300. def is_unannotated_any(t: Type) -> bool:
  1301. if not isinstance(t, ProperType):
  1302. return False
  1303. return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated
  1304. has_explicit_annotation = isinstance(fdef.type, CallableType) and any(
  1305. not is_unannotated_any(t) for t in fdef.type.arg_types + [fdef.type.ret_type]
  1306. )
  1307. show_untyped = not self.is_typeshed_stub or self.options.warn_incomplete_stub
  1308. check_incomplete_defs = self.options.disallow_incomplete_defs and has_explicit_annotation
  1309. if show_untyped and (self.options.disallow_untyped_defs or check_incomplete_defs):
  1310. if fdef.type is None and self.options.disallow_untyped_defs:
  1311. if not fdef.arguments or (
  1312. len(fdef.arguments) == 1
  1313. and (fdef.arg_names[0] == "self" or fdef.arg_names[0] == "cls")
  1314. ):
  1315. self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
  1316. if not has_return_statement(fdef) and not fdef.is_generator:
  1317. self.note(
  1318. 'Use "-> None" if function does not return a value',
  1319. fdef,
  1320. code=codes.NO_UNTYPED_DEF,
  1321. )
  1322. else:
  1323. self.fail(message_registry.FUNCTION_TYPE_EXPECTED, fdef)
  1324. elif isinstance(fdef.type, CallableType):
  1325. ret_type = get_proper_type(fdef.type.ret_type)
  1326. if is_unannotated_any(ret_type):
  1327. self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
  1328. elif fdef.is_generator:
  1329. if is_unannotated_any(
  1330. self.get_generator_return_type(ret_type, fdef.is_coroutine)
  1331. ):
  1332. self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
  1333. elif fdef.is_coroutine and isinstance(ret_type, Instance):
  1334. if is_unannotated_any(self.get_coroutine_return_type(ret_type)):
  1335. self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)
  1336. if any(is_unannotated_any(t) for t in fdef.type.arg_types):
  1337. self.fail(message_registry.ARGUMENT_TYPE_EXPECTED, fdef)
  1338. def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None:
  1339. self_type = fill_typevars_with_any(fdef.info)
  1340. bound_type = bind_self(typ, self_type, is_classmethod=True)
  1341. # Check that __new__ (after binding cls) returns an instance
  1342. # type (or any).
  1343. if fdef.info.is_metaclass():
  1344. # This is a metaclass, so it must return a new unrelated type.
  1345. self.check_subtype(
  1346. bound_type.ret_type,
  1347. self.type_type(),
  1348. fdef,
  1349. message_registry.INVALID_NEW_TYPE,
  1350. "returns",
  1351. "but must return a subtype of",
  1352. )
  1353. elif not isinstance(
  1354. get_proper_type(bound_type.ret_type), (AnyType, Instance, TupleType, UninhabitedType)
  1355. ):
  1356. self.fail(
  1357. message_registry.NON_INSTANCE_NEW_TYPE.format(
  1358. format_type(bound_type.ret_type, self.options)
  1359. ),
  1360. fdef,
  1361. )
  1362. else:
  1363. # And that it returns a subtype of the class
  1364. self.check_subtype(
  1365. bound_type.ret_type,
  1366. self_type,
  1367. fdef,
  1368. message_registry.INVALID_NEW_TYPE,
  1369. "returns",
  1370. "but must return a subtype of",
  1371. )
  1372. def check_reverse_op_method(
  1373. self, defn: FuncItem, reverse_type: CallableType, reverse_name: str, context: Context
  1374. ) -> None:
  1375. """Check a reverse operator method such as __radd__."""
  1376. # Decides whether it's worth calling check_overlapping_op_methods().
  1377. # This used to check for some very obscure scenario. It now
  1378. # just decides whether it's worth calling
  1379. # check_overlapping_op_methods().
  1380. assert defn.info
  1381. # First check for a valid signature
  1382. method_type = CallableType(
  1383. [AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)],
  1384. [nodes.ARG_POS, nodes.ARG_POS],
  1385. [None, None],
  1386. AnyType(TypeOfAny.special_form),
  1387. self.named_type("builtins.function"),
  1388. )
  1389. if not is_subtype(reverse_type, method_type):
  1390. self.msg.invalid_signature(reverse_type, context)
  1391. return
  1392. if reverse_name in ("__eq__", "__ne__"):
  1393. # These are defined for all objects => can't cause trouble.
  1394. return
  1395. # With 'Any' or 'object' return type we are happy, since any possible
  1396. # return value is valid.
  1397. ret_type = get_proper_type(reverse_type.ret_type)
  1398. if isinstance(ret_type, AnyType):
  1399. return
  1400. if isinstance(ret_type, Instance):
  1401. if ret_type.type.fullname == "builtins.object":
  1402. return
  1403. if reverse_type.arg_kinds[0] == ARG_STAR:
  1404. reverse_type = reverse_type.copy_modified(
  1405. arg_types=[reverse_type.arg_types[0]] * 2,
  1406. arg_kinds=[ARG_POS] * 2,
  1407. arg_names=[reverse_type.arg_names[0], "_"],
  1408. )
  1409. assert len(reverse_type.arg_types) >= 2
  1410. forward_name = operators.normal_from_reverse_op[reverse_name]
  1411. forward_inst = get_proper_type(reverse_type.arg_types[1])
  1412. if isinstance(forward_inst, TypeVarType):
  1413. forward_inst = get_proper_type(forward_inst.upper_bound)
  1414. elif isinstance(forward_inst, TupleType):
  1415. forward_inst = tuple_fallback(forward_inst)
  1416. elif isinstance(forward_inst, (FunctionLike, TypedDictType, LiteralType)):
  1417. forward_inst = forward_inst.fallback
  1418. if isinstance(forward_inst, TypeType):
  1419. item = forward_inst.item
  1420. if isinstance(item, Instance):
  1421. opt_meta = item.type.metaclass_type
  1422. if opt_meta is not None:
  1423. forward_inst = opt_meta
  1424. def has_readable_member(typ: UnionType | Instance, name: str) -> bool:
  1425. # TODO: Deal with attributes of TupleType etc.
  1426. if isinstance(typ, Instance):
  1427. return typ.type.has_readable_member(name)
  1428. return all(
  1429. (isinstance(x, UnionType) and has_readable_member(x, name))
  1430. or (isinstance(x, Instance) and x.type.has_readable_member(name))
  1431. for x in get_proper_types(typ.relevant_items())
  1432. )
  1433. if not (
  1434. isinstance(forward_inst, (Instance, UnionType))
  1435. and has_readable_member(forward_inst, forward_name)
  1436. ):
  1437. return
  1438. forward_base = reverse_type.arg_types[1]
  1439. forward_type = self.expr_checker.analyze_external_member_access(
  1440. forward_name, forward_base, context=defn
  1441. )
  1442. self.check_overlapping_op_methods(
  1443. reverse_type,
  1444. reverse_name,
  1445. defn.info,
  1446. forward_type,
  1447. forward_name,
  1448. forward_base,
  1449. context=defn,
  1450. )
  1451. def check_overlapping_op_methods(
  1452. self,
  1453. reverse_type: CallableType,
  1454. reverse_name: str,
  1455. reverse_class: TypeInfo,
  1456. forward_type: Type,
  1457. forward_name: str,
  1458. forward_base: Type,
  1459. context: Context,
  1460. ) -> None:
  1461. """Check for overlapping method and reverse method signatures.
  1462. This function assumes that:
  1463. - The reverse method has valid argument count and kinds.
  1464. - If the reverse operator method accepts some argument of type
  1465. X, the forward operator method also belong to class X.
  1466. For example, if we have the reverse operator `A.__radd__(B)`, then the
  1467. corresponding forward operator must have the type `B.__add__(...)`.
  1468. """
  1469. # Note: Suppose we have two operator methods "A.__rOP__(B) -> R1" and
  1470. # "B.__OP__(C) -> R2". We check if these two methods are unsafely overlapping
  1471. # by using the following algorithm:
  1472. #
  1473. # 1. Rewrite "B.__OP__(C) -> R1" to "temp1(B, C) -> R1"
  1474. #
  1475. # 2. Rewrite "A.__rOP__(B) -> R2" to "temp2(B, A) -> R2"
  1476. #
  1477. # 3. Treat temp1 and temp2 as if they were both variants in the same
  1478. # overloaded function. (This mirrors how the Python runtime calls
  1479. # operator methods: we first try __OP__, then __rOP__.)
  1480. #
  1481. # If the first signature is unsafely overlapping with the second,
  1482. # report an error.
  1483. #
  1484. # 4. However, if temp1 shadows temp2 (e.g. the __rOP__ method can never
  1485. # be called), do NOT report an error.
  1486. #
  1487. # This behavior deviates from how we handle overloads -- many of the
  1488. # modules in typeshed seem to define __OP__ methods that shadow the
  1489. # corresponding __rOP__ method.
  1490. #
  1491. # Note: we do not attempt to handle unsafe overlaps related to multiple
  1492. # inheritance. (This is consistent with how we handle overloads: we also
  1493. # do not try checking unsafe overlaps due to multiple inheritance there.)
  1494. for forward_item in flatten_nested_unions([forward_type]):
  1495. forward_item = get_proper_type(forward_item)
  1496. if isinstance(forward_item, CallableType):
  1497. if self.is_unsafe_overlapping_op(forward_item, forward_base, reverse_type):
  1498. self.msg.operator_method_signatures_overlap(
  1499. reverse_class, reverse_name, forward_base, forward_name, context
  1500. )
  1501. elif isinstance(forward_item, Overloaded):
  1502. for item in forward_item.items:
  1503. if self.is_unsafe_overlapping_op(item, forward_base, reverse_type):
  1504. self.msg.operator_method_signatures_overlap(
  1505. reverse_class, reverse_name, forward_base, forward_name, context
  1506. )
  1507. elif not isinstance(forward_item, AnyType):
  1508. self.msg.forward_operator_not_callable(forward_name, context)
  1509. def is_unsafe_overlapping_op(
  1510. self, forward_item: CallableType, forward_base: Type, reverse_type: CallableType
  1511. ) -> bool:
  1512. # TODO: check argument kinds?
  1513. if len(forward_item.arg_types) < 1:
  1514. # Not a valid operator method -- can't succeed anyway.
  1515. return False
  1516. # Erase the type if necessary to make sure we don't have a single
  1517. # TypeVar in forward_tweaked. (Having a function signature containing
  1518. # just a single TypeVar can lead to unpredictable behavior.)
  1519. forward_base_erased = forward_base
  1520. if isinstance(forward_base, TypeVarType):
  1521. forward_base_erased = erase_to_bound(forward_base)
  1522. # Construct normalized function signatures corresponding to the
  1523. # operator methods. The first argument is the left operand and the
  1524. # second operand is the right argument -- we switch the order of
  1525. # the arguments of the reverse method.
  1526. forward_tweaked = forward_item.copy_modified(
  1527. arg_types=[forward_base_erased, forward_item.arg_types[0]],
  1528. arg_kinds=[nodes.ARG_POS] * 2,
  1529. arg_names=[None] * 2,
  1530. )
  1531. reverse_tweaked = reverse_type.copy_modified(
  1532. arg_types=[reverse_type.arg_types[1], reverse_type.arg_types[0]],
  1533. arg_kinds=[nodes.ARG_POS] * 2,
  1534. arg_names=[None] * 2,
  1535. )
  1536. reverse_base_erased = reverse_type.arg_types[0]
  1537. if isinstance(reverse_base_erased, TypeVarType):
  1538. reverse_base_erased = erase_to_bound(reverse_base_erased)
  1539. if is_same_type(reverse_base_erased, forward_base_erased):
  1540. return False
  1541. elif is_subtype(reverse_base_erased, forward_base_erased):
  1542. first = reverse_tweaked
  1543. second = forward_tweaked
  1544. else:
  1545. first = forward_tweaked
  1546. second = reverse_tweaked
  1547. return is_unsafe_overlapping_overload_signatures(first, second)
  1548. def check_inplace_operator_method(self, defn: FuncBase) -> None:
  1549. """Check an inplace operator method such as __iadd__.
  1550. They cannot arbitrarily overlap with __add__.
  1551. """
  1552. method = defn.name
  1553. if method not in operators.inplace_operator_methods:
  1554. return
  1555. typ = bind_self(self.function_type(defn))
  1556. cls = defn.info
  1557. other_method = "__" + method[3:]
  1558. if cls.has_readable_member(other_method):
  1559. instance = fill_typevars(cls)
  1560. typ2 = get_proper_type(
  1561. self.expr_checker.analyze_external_member_access(other_method, instance, defn)
  1562. )
  1563. fail = False
  1564. if isinstance(typ2, FunctionLike):
  1565. if not is_more_general_arg_prefix(typ, typ2):
  1566. fail = True
  1567. else:
  1568. # TODO overloads
  1569. fail = True
  1570. if fail:
  1571. self.msg.signatures_incompatible(method, other_method, defn)
  1572. def check_getattr_method(self, typ: Type, context: Context, name: str) -> None:
  1573. if len(self.scope.stack) == 1:
  1574. # module scope
  1575. if name == "__getattribute__":
  1576. self.fail(message_registry.MODULE_LEVEL_GETATTRIBUTE, context)
  1577. return
  1578. # __getattr__ is fine at the module level as of Python 3.7 (PEP 562). We could
  1579. # show an error for Python < 3.7, but that would be annoying in code that supports
  1580. # both 3.7 and older versions.
  1581. method_type = CallableType(
  1582. [self.named_type("builtins.str")],
  1583. [nodes.ARG_POS],
  1584. [None],
  1585. AnyType(TypeOfAny.special_form),
  1586. self.named_type("builtins.function"),
  1587. )
  1588. elif self.scope.active_class():
  1589. method_type = CallableType(
  1590. [AnyType(TypeOfAny.special_form), self.named_type("builtins.str")],
  1591. [nodes.ARG_POS, nodes.ARG_POS],
  1592. [None, None],
  1593. AnyType(TypeOfAny.special_form),
  1594. self.named_type("builtins.function"),
  1595. )
  1596. else:
  1597. return
  1598. if not is_subtype(typ, method_type):
  1599. self.msg.invalid_signature_for_special_method(typ, context, name)
  1600. def check_setattr_method(self, typ: Type, context: Context) -> None:
  1601. if not self.scope.active_class():
  1602. return
  1603. method_type = CallableType(
  1604. [
  1605. AnyType(TypeOfAny.special_form),
  1606. self.named_type("builtins.str"),
  1607. AnyType(TypeOfAny.special_form),
  1608. ],
  1609. [nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],
  1610. [None, None, None],
  1611. NoneType(),
  1612. self.named_type("builtins.function"),
  1613. )
  1614. if not is_subtype(typ, method_type):
  1615. self.msg.invalid_signature_for_special_method(typ, context, "__setattr__")
  1616. def check_slots_definition(self, typ: Type, context: Context) -> None:
  1617. """Check the type of __slots__."""
  1618. str_type = self.named_type("builtins.str")
  1619. expected_type = UnionType(
  1620. [str_type, self.named_generic_type("typing.Iterable", [str_type])]
  1621. )
  1622. self.check_subtype(
  1623. typ,
  1624. expected_type,
  1625. context,
  1626. message_registry.INVALID_TYPE_FOR_SLOTS,
  1627. "actual type",
  1628. "expected type",
  1629. code=codes.ASSIGNMENT,
  1630. )
  1631. def check_match_args(self, var: Var, typ: Type, context: Context) -> None:
  1632. """Check that __match_args__ contains literal strings"""
  1633. if not self.scope.active_class():
  1634. return
  1635. typ = get_proper_type(typ)
  1636. if not isinstance(typ, TupleType) or not all(
  1637. [is_string_literal(item) for item in typ.items]
  1638. ):
  1639. self.msg.note(
  1640. "__match_args__ must be a tuple containing string literals for checking "
  1641. "of match statements to work",
  1642. context,
  1643. code=codes.LITERAL_REQ,
  1644. )
  1645. def expand_typevars(
  1646. self, defn: FuncItem, typ: CallableType
  1647. ) -> list[tuple[FuncItem, CallableType]]:
  1648. # TODO use generator
  1649. subst: list[list[tuple[TypeVarId, Type]]] = []
  1650. tvars = list(typ.variables) or []
  1651. if defn.info:
  1652. # Class type variables
  1653. tvars += defn.info.defn.type_vars or []
  1654. # TODO(PEP612): audit for paramspec
  1655. for tvar in tvars:
  1656. if isinstance(tvar, TypeVarType) and tvar.values:
  1657. subst.append([(tvar.id, value) for value in tvar.values])
  1658. # Make a copy of the function to check for each combination of
  1659. # value restricted type variables. (Except when running mypyc,
  1660. # where we need one canonical version of the function.)
  1661. if subst and not (self.options.mypyc or self.options.inspections):
  1662. result: list[tuple[FuncItem, CallableType]] = []
  1663. for substitutions in itertools.product(*subst):
  1664. mapping = dict(substitutions)
  1665. result.append((expand_func(defn, mapping), expand_type(typ, mapping)))
  1666. return result
  1667. else:
  1668. return [(defn, typ)]
  1669. def check_explicit_override_decorator(
  1670. self,
  1671. defn: FuncDef | OverloadedFuncDef,
  1672. found_method_base_classes: list[TypeInfo] | None,
  1673. context: Context | None = None,
  1674. ) -> None:
  1675. if (
  1676. found_method_base_classes
  1677. and not defn.is_explicit_override
  1678. and defn.name not in ("__init__", "__new__")
  1679. ):
  1680. self.msg.explicit_override_decorator_missing(
  1681. defn.name, found_method_base_classes[0].fullname, context or defn
  1682. )
  1683. def check_method_override(
  1684. self, defn: FuncDef | OverloadedFuncDef | Decorator
  1685. ) -> list[TypeInfo] | None:
  1686. """Check if function definition is compatible with base classes.
  1687. This may defer the method if a signature is not available in at least one base class.
  1688. Return ``None`` if that happens.
  1689. Return a list of base classes which contain an attribute with the method name.
  1690. """
  1691. # Check against definitions in base classes.
  1692. found_method_base_classes: list[TypeInfo] = []
  1693. for base in defn.info.mro[1:]:
  1694. result = self.check_method_or_accessor_override_for_base(defn, base)
  1695. if result is None:
  1696. # Node was deferred, we will have another attempt later.
  1697. return None
  1698. if result:
  1699. found_method_base_classes.append(base)
  1700. return found_method_base_classes
  1701. def check_method_or_accessor_override_for_base(
  1702. self, defn: FuncDef | OverloadedFuncDef | Decorator, base: TypeInfo
  1703. ) -> bool | None:
  1704. """Check if method definition is compatible with a base class.
  1705. Return ``None`` if the node was deferred because one of the corresponding
  1706. superclass nodes is not ready.
  1707. Return ``True`` if an attribute with the method name was found in the base class.
  1708. """
  1709. found_base_method = False
  1710. if base:
  1711. name = defn.name
  1712. base_attr = base.names.get(name)
  1713. if base_attr:
  1714. # First, check if we override a final (always an error, even with Any types).
  1715. if is_final_node(base_attr.node):
  1716. self.msg.cant_override_final(name, base.name, defn)
  1717. # Second, final can't override anything writeable independently of types.
  1718. if defn.is_final:
  1719. self.check_if_final_var_override_writable(name, base_attr.node, defn)
  1720. found_base_method = True
  1721. # Check the type of override.
  1722. if name not in ("__init__", "__new__", "__init_subclass__", "__post_init__"):
  1723. # Check method override
  1724. # (__init__, __new__, __init_subclass__ are special).
  1725. if self.check_method_override_for_base_with_name(defn, name, base):
  1726. return None
  1727. if name in operators.inplace_operator_methods:
  1728. # Figure out the name of the corresponding operator method.
  1729. method = "__" + name[3:]
  1730. # An inplace operator method such as __iadd__ might not be
  1731. # always introduced safely if a base class defined __add__.
  1732. # TODO can't come up with an example where this is
  1733. # necessary; now it's "just in case"
  1734. if self.check_method_override_for_base_with_name(defn, method, base):
  1735. return None
  1736. return found_base_method
  1737. def check_method_override_for_base_with_name(
  1738. self, defn: FuncDef | OverloadedFuncDef | Decorator, name: str, base: TypeInfo
  1739. ) -> bool:
  1740. """Check if overriding an attribute `name` of `base` with `defn` is valid.
  1741. Return True if the supertype node was not analysed yet, and `defn` was deferred.
  1742. """
  1743. base_attr = base.names.get(name)
  1744. if base_attr:
  1745. # The name of the method is defined in the base class.
  1746. # Point errors at the 'def' line (important for backward compatibility
  1747. # of type ignores).
  1748. if not isinstance(defn, Decorator):
  1749. context = defn
  1750. else:
  1751. context = defn.func
  1752. # Construct the type of the overriding method.
  1753. # TODO: this logic is much less complete than similar one in checkmember.py
  1754. if isinstance(defn, (FuncDef, OverloadedFuncDef)):
  1755. typ: Type = self.function_type(defn)
  1756. override_class_or_static = defn.is_class or defn.is_static
  1757. override_class = defn.is_class
  1758. else:
  1759. assert defn.var.is_ready
  1760. assert defn.var.type is not None
  1761. typ = defn.var.type
  1762. override_class_or_static = defn.func.is_class or defn.func.is_static
  1763. override_class = defn.func.is_class
  1764. typ = get_proper_type(typ)
  1765. if isinstance(typ, FunctionLike) and not is_static(context):
  1766. typ = bind_self(typ, self.scope.active_self_type(), is_classmethod=override_class)
  1767. # Map the overridden method type to subtype context so that
  1768. # it can be checked for compatibility.
  1769. original_type = get_proper_type(base_attr.type)
  1770. original_node = base_attr.node
  1771. # `original_type` can be partial if (e.g.) it is originally an
  1772. # instance variable from an `__init__` block that becomes deferred.
  1773. if original_type is None or isinstance(original_type, PartialType):
  1774. if self.pass_num < self.last_pass:
  1775. # If there are passes left, defer this node until next pass,
  1776. # otherwise try reconstructing the method type from available information.
  1777. self.defer_node(defn, defn.info)
  1778. return True
  1779. elif isinstance(original_node, (FuncDef, OverloadedFuncDef)):
  1780. original_type = self.function_type(original_node)
  1781. elif isinstance(original_node, Decorator):
  1782. original_type = self.function_type(original_node.func)
  1783. elif isinstance(original_node, Var):
  1784. # Super type can define method as an attribute.
  1785. # See https://github.com/python/mypy/issues/10134
  1786. # We also check that sometimes `original_node.type` is None.
  1787. # This is the case when we use something like `__hash__ = None`.
  1788. if original_node.type is not None:
  1789. original_type = get_proper_type(original_node.type)
  1790. else:
  1791. original_type = NoneType()
  1792. else:
  1793. # Will always fail to typecheck below, since we know the node is a method
  1794. original_type = NoneType()
  1795. if isinstance(original_node, (FuncDef, OverloadedFuncDef)):
  1796. original_class_or_static = original_node.is_class or original_node.is_static
  1797. elif isinstance(original_node, Decorator):
  1798. fdef = original_node.func
  1799. original_class_or_static = fdef.is_class or fdef.is_static
  1800. else:
  1801. original_class_or_static = False # a variable can't be class or static
  1802. if isinstance(original_type, FunctionLike):
  1803. original_type = self.bind_and_map_method(base_attr, original_type, defn.info, base)
  1804. if original_node and is_property(original_node):
  1805. original_type = get_property_type(original_type)
  1806. if isinstance(typ, FunctionLike) and is_property(defn):
  1807. typ = get_property_type(typ)
  1808. if (
  1809. isinstance(original_node, Var)
  1810. and not original_node.is_final
  1811. and (not original_node.is_property or original_node.is_settable_property)
  1812. and isinstance(defn, Decorator)
  1813. ):
  1814. # We only give an error where no other similar errors will be given.
  1815. if not isinstance(original_type, AnyType):
  1816. self.msg.fail(
  1817. "Cannot override writeable attribute with read-only property",
  1818. # Give an error on function line to match old behaviour.
  1819. defn.func,
  1820. code=codes.OVERRIDE,
  1821. )
  1822. if isinstance(original_type, AnyType) or isinstance(typ, AnyType):
  1823. pass
  1824. elif isinstance(original_type, FunctionLike) and isinstance(typ, FunctionLike):
  1825. # Check that the types are compatible.
  1826. # TODO overloaded signatures
  1827. self.check_override(
  1828. typ,
  1829. original_type,
  1830. defn.name,
  1831. name,
  1832. base.name,
  1833. original_class_or_static,
  1834. override_class_or_static,
  1835. context,
  1836. )
  1837. elif is_equivalent(original_type, typ):
  1838. # Assume invariance for a non-callable attribute here. Note
  1839. # that this doesn't affect read-only properties which can have
  1840. # covariant overrides.
  1841. #
  1842. pass
  1843. elif (
  1844. original_node
  1845. and not self.is_writable_attribute(original_node)
  1846. and is_subtype(typ, original_type)
  1847. ):
  1848. # If the attribute is read-only, allow covariance
  1849. pass
  1850. else:
  1851. self.msg.signature_incompatible_with_supertype(
  1852. defn.name, name, base.name, context, original=original_type, override=typ
  1853. )
  1854. return False
  1855. def bind_and_map_method(
  1856. self, sym: SymbolTableNode, typ: FunctionLike, sub_info: TypeInfo, super_info: TypeInfo
  1857. ) -> FunctionLike:
  1858. """Bind self-type and map type variables for a method.
  1859. Arguments:
  1860. sym: a symbol that points to method definition
  1861. typ: method type on the definition
  1862. sub_info: class where the method is used
  1863. super_info: class where the method was defined
  1864. """
  1865. if isinstance(sym.node, (FuncDef, OverloadedFuncDef, Decorator)) and not is_static(
  1866. sym.node
  1867. ):
  1868. if isinstance(sym.node, Decorator):
  1869. is_class_method = sym.node.func.is_class
  1870. else:
  1871. is_class_method = sym.node.is_class
  1872. mapped_typ = cast(FunctionLike, map_type_from_supertype(typ, sub_info, super_info))
  1873. active_self_type = self.scope.active_self_type()
  1874. if isinstance(mapped_typ, Overloaded) and active_self_type:
  1875. # If we have an overload, filter to overloads that match the self type.
  1876. # This avoids false positives for concrete subclasses of generic classes,
  1877. # see testSelfTypeOverrideCompatibility for an example.
  1878. filtered_items = []
  1879. for item in mapped_typ.items:
  1880. if not item.arg_types:
  1881. filtered_items.append(item)
  1882. item_arg = item.arg_types[0]
  1883. if isinstance(item_arg, TypeVarType):
  1884. item_arg = item_arg.upper_bound
  1885. if is_subtype(active_self_type, item_arg):
  1886. filtered_items.append(item)
  1887. # If we don't have any filtered_items, maybe it's always a valid override
  1888. # of the superclass? However if you get to that point you're in murky type
  1889. # territory anyway, so we just preserve the type and have the behaviour match
  1890. # that of older versions of mypy.
  1891. if filtered_items:
  1892. mapped_typ = Overloaded(filtered_items)
  1893. return bind_self(mapped_typ, active_self_type, is_class_method)
  1894. else:
  1895. return cast(FunctionLike, map_type_from_supertype(typ, sub_info, super_info))
  1896. def get_op_other_domain(self, tp: FunctionLike) -> Type | None:
  1897. if isinstance(tp, CallableType):
  1898. if tp.arg_kinds and tp.arg_kinds[0] == ARG_POS:
  1899. return tp.arg_types[0]
  1900. return None
  1901. elif isinstance(tp, Overloaded):
  1902. raw_items = [self.get_op_other_domain(it) for it in tp.items]
  1903. items = [it for it in raw_items if it]
  1904. if items:
  1905. return make_simplified_union(items)
  1906. return None
  1907. else:
  1908. assert False, "Need to check all FunctionLike subtypes here"
  1909. def check_override(
  1910. self,
  1911. override: FunctionLike,
  1912. original: FunctionLike,
  1913. name: str,
  1914. name_in_super: str,
  1915. supertype: str,
  1916. original_class_or_static: bool,
  1917. override_class_or_static: bool,
  1918. node: Context,
  1919. ) -> None:
  1920. """Check a method override with given signatures.
  1921. Arguments:
  1922. override: The signature of the overriding method.
  1923. original: The signature of the original supertype method.
  1924. name: The name of the subtype. This and the next argument are
  1925. only used for generating error messages.
  1926. supertype: The name of the supertype.
  1927. """
  1928. # Use boolean variable to clarify code.
  1929. fail = False
  1930. op_method_wider_note = False
  1931. if not is_subtype(override, original, ignore_pos_arg_names=True):
  1932. fail = True
  1933. elif isinstance(override, Overloaded) and self.is_forward_op_method(name):
  1934. # Operator method overrides cannot extend the domain, as
  1935. # this could be unsafe with reverse operator methods.
  1936. original_domain = self.get_op_other_domain(original)
  1937. override_domain = self.get_op_other_domain(override)
  1938. if (
  1939. original_domain
  1940. and override_domain
  1941. and not is_subtype(override_domain, original_domain)
  1942. ):
  1943. fail = True
  1944. op_method_wider_note = True
  1945. if isinstance(override, FunctionLike):
  1946. if original_class_or_static and not override_class_or_static:
  1947. fail = True
  1948. elif isinstance(original, CallableType) and isinstance(override, CallableType):
  1949. if original.type_guard is not None and override.type_guard is None:
  1950. fail = True
  1951. if is_private(name):
  1952. fail = False
  1953. if fail:
  1954. emitted_msg = False
  1955. # Normalize signatures, so we get better diagnostics.
  1956. if isinstance(override, (CallableType, Overloaded)):
  1957. override = override.with_unpacked_kwargs()
  1958. if isinstance(original, (CallableType, Overloaded)):
  1959. original = original.with_unpacked_kwargs()
  1960. if (
  1961. isinstance(override, CallableType)
  1962. and isinstance(original, CallableType)
  1963. and len(override.arg_types) == len(original.arg_types)
  1964. and override.min_args == original.min_args
  1965. ):
  1966. # Give more detailed messages for the common case of both
  1967. # signatures having the same number of arguments and no
  1968. # overloads.
  1969. # override might have its own generic function type
  1970. # variables. If an argument or return type of override
  1971. # does not have the correct subtyping relationship
  1972. # with the original type even after these variables
  1973. # are erased, then it is definitely an incompatibility.
  1974. override_ids = override.type_var_ids()
  1975. type_name = None
  1976. if isinstance(override.definition, FuncDef):
  1977. type_name = override.definition.info.name
  1978. def erase_override(t: Type) -> Type:
  1979. return erase_typevars(t, ids_to_erase=override_ids)
  1980. for i in range(len(override.arg_types)):
  1981. if not is_subtype(
  1982. original.arg_types[i], erase_override(override.arg_types[i])
  1983. ):
  1984. arg_type_in_super = original.arg_types[i]
  1985. if isinstance(node, FuncDef):
  1986. context: Context = node.arguments[i + len(override.bound_args)]
  1987. else:
  1988. context = node
  1989. self.msg.argument_incompatible_with_supertype(
  1990. i + 1,
  1991. name,
  1992. type_name,
  1993. name_in_super,
  1994. arg_type_in_super,
  1995. supertype,
  1996. context,
  1997. secondary_context=node,
  1998. )
  1999. emitted_msg = True
  2000. if not is_subtype(erase_override(override.ret_type), original.ret_type):
  2001. self.msg.return_type_incompatible_with_supertype(
  2002. name, name_in_super, supertype, original.ret_type, override.ret_type, node
  2003. )
  2004. emitted_msg = True
  2005. elif isinstance(override, Overloaded) and isinstance(original, Overloaded):
  2006. # Give a more detailed message in the case where the user is trying to
  2007. # override an overload, and the subclass's overload is plausible, except
  2008. # that the order of the variants are wrong.
  2009. #
  2010. # For example, if the parent defines the overload f(int) -> int and f(str) -> str
  2011. # (in that order), and if the child swaps the two and does f(str) -> str and
  2012. # f(int) -> int
  2013. order = []
  2014. for child_variant in override.items:
  2015. for i, parent_variant in enumerate(original.items):
  2016. if is_subtype(child_variant, parent_variant):
  2017. order.append(i)
  2018. break
  2019. if len(order) == len(original.items) and order != sorted(order):
  2020. self.msg.overload_signature_incompatible_with_supertype(
  2021. name, name_in_super, supertype, node
  2022. )
  2023. emitted_msg = True
  2024. if not emitted_msg:
  2025. # Fall back to generic incompatibility message.
  2026. self.msg.signature_incompatible_with_supertype(
  2027. name, name_in_super, supertype, node, original=original, override=override
  2028. )
  2029. if op_method_wider_note:
  2030. self.note(
  2031. "Overloaded operator methods can't have wider argument types in overrides",
  2032. node,
  2033. code=codes.OVERRIDE,
  2034. )
  2035. def check__exit__return_type(self, defn: FuncItem) -> None:
  2036. """Generate error if the return type of __exit__ is problematic.
  2037. If __exit__ always returns False but the return type is declared
  2038. as bool, mypy thinks that a with statement may "swallow"
  2039. exceptions even though this is not the case, resulting in
  2040. invalid reachability inference.
  2041. """
  2042. if not defn.type or not isinstance(defn.type, CallableType):
  2043. return
  2044. ret_type = get_proper_type(defn.type.ret_type)
  2045. if not has_bool_item(ret_type):
  2046. return
  2047. returns = all_return_statements(defn)
  2048. if not returns:
  2049. return
  2050. if all(
  2051. isinstance(ret.expr, NameExpr) and ret.expr.fullname == "builtins.False"
  2052. for ret in returns
  2053. ):
  2054. self.msg.incorrect__exit__return(defn)
  2055. def visit_class_def(self, defn: ClassDef) -> None:
  2056. """Type check a class definition."""
  2057. typ = defn.info
  2058. for base in typ.mro[1:]:
  2059. if base.is_final:
  2060. self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn)
  2061. with self.tscope.class_scope(defn.info), self.enter_partial_types(is_class=True):
  2062. old_binder = self.binder
  2063. self.binder = ConditionalTypeBinder()
  2064. with self.binder.top_frame_context():
  2065. with self.scope.push_class(defn.info):
  2066. self.accept(defn.defs)
  2067. self.binder = old_binder
  2068. if not (defn.info.typeddict_type or defn.info.tuple_type or defn.info.is_enum):
  2069. # If it is not a normal class (not a special form) check class keywords.
  2070. self.check_init_subclass(defn)
  2071. if not defn.has_incompatible_baseclass:
  2072. # Otherwise we've already found errors; more errors are not useful
  2073. self.check_multiple_inheritance(typ)
  2074. self.check_metaclass_compatibility(typ)
  2075. self.check_final_deletable(typ)
  2076. if defn.decorators:
  2077. sig: Type = type_object_type(defn.info, self.named_type)
  2078. # Decorators are applied in reverse order.
  2079. for decorator in reversed(defn.decorators):
  2080. if isinstance(decorator, CallExpr) and isinstance(
  2081. decorator.analyzed, PromoteExpr
  2082. ):
  2083. # _promote is a special type checking related construct.
  2084. continue
  2085. dec = self.expr_checker.accept(decorator)
  2086. temp = self.temp_node(sig, context=decorator)
  2087. fullname = None
  2088. if isinstance(decorator, RefExpr):
  2089. fullname = decorator.fullname or None
  2090. # TODO: Figure out how to have clearer error messages.
  2091. # (e.g. "class decorator must be a function that accepts a type."
  2092. old_allow_abstract_call = self.allow_abstract_call
  2093. self.allow_abstract_call = True
  2094. sig, _ = self.expr_checker.check_call(
  2095. dec, [temp], [nodes.ARG_POS], defn, callable_name=fullname
  2096. )
  2097. self.allow_abstract_call = old_allow_abstract_call
  2098. # TODO: Apply the sig to the actual TypeInfo so we can handle decorators
  2099. # that completely swap out the type. (e.g. Callable[[Type[A]], Type[B]])
  2100. if typ.defn.type_vars:
  2101. for base_inst in typ.bases:
  2102. for base_tvar, base_decl_tvar in zip(
  2103. base_inst.args, base_inst.type.defn.type_vars
  2104. ):
  2105. if (
  2106. isinstance(base_tvar, TypeVarType)
  2107. and base_tvar.variance != INVARIANT
  2108. and isinstance(base_decl_tvar, TypeVarType)
  2109. and base_decl_tvar.variance != base_tvar.variance
  2110. ):
  2111. self.fail(
  2112. f'Variance of TypeVar "{base_tvar.name}" incompatible '
  2113. "with variance in parent type",
  2114. context=defn,
  2115. code=codes.TYPE_VAR,
  2116. )
  2117. if typ.is_protocol and typ.defn.type_vars:
  2118. self.check_protocol_variance(defn)
  2119. if not defn.has_incompatible_baseclass and defn.info.is_enum:
  2120. self.check_enum(defn)
  2121. def check_final_deletable(self, typ: TypeInfo) -> None:
  2122. # These checks are only for mypyc. Only perform some checks that are easier
  2123. # to implement here than in mypyc.
  2124. for attr in typ.deletable_attributes:
  2125. node = typ.names.get(attr)
  2126. if node and isinstance(node.node, Var) and node.node.is_final:
  2127. self.fail(message_registry.CANNOT_MAKE_DELETABLE_FINAL, node.node)
  2128. def check_init_subclass(self, defn: ClassDef) -> None:
  2129. """Check that keywords in a class definition are valid arguments for __init_subclass__().
  2130. In this example:
  2131. 1 class Base:
  2132. 2 def __init_subclass__(cls, thing: int):
  2133. 3 pass
  2134. 4 class Child(Base, thing=5):
  2135. 5 def __init_subclass__(cls):
  2136. 6 pass
  2137. 7 Child()
  2138. Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here.
  2139. Child.__init_subclass__ is never called.
  2140. """
  2141. if defn.info.metaclass_type and defn.info.metaclass_type.type.fullname not in (
  2142. "builtins.type",
  2143. "abc.ABCMeta",
  2144. ):
  2145. # We can't safely check situations when both __init_subclass__ and a custom
  2146. # metaclass are present.
  2147. return
  2148. # At runtime, only Base.__init_subclass__ will be called, so
  2149. # we skip the current class itself.
  2150. for base in defn.info.mro[1:]:
  2151. if "__init_subclass__" not in base.names:
  2152. continue
  2153. name_expr = NameExpr(defn.name)
  2154. name_expr.node = base
  2155. callee = MemberExpr(name_expr, "__init_subclass__")
  2156. args = list(defn.keywords.values())
  2157. arg_names: list[str | None] = list(defn.keywords.keys())
  2158. # 'metaclass' keyword is consumed by the rest of the type machinery,
  2159. # and is never passed to __init_subclass__ implementations
  2160. if "metaclass" in arg_names:
  2161. idx = arg_names.index("metaclass")
  2162. arg_names.pop(idx)
  2163. args.pop(idx)
  2164. arg_kinds = [ARG_NAMED] * len(args)
  2165. call_expr = CallExpr(callee, args, arg_kinds, arg_names)
  2166. call_expr.line = defn.line
  2167. call_expr.column = defn.column
  2168. call_expr.end_line = defn.end_line
  2169. self.expr_checker.accept(call_expr, allow_none_return=True, always_allow_any=True)
  2170. # We are only interested in the first Base having __init_subclass__,
  2171. # all other bases have already been checked.
  2172. break
  2173. def check_enum(self, defn: ClassDef) -> None:
  2174. assert defn.info.is_enum
  2175. if defn.info.fullname not in ENUM_BASES:
  2176. for sym in defn.info.names.values():
  2177. if (
  2178. isinstance(sym.node, Var)
  2179. and sym.node.has_explicit_value
  2180. and sym.node.name == "__members__"
  2181. ):
  2182. # `__members__` will always be overwritten by `Enum` and is considered
  2183. # read-only so we disallow assigning a value to it
  2184. self.fail(message_registry.ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDEN, sym.node)
  2185. for base in defn.info.mro[1:-1]: # we don't need self and `object`
  2186. if base.is_enum and base.fullname not in ENUM_BASES:
  2187. self.check_final_enum(defn, base)
  2188. self.check_enum_bases(defn)
  2189. self.check_enum_new(defn)
  2190. def check_final_enum(self, defn: ClassDef, base: TypeInfo) -> None:
  2191. for sym in base.names.values():
  2192. if self.is_final_enum_value(sym):
  2193. self.fail(f'Cannot extend enum with existing members: "{base.name}"', defn)
  2194. break
  2195. def is_final_enum_value(self, sym: SymbolTableNode) -> bool:
  2196. if isinstance(sym.node, (FuncBase, Decorator)):
  2197. return False # A method is fine
  2198. if not isinstance(sym.node, Var):
  2199. return True # Can be a class or anything else
  2200. # Now, only `Var` is left, we need to check:
  2201. # 1. Private name like in `__prop = 1`
  2202. # 2. Dunder name like `__hash__ = some_hasher`
  2203. # 3. Sunder name like `_order_ = 'a, b, c'`
  2204. # 4. If it is a method / descriptor like in `method = classmethod(func)`
  2205. if (
  2206. is_private(sym.node.name)
  2207. or is_dunder(sym.node.name)
  2208. or is_sunder(sym.node.name)
  2209. # TODO: make sure that `x = @class/staticmethod(func)`
  2210. # and `x = property(prop)` both work correctly.
  2211. # Now they are incorrectly counted as enum members.
  2212. or isinstance(get_proper_type(sym.node.type), FunctionLike)
  2213. ):
  2214. return False
  2215. return self.is_stub or sym.node.has_explicit_value
  2216. def check_enum_bases(self, defn: ClassDef) -> None:
  2217. """
  2218. Non-enum mixins cannot appear after enum bases; this is disallowed at runtime:
  2219. class Foo: ...
  2220. class Bar(enum.Enum, Foo): ...
  2221. But any number of enum mixins can appear in a class definition
  2222. (even if multiple enum bases define __new__). So this is fine:
  2223. class Foo(enum.Enum):
  2224. def __new__(cls, val): ...
  2225. class Bar(enum.Enum):
  2226. def __new__(cls, val): ...
  2227. class Baz(int, Foo, Bar, enum.Flag): ...
  2228. """
  2229. enum_base: Instance | None = None
  2230. for base in defn.info.bases:
  2231. if enum_base is None and base.type.is_enum:
  2232. enum_base = base
  2233. continue
  2234. elif enum_base is not None and not base.type.is_enum:
  2235. self.fail(
  2236. f'No non-enum mixin classes are allowed after "{enum_base.str_with_options(self.options)}"',
  2237. defn,
  2238. )
  2239. break
  2240. def check_enum_new(self, defn: ClassDef) -> None:
  2241. def has_new_method(info: TypeInfo) -> bool:
  2242. new_method = info.get("__new__")
  2243. return bool(
  2244. new_method
  2245. and new_method.node
  2246. and new_method.node.fullname != "builtins.object.__new__"
  2247. )
  2248. has_new = False
  2249. for base in defn.info.bases:
  2250. candidate = False
  2251. if base.type.is_enum:
  2252. # If we have an `Enum`, then we need to check all its bases.
  2253. candidate = any(not b.is_enum and has_new_method(b) for b in base.type.mro[1:-1])
  2254. else:
  2255. candidate = has_new_method(base.type)
  2256. if candidate and has_new:
  2257. self.fail(
  2258. "Only a single data type mixin is allowed for Enum subtypes, "
  2259. 'found extra "{}"'.format(base.str_with_options(self.options)),
  2260. defn,
  2261. )
  2262. elif candidate:
  2263. has_new = True
  2264. def check_protocol_variance(self, defn: ClassDef) -> None:
  2265. """Check that protocol definition is compatible with declared
  2266. variances of type variables.
  2267. Note that we also prohibit declaring protocol classes as invariant
  2268. if they are actually covariant/contravariant, since this may break
  2269. transitivity of subtyping, see PEP 544.
  2270. """
  2271. info = defn.info
  2272. object_type = Instance(info.mro[-1], [])
  2273. tvars = info.defn.type_vars
  2274. for i, tvar in enumerate(tvars):
  2275. up_args: list[Type] = [
  2276. object_type if i == j else AnyType(TypeOfAny.special_form)
  2277. for j, _ in enumerate(tvars)
  2278. ]
  2279. down_args: list[Type] = [
  2280. UninhabitedType() if i == j else AnyType(TypeOfAny.special_form)
  2281. for j, _ in enumerate(tvars)
  2282. ]
  2283. up, down = Instance(info, up_args), Instance(info, down_args)
  2284. # TODO: add advanced variance checks for recursive protocols
  2285. if is_subtype(down, up, ignore_declared_variance=True):
  2286. expected = COVARIANT
  2287. elif is_subtype(up, down, ignore_declared_variance=True):
  2288. expected = CONTRAVARIANT
  2289. else:
  2290. expected = INVARIANT
  2291. if isinstance(tvar, TypeVarType) and expected != tvar.variance:
  2292. self.msg.bad_proto_variance(tvar.variance, tvar.name, expected, defn)
  2293. def check_multiple_inheritance(self, typ: TypeInfo) -> None:
  2294. """Check for multiple inheritance related errors."""
  2295. if len(typ.bases) <= 1:
  2296. # No multiple inheritance.
  2297. return
  2298. # Verify that inherited attributes are compatible.
  2299. mro = typ.mro[1:]
  2300. for i, base in enumerate(mro):
  2301. # Attributes defined in both the type and base are skipped.
  2302. # Normal checks for attribute compatibility should catch any problems elsewhere.
  2303. non_overridden_attrs = base.names.keys() - typ.names.keys()
  2304. for name in non_overridden_attrs:
  2305. if is_private(name):
  2306. continue
  2307. for base2 in mro[i + 1 :]:
  2308. # We only need to check compatibility of attributes from classes not
  2309. # in a subclass relationship. For subclasses, normal (single inheritance)
  2310. # checks suffice (these are implemented elsewhere).
  2311. if name in base2.names and base2 not in base.mro:
  2312. self.check_compatibility(name, base, base2, typ)
  2313. def determine_type_of_member(self, sym: SymbolTableNode) -> Type | None:
  2314. if sym.type is not None:
  2315. return sym.type
  2316. if isinstance(sym.node, FuncBase):
  2317. return self.function_type(sym.node)
  2318. if isinstance(sym.node, TypeInfo):
  2319. if sym.node.typeddict_type:
  2320. # We special-case TypedDict, because they don't define any constructor.
  2321. return self.expr_checker.typeddict_callable(sym.node)
  2322. else:
  2323. return type_object_type(sym.node, self.named_type)
  2324. if isinstance(sym.node, TypeVarExpr):
  2325. # Use of TypeVars is rejected in an expression/runtime context, so
  2326. # we don't need to check supertype compatibility for them.
  2327. return AnyType(TypeOfAny.special_form)
  2328. if isinstance(sym.node, TypeAlias):
  2329. with self.msg.filter_errors():
  2330. # Suppress any errors, they will be given when analyzing the corresponding node.
  2331. # Here we may have incorrect options and location context.
  2332. return self.expr_checker.alias_type_in_runtime_context(sym.node, ctx=sym.node)
  2333. # TODO: handle more node kinds here.
  2334. return None
  2335. def check_compatibility(
  2336. self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: TypeInfo
  2337. ) -> None:
  2338. """Check if attribute name in base1 is compatible with base2 in multiple inheritance.
  2339. Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have
  2340. a direct subclass relationship (i.e., the compatibility requirement only derives from
  2341. multiple inheritance).
  2342. This check verifies that a definition taken from base1 (and mapped to the current
  2343. class ctx), is type compatible with the definition taken from base2 (also mapped), so
  2344. that unsafe subclassing like this can be detected:
  2345. class A(Generic[T]):
  2346. def foo(self, x: T) -> None: ...
  2347. class B:
  2348. def foo(self, x: str) -> None: ...
  2349. class C(B, A[int]): ... # this is unsafe because...
  2350. x: A[int] = C()
  2351. x.foo # ...runtime type is (str) -> None, while static type is (int) -> None
  2352. """
  2353. if name in ("__init__", "__new__", "__init_subclass__"):
  2354. # __init__ and friends can be incompatible -- it's a special case.
  2355. return
  2356. first = base1.names[name]
  2357. second = base2.names[name]
  2358. first_type = get_proper_type(self.determine_type_of_member(first))
  2359. second_type = get_proper_type(self.determine_type_of_member(second))
  2360. # start with the special case that Instance can be a subtype of FunctionLike
  2361. call = None
  2362. if isinstance(first_type, Instance):
  2363. call = find_member("__call__", first_type, first_type, is_operator=True)
  2364. if call and isinstance(second_type, FunctionLike):
  2365. second_sig = self.bind_and_map_method(second, second_type, ctx, base2)
  2366. ok = is_subtype(call, second_sig, ignore_pos_arg_names=True)
  2367. elif isinstance(first_type, FunctionLike) and isinstance(second_type, FunctionLike):
  2368. if first_type.is_type_obj() and second_type.is_type_obj():
  2369. # For class objects only check the subtype relationship of the classes,
  2370. # since we allow incompatible overrides of '__init__'/'__new__'
  2371. ok = is_subtype(
  2372. left=fill_typevars_with_any(first_type.type_object()),
  2373. right=fill_typevars_with_any(second_type.type_object()),
  2374. )
  2375. else:
  2376. # First bind/map method types when necessary.
  2377. first_sig = self.bind_and_map_method(first, first_type, ctx, base1)
  2378. second_sig = self.bind_and_map_method(second, second_type, ctx, base2)
  2379. ok = is_subtype(first_sig, second_sig, ignore_pos_arg_names=True)
  2380. elif first_type and second_type:
  2381. if isinstance(first.node, Var):
  2382. first_type = expand_self_type(first.node, first_type, fill_typevars(ctx))
  2383. if isinstance(second.node, Var):
  2384. second_type = expand_self_type(second.node, second_type, fill_typevars(ctx))
  2385. ok = is_equivalent(first_type, second_type)
  2386. if not ok:
  2387. second_node = base2[name].node
  2388. if (
  2389. isinstance(second_type, FunctionLike)
  2390. and second_node is not None
  2391. and is_property(second_node)
  2392. ):
  2393. second_type = get_property_type(second_type)
  2394. ok = is_subtype(first_type, second_type)
  2395. else:
  2396. if first_type is None:
  2397. self.msg.cannot_determine_type_in_base(name, base1.name, ctx)
  2398. if second_type is None:
  2399. self.msg.cannot_determine_type_in_base(name, base2.name, ctx)
  2400. ok = True
  2401. # Final attributes can never be overridden, but can override
  2402. # non-final read-only attributes.
  2403. if is_final_node(second.node):
  2404. self.msg.cant_override_final(name, base2.name, ctx)
  2405. if is_final_node(first.node):
  2406. self.check_if_final_var_override_writable(name, second.node, ctx)
  2407. # Some attributes like __slots__ and __deletable__ are special, and the type can
  2408. # vary across class hierarchy.
  2409. if isinstance(second.node, Var) and second.node.allow_incompatible_override:
  2410. ok = True
  2411. if not ok:
  2412. self.msg.base_class_definitions_incompatible(name, base1, base2, ctx)
  2413. def check_metaclass_compatibility(self, typ: TypeInfo) -> None:
  2414. """Ensures that metaclasses of all parent types are compatible."""
  2415. if (
  2416. typ.is_metaclass()
  2417. or typ.is_protocol
  2418. or typ.is_named_tuple
  2419. or typ.is_enum
  2420. or typ.typeddict_type is not None
  2421. ):
  2422. return # Reasonable exceptions from this check
  2423. metaclasses = [
  2424. entry.metaclass_type
  2425. for entry in typ.mro[1:-1]
  2426. if entry.metaclass_type
  2427. and not is_named_instance(entry.metaclass_type, "builtins.type")
  2428. ]
  2429. if not metaclasses:
  2430. return
  2431. if typ.metaclass_type is not None and all(
  2432. is_subtype(typ.metaclass_type, meta) for meta in metaclasses
  2433. ):
  2434. return
  2435. self.fail(
  2436. "Metaclass conflict: the metaclass of a derived class must be "
  2437. "a (non-strict) subclass of the metaclasses of all its bases",
  2438. typ,
  2439. )
  2440. def visit_import_from(self, node: ImportFrom) -> None:
  2441. self.check_import(node)
  2442. def visit_import_all(self, node: ImportAll) -> None:
  2443. self.check_import(node)
  2444. def visit_import(self, node: Import) -> None:
  2445. self.check_import(node)
  2446. def check_import(self, node: ImportBase) -> None:
  2447. for assign in node.assignments:
  2448. lvalue = assign.lvalues[0]
  2449. lvalue_type, _, __ = self.check_lvalue(lvalue)
  2450. if lvalue_type is None:
  2451. # TODO: This is broken.
  2452. lvalue_type = AnyType(TypeOfAny.special_form)
  2453. assert isinstance(assign.rvalue, NameExpr)
  2454. message = message_registry.INCOMPATIBLE_IMPORT_OF.format(assign.rvalue.name)
  2455. self.check_simple_assignment(
  2456. lvalue_type,
  2457. assign.rvalue,
  2458. node,
  2459. msg=message,
  2460. lvalue_name="local name",
  2461. rvalue_name="imported name",
  2462. )
  2463. #
  2464. # Statements
  2465. #
  2466. def visit_block(self, b: Block) -> None:
  2467. if b.is_unreachable:
  2468. # This block was marked as being unreachable during semantic analysis.
  2469. # It turns out any blocks marked in this way are *intentionally* marked
  2470. # as unreachable -- so we don't display an error.
  2471. self.binder.unreachable()
  2472. return
  2473. for s in b.body:
  2474. if self.binder.is_unreachable():
  2475. if not self.should_report_unreachable_issues():
  2476. break
  2477. if not self.is_noop_for_reachability(s):
  2478. self.msg.unreachable_statement(s)
  2479. break
  2480. else:
  2481. self.accept(s)
  2482. def should_report_unreachable_issues(self) -> bool:
  2483. return (
  2484. self.in_checked_function()
  2485. and self.options.warn_unreachable
  2486. and not self.current_node_deferred
  2487. and not self.binder.is_unreachable_warning_suppressed()
  2488. )
  2489. def is_noop_for_reachability(self, s: Statement) -> bool:
  2490. """Returns 'true' if the given statement either throws an error of some kind
  2491. or is a no-op.
  2492. We use this function while handling the '--warn-unreachable' flag. When
  2493. that flag is present, we normally report an error on any unreachable statement.
  2494. But if that statement is just something like a 'pass' or a just-in-case 'assert False',
  2495. reporting an error would be annoying.
  2496. """
  2497. if isinstance(s, AssertStmt) and is_false_literal(s.expr):
  2498. return True
  2499. elif isinstance(s, (RaiseStmt, PassStmt)):
  2500. return True
  2501. elif isinstance(s, ExpressionStmt):
  2502. if isinstance(s.expr, EllipsisExpr):
  2503. return True
  2504. elif isinstance(s.expr, CallExpr):
  2505. with self.expr_checker.msg.filter_errors():
  2506. typ = get_proper_type(
  2507. self.expr_checker.accept(
  2508. s.expr, allow_none_return=True, always_allow_any=True
  2509. )
  2510. )
  2511. if isinstance(typ, UninhabitedType):
  2512. return True
  2513. return False
  2514. def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
  2515. """Type check an assignment statement.
  2516. Handle all kinds of assignment statements (simple, indexed, multiple).
  2517. """
  2518. # Avoid type checking type aliases in stubs to avoid false
  2519. # positives about modern type syntax available in stubs such
  2520. # as X | Y.
  2521. if not (s.is_alias_def and self.is_stub):
  2522. with self.enter_final_context(s.is_final_def):
  2523. self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
  2524. if s.is_alias_def:
  2525. self.check_type_alias_rvalue(s)
  2526. if (
  2527. s.type is not None
  2528. and self.options.disallow_any_unimported
  2529. and has_any_from_unimported_type(s.type)
  2530. ):
  2531. if isinstance(s.lvalues[-1], TupleExpr):
  2532. # This is a multiple assignment. Instead of figuring out which type is problematic,
  2533. # give a generic error message.
  2534. self.msg.unimported_type_becomes_any(
  2535. "A type on this line", AnyType(TypeOfAny.special_form), s
  2536. )
  2537. else:
  2538. self.msg.unimported_type_becomes_any("Type of variable", s.type, s)
  2539. check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)
  2540. if len(s.lvalues) > 1:
  2541. # Chained assignment (e.g. x = y = ...).
  2542. # Make sure that rvalue type will not be reinferred.
  2543. if not self.has_type(s.rvalue):
  2544. self.expr_checker.accept(s.rvalue)
  2545. rvalue = self.temp_node(self.lookup_type(s.rvalue), s)
  2546. for lv in s.lvalues[:-1]:
  2547. with self.enter_final_context(s.is_final_def):
  2548. self.check_assignment(lv, rvalue, s.type is None)
  2549. self.check_final(s)
  2550. if (
  2551. s.is_final_def
  2552. and s.type
  2553. and not has_no_typevars(s.type)
  2554. and self.scope.active_class() is not None
  2555. ):
  2556. self.fail(message_registry.DEPENDENT_FINAL_IN_CLASS_BODY, s)
  2557. if s.unanalyzed_type and not self.in_checked_function():
  2558. self.msg.annotation_in_unchecked_function(context=s)
  2559. def check_type_alias_rvalue(self, s: AssignmentStmt) -> None:
  2560. alias_type = self.expr_checker.accept(s.rvalue)
  2561. self.store_type(s.lvalues[-1], alias_type)
  2562. def check_assignment(
  2563. self,
  2564. lvalue: Lvalue,
  2565. rvalue: Expression,
  2566. infer_lvalue_type: bool = True,
  2567. new_syntax: bool = False,
  2568. ) -> None:
  2569. """Type check a single assignment: lvalue = rvalue."""
  2570. if isinstance(lvalue, (TupleExpr, ListExpr)):
  2571. self.check_assignment_to_multiple_lvalues(
  2572. lvalue.items, rvalue, rvalue, infer_lvalue_type
  2573. )
  2574. else:
  2575. self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, "=")
  2576. lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)
  2577. # If we're assigning to __getattr__ or similar methods, check that the signature is
  2578. # valid.
  2579. if isinstance(lvalue, NameExpr) and lvalue.node:
  2580. name = lvalue.node.name
  2581. if name in ("__setattr__", "__getattribute__", "__getattr__"):
  2582. # If an explicit type is given, use that.
  2583. if lvalue_type:
  2584. signature = lvalue_type
  2585. else:
  2586. signature = self.expr_checker.accept(rvalue)
  2587. if signature:
  2588. if name == "__setattr__":
  2589. self.check_setattr_method(signature, lvalue)
  2590. else:
  2591. self.check_getattr_method(signature, lvalue, name)
  2592. if name == "__slots__":
  2593. typ = lvalue_type or self.expr_checker.accept(rvalue)
  2594. self.check_slots_definition(typ, lvalue)
  2595. if name == "__match_args__" and inferred is not None:
  2596. typ = self.expr_checker.accept(rvalue)
  2597. self.check_match_args(inferred, typ, lvalue)
  2598. if name == "__post_init__":
  2599. if dataclasses_plugin.is_processed_dataclass(self.scope.active_class()):
  2600. self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue)
  2601. # Defer PartialType's super type checking.
  2602. if (
  2603. isinstance(lvalue, RefExpr)
  2604. and not (isinstance(lvalue_type, PartialType) and lvalue_type.type is None)
  2605. and not (isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__")
  2606. ):
  2607. if self.check_compatibility_all_supers(lvalue, lvalue_type, rvalue):
  2608. # We hit an error on this line; don't check for any others
  2609. return
  2610. if isinstance(lvalue, MemberExpr) and lvalue.name == "__match_args__":
  2611. self.fail(message_registry.CANNOT_MODIFY_MATCH_ARGS, lvalue)
  2612. if lvalue_type:
  2613. if isinstance(lvalue_type, PartialType) and lvalue_type.type is None:
  2614. # Try to infer a proper type for a variable with a partial None type.
  2615. rvalue_type = self.expr_checker.accept(rvalue)
  2616. if isinstance(get_proper_type(rvalue_type), NoneType):
  2617. # This doesn't actually provide any additional information -- multiple
  2618. # None initializers preserve the partial None type.
  2619. return
  2620. var = lvalue_type.var
  2621. if is_valid_inferred_type(rvalue_type, is_lvalue_final=var.is_final):
  2622. partial_types = self.find_partial_types(var)
  2623. if partial_types is not None:
  2624. if not self.current_node_deferred:
  2625. # Partial type can't be final, so strip any literal values.
  2626. rvalue_type = remove_instance_last_known_values(rvalue_type)
  2627. inferred_type = make_simplified_union([rvalue_type, NoneType()])
  2628. self.set_inferred_type(var, lvalue, inferred_type)
  2629. else:
  2630. var.type = None
  2631. del partial_types[var]
  2632. lvalue_type = var.type
  2633. else:
  2634. # Try to infer a partial type. No need to check the return value, as
  2635. # an error will be reported elsewhere.
  2636. self.infer_partial_type(lvalue_type.var, lvalue, rvalue_type)
  2637. # Handle None PartialType's super type checking here, after it's resolved.
  2638. if isinstance(lvalue, RefExpr) and self.check_compatibility_all_supers(
  2639. lvalue, lvalue_type, rvalue
  2640. ):
  2641. # We hit an error on this line; don't check for any others
  2642. return
  2643. elif (
  2644. is_literal_none(rvalue)
  2645. and isinstance(lvalue, NameExpr)
  2646. and isinstance(lvalue.node, Var)
  2647. and lvalue.node.is_initialized_in_class
  2648. and not new_syntax
  2649. ):
  2650. # Allow None's to be assigned to class variables with non-Optional types.
  2651. rvalue_type = lvalue_type
  2652. elif (
  2653. isinstance(lvalue, MemberExpr) and lvalue.kind is None
  2654. ): # Ignore member access to modules
  2655. instance_type = self.expr_checker.accept(lvalue.expr)
  2656. rvalue_type, lvalue_type, infer_lvalue_type = self.check_member_assignment(
  2657. instance_type, lvalue_type, rvalue, context=rvalue
  2658. )
  2659. else:
  2660. # Hacky special case for assigning a literal None
  2661. # to a variable defined in a previous if
  2662. # branch. When we detect this, we'll go back and
  2663. # make the type optional. This is somewhat
  2664. # unpleasant, and a generalization of this would
  2665. # be an improvement!
  2666. if (
  2667. is_literal_none(rvalue)
  2668. and isinstance(lvalue, NameExpr)
  2669. and lvalue.kind == LDEF
  2670. and isinstance(lvalue.node, Var)
  2671. and lvalue.node.type
  2672. and lvalue.node in self.var_decl_frames
  2673. and not isinstance(get_proper_type(lvalue_type), AnyType)
  2674. ):
  2675. decl_frame_map = self.var_decl_frames[lvalue.node]
  2676. # Check if the nearest common ancestor frame for the definition site
  2677. # and the current site is the enclosing frame of an if/elif/else block.
  2678. has_if_ancestor = False
  2679. for frame in reversed(self.binder.frames):
  2680. if frame.id in decl_frame_map:
  2681. has_if_ancestor = frame.conditional_frame
  2682. break
  2683. if has_if_ancestor:
  2684. lvalue_type = make_optional_type(lvalue_type)
  2685. self.set_inferred_type(lvalue.node, lvalue, lvalue_type)
  2686. rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, context=rvalue)
  2687. # Special case: only non-abstract non-protocol classes can be assigned to
  2688. # variables with explicit type Type[A], where A is protocol or abstract.
  2689. p_rvalue_type = get_proper_type(rvalue_type)
  2690. p_lvalue_type = get_proper_type(lvalue_type)
  2691. if (
  2692. isinstance(p_rvalue_type, CallableType)
  2693. and p_rvalue_type.is_type_obj()
  2694. and (
  2695. p_rvalue_type.type_object().is_abstract
  2696. or p_rvalue_type.type_object().is_protocol
  2697. )
  2698. and isinstance(p_lvalue_type, TypeType)
  2699. and isinstance(p_lvalue_type.item, Instance)
  2700. and (
  2701. p_lvalue_type.item.type.is_abstract or p_lvalue_type.item.type.is_protocol
  2702. )
  2703. ):
  2704. self.msg.concrete_only_assign(p_lvalue_type, rvalue)
  2705. return
  2706. if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):
  2707. # Don't use type binder for definitions of special forms, like named tuples.
  2708. if not (isinstance(lvalue, NameExpr) and lvalue.is_special_form):
  2709. self.binder.assign_type(lvalue, rvalue_type, lvalue_type, False)
  2710. elif index_lvalue:
  2711. self.check_indexed_assignment(index_lvalue, rvalue, lvalue)
  2712. if inferred:
  2713. type_context = self.get_variable_type_context(inferred)
  2714. rvalue_type = self.expr_checker.accept(rvalue, type_context=type_context)
  2715. if not (
  2716. inferred.is_final
  2717. or (isinstance(lvalue, NameExpr) and lvalue.name == "__match_args__")
  2718. ):
  2719. rvalue_type = remove_instance_last_known_values(rvalue_type)
  2720. self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue)
  2721. self.check_assignment_to_slots(lvalue)
  2722. # (type, operator) tuples for augmented assignments supported with partial types
  2723. partial_type_augmented_ops: Final = {("builtins.list", "+"), ("builtins.set", "|")}
  2724. def get_variable_type_context(self, inferred: Var) -> Type | None:
  2725. type_contexts = []
  2726. if inferred.info:
  2727. for base in inferred.info.mro[1:]:
  2728. base_type, base_node = self.lvalue_type_from_base(inferred, base)
  2729. if (
  2730. base_type
  2731. and not (isinstance(base_node, Var) and base_node.invalid_partial_type)
  2732. and not isinstance(base_type, PartialType)
  2733. ):
  2734. type_contexts.append(base_type)
  2735. # Use most derived supertype as type context if available.
  2736. if not type_contexts:
  2737. return None
  2738. candidate = type_contexts[0]
  2739. for other in type_contexts:
  2740. if is_proper_subtype(other, candidate):
  2741. candidate = other
  2742. elif not is_subtype(candidate, other):
  2743. # Multiple incompatible candidates, cannot use any of them as context.
  2744. return None
  2745. return candidate
  2746. def try_infer_partial_generic_type_from_assignment(
  2747. self, lvalue: Lvalue, rvalue: Expression, op: str
  2748. ) -> None:
  2749. """Try to infer a precise type for partial generic type from assignment.
  2750. 'op' is '=' for normal assignment and a binary operator ('+', ...) for
  2751. augmented assignment.
  2752. Example where this happens:
  2753. x = []
  2754. if foo():
  2755. x = [1] # Infer List[int] as type of 'x'
  2756. """
  2757. var = None
  2758. if (
  2759. isinstance(lvalue, NameExpr)
  2760. and isinstance(lvalue.node, Var)
  2761. and isinstance(lvalue.node.type, PartialType)
  2762. ):
  2763. var = lvalue.node
  2764. elif isinstance(lvalue, MemberExpr):
  2765. var = self.expr_checker.get_partial_self_var(lvalue)
  2766. if var is not None:
  2767. typ = var.type
  2768. assert isinstance(typ, PartialType)
  2769. if typ.type is None:
  2770. return
  2771. # Return if this is an unsupported augmented assignment.
  2772. if op != "=" and (typ.type.fullname, op) not in self.partial_type_augmented_ops:
  2773. return
  2774. # TODO: some logic here duplicates the None partial type counterpart
  2775. # inlined in check_assignment(), see #8043.
  2776. partial_types = self.find_partial_types(var)
  2777. if partial_types is None:
  2778. return
  2779. rvalue_type = self.expr_checker.accept(rvalue)
  2780. rvalue_type = get_proper_type(rvalue_type)
  2781. if isinstance(rvalue_type, Instance):
  2782. if rvalue_type.type == typ.type and is_valid_inferred_type(rvalue_type):
  2783. var.type = rvalue_type
  2784. del partial_types[var]
  2785. elif isinstance(rvalue_type, AnyType):
  2786. var.type = fill_typevars_with_any(typ.type)
  2787. del partial_types[var]
  2788. def check_compatibility_all_supers(
  2789. self, lvalue: RefExpr, lvalue_type: Type | None, rvalue: Expression
  2790. ) -> bool:
  2791. lvalue_node = lvalue.node
  2792. # Check if we are a class variable with at least one base class
  2793. if (
  2794. isinstance(lvalue_node, Var)
  2795. and lvalue.kind in (MDEF, None)
  2796. and len(lvalue_node.info.bases) > 0 # None for Vars defined via self
  2797. ):
  2798. for base in lvalue_node.info.mro[1:]:
  2799. tnode = base.names.get(lvalue_node.name)
  2800. if tnode is not None:
  2801. if not self.check_compatibility_classvar_super(lvalue_node, base, tnode.node):
  2802. # Show only one error per variable
  2803. break
  2804. if not self.check_compatibility_final_super(lvalue_node, base, tnode.node):
  2805. # Show only one error per variable
  2806. break
  2807. direct_bases = lvalue_node.info.direct_base_classes()
  2808. last_immediate_base = direct_bases[-1] if direct_bases else None
  2809. for base in lvalue_node.info.mro[1:]:
  2810. # The type of "__slots__" and some other attributes usually doesn't need to
  2811. # be compatible with a base class. We'll still check the type of "__slots__"
  2812. # against "object" as an exception.
  2813. if lvalue_node.allow_incompatible_override and not (
  2814. lvalue_node.name == "__slots__" and base.fullname == "builtins.object"
  2815. ):
  2816. continue
  2817. if is_private(lvalue_node.name):
  2818. continue
  2819. base_type, base_node = self.lvalue_type_from_base(lvalue_node, base)
  2820. if isinstance(base_type, PartialType):
  2821. base_type = None
  2822. if base_type:
  2823. assert base_node is not None
  2824. if not self.check_compatibility_super(
  2825. lvalue, lvalue_type, rvalue, base, base_type, base_node
  2826. ):
  2827. # Only show one error per variable; even if other
  2828. # base classes are also incompatible
  2829. return True
  2830. if base is last_immediate_base:
  2831. # At this point, the attribute was found to be compatible with all
  2832. # immediate parents.
  2833. break
  2834. return False
  2835. def check_compatibility_super(
  2836. self,
  2837. lvalue: RefExpr,
  2838. lvalue_type: Type | None,
  2839. rvalue: Expression,
  2840. base: TypeInfo,
  2841. base_type: Type,
  2842. base_node: Node,
  2843. ) -> bool:
  2844. lvalue_node = lvalue.node
  2845. assert isinstance(lvalue_node, Var)
  2846. # Do not check whether the rvalue is compatible if the
  2847. # lvalue had a type defined; this is handled by other
  2848. # parts, and all we have to worry about in that case is
  2849. # that lvalue is compatible with the base class.
  2850. compare_node = None
  2851. if lvalue_type:
  2852. compare_type = lvalue_type
  2853. compare_node = lvalue.node
  2854. else:
  2855. compare_type = self.expr_checker.accept(rvalue, base_type)
  2856. if isinstance(rvalue, NameExpr):
  2857. compare_node = rvalue.node
  2858. if isinstance(compare_node, Decorator):
  2859. compare_node = compare_node.func
  2860. base_type = get_proper_type(base_type)
  2861. compare_type = get_proper_type(compare_type)
  2862. if compare_type:
  2863. if isinstance(base_type, CallableType) and isinstance(compare_type, CallableType):
  2864. base_static = is_node_static(base_node)
  2865. compare_static = is_node_static(compare_node)
  2866. # In case compare_static is unknown, also check
  2867. # if 'definition' is set. The most common case for
  2868. # this is with TempNode(), where we lose all
  2869. # information about the real rvalue node (but only get
  2870. # the rvalue type)
  2871. if compare_static is None and compare_type.definition:
  2872. compare_static = is_node_static(compare_type.definition)
  2873. # Compare against False, as is_node_static can return None
  2874. if base_static is False and compare_static is False:
  2875. # Class-level function objects and classmethods become bound
  2876. # methods: the former to the instance, the latter to the
  2877. # class
  2878. base_type = bind_self(base_type, self.scope.active_self_type())
  2879. compare_type = bind_self(compare_type, self.scope.active_self_type())
  2880. # If we are a static method, ensure to also tell the
  2881. # lvalue it now contains a static method
  2882. if base_static and compare_static:
  2883. lvalue_node.is_staticmethod = True
  2884. return self.check_subtype(
  2885. compare_type,
  2886. base_type,
  2887. rvalue,
  2888. message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,
  2889. "expression has type",
  2890. f'base class "{base.name}" defined the type as',
  2891. )
  2892. return True
  2893. def lvalue_type_from_base(
  2894. self, expr_node: Var, base: TypeInfo
  2895. ) -> tuple[Type | None, Node | None]:
  2896. """For a NameExpr that is part of a class, walk all base classes and try
  2897. to find the first class that defines a Type for the same name."""
  2898. expr_name = expr_node.name
  2899. base_var = base.names.get(expr_name)
  2900. if base_var:
  2901. base_node = base_var.node
  2902. base_type = base_var.type
  2903. if isinstance(base_node, Var) and base_type is not None:
  2904. base_type = expand_self_type(base_node, base_type, fill_typevars(expr_node.info))
  2905. if isinstance(base_node, Decorator):
  2906. base_node = base_node.func
  2907. base_type = base_node.type
  2908. if base_type:
  2909. if not has_no_typevars(base_type):
  2910. self_type = self.scope.active_self_type()
  2911. assert self_type is not None, "Internal error: base lookup outside class"
  2912. if isinstance(self_type, TupleType):
  2913. instance = tuple_fallback(self_type)
  2914. else:
  2915. instance = self_type
  2916. itype = map_instance_to_supertype(instance, base)
  2917. base_type = expand_type_by_instance(base_type, itype)
  2918. base_type = get_proper_type(base_type)
  2919. if isinstance(base_type, CallableType) and isinstance(base_node, FuncDef):
  2920. # If we are a property, return the Type of the return
  2921. # value, not the Callable
  2922. if base_node.is_property:
  2923. base_type = get_proper_type(base_type.ret_type)
  2924. if isinstance(base_type, FunctionLike) and isinstance(
  2925. base_node, OverloadedFuncDef
  2926. ):
  2927. # Same for properties with setter
  2928. if base_node.is_property:
  2929. base_type = base_type.items[0].ret_type
  2930. return base_type, base_node
  2931. return None, None
  2932. def check_compatibility_classvar_super(
  2933. self, node: Var, base: TypeInfo, base_node: Node | None
  2934. ) -> bool:
  2935. if not isinstance(base_node, Var):
  2936. return True
  2937. if node.is_classvar and not base_node.is_classvar:
  2938. self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name), node)
  2939. return False
  2940. elif not node.is_classvar and base_node.is_classvar:
  2941. self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name), node)
  2942. return False
  2943. return True
  2944. def check_compatibility_final_super(
  2945. self, node: Var, base: TypeInfo, base_node: Node | None
  2946. ) -> bool:
  2947. """Check if an assignment overrides a final attribute in a base class.
  2948. This only checks situations where either a node in base class is not a variable
  2949. but a final method, or where override is explicitly declared as final.
  2950. In these cases we give a more detailed error message. In addition, we check that
  2951. a final variable doesn't override writeable attribute, which is not safe.
  2952. Other situations are checked in `check_final()`.
  2953. """
  2954. if not isinstance(base_node, (Var, FuncBase, Decorator)):
  2955. return True
  2956. if base_node.is_final and (node.is_final or not isinstance(base_node, Var)):
  2957. # Give this error only for explicit override attempt with `Final`, or
  2958. # if we are overriding a final method with variable.
  2959. # Other override attempts will be flagged as assignment to constant
  2960. # in `check_final()`.
  2961. self.msg.cant_override_final(node.name, base.name, node)
  2962. return False
  2963. if node.is_final:
  2964. if base.fullname in ENUM_BASES or node.name in ENUM_SPECIAL_PROPS:
  2965. return True
  2966. self.check_if_final_var_override_writable(node.name, base_node, node)
  2967. return True
  2968. def check_if_final_var_override_writable(
  2969. self, name: str, base_node: Node | None, ctx: Context
  2970. ) -> None:
  2971. """Check that a final variable doesn't override writeable attribute.
  2972. This is done to prevent situations like this:
  2973. class C:
  2974. attr = 1
  2975. class D(C):
  2976. attr: Final = 2
  2977. x: C = D()
  2978. x.attr = 3 # Oops!
  2979. """
  2980. writable = True
  2981. if base_node:
  2982. writable = self.is_writable_attribute(base_node)
  2983. if writable:
  2984. self.msg.final_cant_override_writable(name, ctx)
  2985. def get_final_context(self) -> bool:
  2986. """Check whether we a currently checking a final declaration."""
  2987. return self._is_final_def
  2988. @contextmanager
  2989. def enter_final_context(self, is_final_def: bool) -> Iterator[None]:
  2990. """Store whether the current checked assignment is a final declaration."""
  2991. old_ctx = self._is_final_def
  2992. self._is_final_def = is_final_def
  2993. try:
  2994. yield
  2995. finally:
  2996. self._is_final_def = old_ctx
  2997. def check_final(self, s: AssignmentStmt | OperatorAssignmentStmt | AssignmentExpr) -> None:
  2998. """Check if this assignment does not assign to a final attribute.
  2999. This function performs the check only for name assignments at module
  3000. and class scope. The assignments to `obj.attr` and `Cls.attr` are checked
  3001. in checkmember.py.
  3002. """
  3003. if isinstance(s, AssignmentStmt):
  3004. lvs = self.flatten_lvalues(s.lvalues)
  3005. elif isinstance(s, AssignmentExpr):
  3006. lvs = [s.target]
  3007. else:
  3008. lvs = [s.lvalue]
  3009. is_final_decl = s.is_final_def if isinstance(s, AssignmentStmt) else False
  3010. if is_final_decl and self.scope.active_class():
  3011. lv = lvs[0]
  3012. assert isinstance(lv, RefExpr)
  3013. if lv.node is not None:
  3014. assert isinstance(lv.node, Var)
  3015. if (
  3016. lv.node.final_unset_in_class
  3017. and not lv.node.final_set_in_init
  3018. and not self.is_stub
  3019. and # It is OK to skip initializer in stub files.
  3020. # Avoid extra error messages, if there is no type in Final[...],
  3021. # then we already reported the error about missing r.h.s.
  3022. isinstance(s, AssignmentStmt)
  3023. and s.type is not None
  3024. ):
  3025. self.msg.final_without_value(s)
  3026. for lv in lvs:
  3027. if isinstance(lv, RefExpr) and isinstance(lv.node, Var):
  3028. name = lv.node.name
  3029. cls = self.scope.active_class()
  3030. if cls is not None:
  3031. # These additional checks exist to give more error messages
  3032. # even if the final attribute was overridden with a new symbol
  3033. # (which is itself an error)...
  3034. for base in cls.mro[1:]:
  3035. sym = base.names.get(name)
  3036. # We only give this error if base node is variable,
  3037. # overriding final method will be caught in
  3038. # `check_compatibility_final_super()`.
  3039. if sym and isinstance(sym.node, Var):
  3040. if sym.node.is_final and not is_final_decl:
  3041. self.msg.cant_assign_to_final(name, sym.node.info is None, s)
  3042. # ...but only once
  3043. break
  3044. if lv.node.is_final and not is_final_decl:
  3045. self.msg.cant_assign_to_final(name, lv.node.info is None, s)
  3046. def check_assignment_to_slots(self, lvalue: Lvalue) -> None:
  3047. if not isinstance(lvalue, MemberExpr):
  3048. return
  3049. inst = get_proper_type(self.expr_checker.accept(lvalue.expr))
  3050. if not isinstance(inst, Instance):
  3051. return
  3052. if inst.type.slots is None:
  3053. return # Slots do not exist, we can allow any assignment
  3054. if lvalue.name in inst.type.slots:
  3055. return # We are assigning to an existing slot
  3056. for base_info in inst.type.mro[:-1]:
  3057. if base_info.names.get("__setattr__") is not None:
  3058. # When type has `__setattr__` defined,
  3059. # we can assign any dynamic value.
  3060. # We exclude object, because it always has `__setattr__`.
  3061. return
  3062. definition = inst.type.get(lvalue.name)
  3063. if definition is None:
  3064. # We don't want to duplicate
  3065. # `"SomeType" has no attribute "some_attr"`
  3066. # error twice.
  3067. return
  3068. if self.is_assignable_slot(lvalue, definition.type):
  3069. return
  3070. self.fail(
  3071. message_registry.NAME_NOT_IN_SLOTS.format(lvalue.name, inst.type.fullname), lvalue
  3072. )
  3073. def is_assignable_slot(self, lvalue: Lvalue, typ: Type | None) -> bool:
  3074. if getattr(lvalue, "node", None):
  3075. return False # This is a definition
  3076. typ = get_proper_type(typ)
  3077. if typ is None or isinstance(typ, AnyType):
  3078. return True # Any can be literally anything, like `@propery`
  3079. if isinstance(typ, Instance):
  3080. # When working with instances, we need to know if they contain
  3081. # `__set__` special method. Like `@property` does.
  3082. # This makes assigning to properties possible,
  3083. # even without extra slot spec.
  3084. return typ.type.get("__set__") is not None
  3085. if isinstance(typ, FunctionLike):
  3086. return True # Can be a property, or some other magic
  3087. if isinstance(typ, UnionType):
  3088. return all(self.is_assignable_slot(lvalue, u) for u in typ.items)
  3089. return False
  3090. def check_assignment_to_multiple_lvalues(
  3091. self,
  3092. lvalues: list[Lvalue],
  3093. rvalue: Expression,
  3094. context: Context,
  3095. infer_lvalue_type: bool = True,
  3096. ) -> None:
  3097. if isinstance(rvalue, (TupleExpr, ListExpr)):
  3098. # Recursively go into Tuple or List expression rhs instead of
  3099. # using the type of rhs, because this allowed more fine grained
  3100. # control in cases like: a, b = [int, str] where rhs would get
  3101. # type List[object]
  3102. rvalues: list[Expression] = []
  3103. iterable_type: Type | None = None
  3104. last_idx: int | None = None
  3105. for idx_rval, rval in enumerate(rvalue.items):
  3106. if isinstance(rval, StarExpr):
  3107. typs = get_proper_type(self.expr_checker.accept(rval.expr))
  3108. if isinstance(typs, TupleType):
  3109. rvalues.extend([TempNode(typ) for typ in typs.items])
  3110. elif self.type_is_iterable(typs) and isinstance(typs, Instance):
  3111. if iterable_type is not None and iterable_type != self.iterable_item_type(
  3112. typs, rvalue
  3113. ):
  3114. self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)
  3115. else:
  3116. if last_idx is None or last_idx + 1 == idx_rval:
  3117. rvalues.append(rval)
  3118. last_idx = idx_rval
  3119. iterable_type = self.iterable_item_type(typs, rvalue)
  3120. else:
  3121. self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)
  3122. else:
  3123. self.fail(message_registry.ITERABLE_TYPE_EXPECTED.format(typs), context)
  3124. else:
  3125. rvalues.append(rval)
  3126. iterable_start: int | None = None
  3127. iterable_end: int | None = None
  3128. for i, rval in enumerate(rvalues):
  3129. if isinstance(rval, StarExpr):
  3130. typs = get_proper_type(self.expr_checker.accept(rval.expr))
  3131. if self.type_is_iterable(typs) and isinstance(typs, Instance):
  3132. if iterable_start is None:
  3133. iterable_start = i
  3134. iterable_end = i
  3135. if (
  3136. iterable_start is not None
  3137. and iterable_end is not None
  3138. and iterable_type is not None
  3139. ):
  3140. iterable_num = iterable_end - iterable_start + 1
  3141. rvalue_needed = len(lvalues) - (len(rvalues) - iterable_num)
  3142. if rvalue_needed > 0:
  3143. rvalues = (
  3144. rvalues[0:iterable_start]
  3145. + [TempNode(iterable_type) for i in range(rvalue_needed)]
  3146. + rvalues[iterable_end + 1 :]
  3147. )
  3148. if self.check_rvalue_count_in_assignment(lvalues, len(rvalues), context):
  3149. star_index = next(
  3150. (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
  3151. )
  3152. left_lvs = lvalues[:star_index]
  3153. star_lv = (
  3154. cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
  3155. )
  3156. right_lvs = lvalues[star_index + 1 :]
  3157. left_rvs, star_rvs, right_rvs = self.split_around_star(
  3158. rvalues, star_index, len(lvalues)
  3159. )
  3160. lr_pairs = list(zip(left_lvs, left_rvs))
  3161. if star_lv:
  3162. rv_list = ListExpr(star_rvs)
  3163. rv_list.set_line(rvalue)
  3164. lr_pairs.append((star_lv.expr, rv_list))
  3165. lr_pairs.extend(zip(right_lvs, right_rvs))
  3166. for lv, rv in lr_pairs:
  3167. self.check_assignment(lv, rv, infer_lvalue_type)
  3168. else:
  3169. self.check_multi_assignment(lvalues, rvalue, context, infer_lvalue_type)
  3170. def check_rvalue_count_in_assignment(
  3171. self, lvalues: list[Lvalue], rvalue_count: int, context: Context
  3172. ) -> bool:
  3173. if any(isinstance(lvalue, StarExpr) for lvalue in lvalues):
  3174. if len(lvalues) - 1 > rvalue_count:
  3175. self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues) - 1, context)
  3176. return False
  3177. elif rvalue_count != len(lvalues):
  3178. self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues), context)
  3179. return False
  3180. return True
  3181. def check_multi_assignment(
  3182. self,
  3183. lvalues: list[Lvalue],
  3184. rvalue: Expression,
  3185. context: Context,
  3186. infer_lvalue_type: bool = True,
  3187. rv_type: Type | None = None,
  3188. undefined_rvalue: bool = False,
  3189. ) -> None:
  3190. """Check the assignment of one rvalue to a number of lvalues."""
  3191. # Infer the type of an ordinary rvalue expression.
  3192. # TODO: maybe elsewhere; redundant.
  3193. rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue))
  3194. if isinstance(rvalue_type, TypeVarLikeType):
  3195. rvalue_type = get_proper_type(rvalue_type.upper_bound)
  3196. if isinstance(rvalue_type, UnionType):
  3197. # If this is an Optional type in non-strict Optional code, unwrap it.
  3198. relevant_items = rvalue_type.relevant_items()
  3199. if len(relevant_items) == 1:
  3200. rvalue_type = get_proper_type(relevant_items[0])
  3201. if isinstance(rvalue_type, AnyType):
  3202. for lv in lvalues:
  3203. if isinstance(lv, StarExpr):
  3204. lv = lv.expr
  3205. temp_node = self.temp_node(
  3206. AnyType(TypeOfAny.from_another_any, source_any=rvalue_type), context
  3207. )
  3208. self.check_assignment(lv, temp_node, infer_lvalue_type)
  3209. elif isinstance(rvalue_type, TupleType):
  3210. self.check_multi_assignment_from_tuple(
  3211. lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type
  3212. )
  3213. elif isinstance(rvalue_type, UnionType):
  3214. self.check_multi_assignment_from_union(
  3215. lvalues, rvalue, rvalue_type, context, infer_lvalue_type
  3216. )
  3217. elif isinstance(rvalue_type, Instance) and rvalue_type.type.fullname == "builtins.str":
  3218. self.msg.unpacking_strings_disallowed(context)
  3219. else:
  3220. self.check_multi_assignment_from_iterable(
  3221. lvalues, rvalue_type, context, infer_lvalue_type
  3222. )
  3223. def check_multi_assignment_from_union(
  3224. self,
  3225. lvalues: list[Expression],
  3226. rvalue: Expression,
  3227. rvalue_type: UnionType,
  3228. context: Context,
  3229. infer_lvalue_type: bool,
  3230. ) -> None:
  3231. """Check assignment to multiple lvalue targets when rvalue type is a Union[...].
  3232. For example:
  3233. t: Union[Tuple[int, int], Tuple[str, str]]
  3234. x, y = t
  3235. reveal_type(x) # Union[int, str]
  3236. The idea in this case is to process the assignment for every item of the union.
  3237. Important note: the types are collected in two places, 'union_types' contains
  3238. inferred types for first assignments, 'assignments' contains the narrowed types
  3239. for binder.
  3240. """
  3241. self.no_partial_types = True
  3242. transposed: tuple[list[Type], ...] = tuple([] for _ in self.flatten_lvalues(lvalues))
  3243. # Notify binder that we want to defer bindings and instead collect types.
  3244. with self.binder.accumulate_type_assignments() as assignments:
  3245. for item in rvalue_type.items:
  3246. # Type check the assignment separately for each union item and collect
  3247. # the inferred lvalue types for each union item.
  3248. self.check_multi_assignment(
  3249. lvalues,
  3250. rvalue,
  3251. context,
  3252. infer_lvalue_type=infer_lvalue_type,
  3253. rv_type=item,
  3254. undefined_rvalue=True,
  3255. )
  3256. for t, lv in zip(transposed, self.flatten_lvalues(lvalues)):
  3257. # We can access _type_maps directly since temporary type maps are
  3258. # only created within expressions.
  3259. t.append(self._type_maps[0].pop(lv, AnyType(TypeOfAny.special_form)))
  3260. union_types = tuple(make_simplified_union(col) for col in transposed)
  3261. for expr, items in assignments.items():
  3262. # Bind a union of types collected in 'assignments' to every expression.
  3263. if isinstance(expr, StarExpr):
  3264. expr = expr.expr
  3265. # TODO: See todo in binder.py, ConditionalTypeBinder.assign_type
  3266. # It's unclear why the 'declared_type' param is sometimes 'None'
  3267. clean_items: list[tuple[Type, Type]] = []
  3268. for type, declared_type in items:
  3269. assert declared_type is not None
  3270. clean_items.append((type, declared_type))
  3271. types, declared_types = zip(*clean_items)
  3272. self.binder.assign_type(
  3273. expr,
  3274. make_simplified_union(list(types)),
  3275. make_simplified_union(list(declared_types)),
  3276. False,
  3277. )
  3278. for union, lv in zip(union_types, self.flatten_lvalues(lvalues)):
  3279. # Properly store the inferred types.
  3280. _1, _2, inferred = self.check_lvalue(lv)
  3281. if inferred:
  3282. self.set_inferred_type(inferred, lv, union)
  3283. else:
  3284. self.store_type(lv, union)
  3285. self.no_partial_types = False
  3286. def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]:
  3287. res: list[Expression] = []
  3288. for lv in lvalues:
  3289. if isinstance(lv, (TupleExpr, ListExpr)):
  3290. res.extend(self.flatten_lvalues(lv.items))
  3291. if isinstance(lv, StarExpr):
  3292. # Unwrap StarExpr, since it is unwrapped by other helpers.
  3293. lv = lv.expr
  3294. res.append(lv)
  3295. return res
  3296. def check_multi_assignment_from_tuple(
  3297. self,
  3298. lvalues: list[Lvalue],
  3299. rvalue: Expression,
  3300. rvalue_type: TupleType,
  3301. context: Context,
  3302. undefined_rvalue: bool,
  3303. infer_lvalue_type: bool = True,
  3304. ) -> None:
  3305. if self.check_rvalue_count_in_assignment(lvalues, len(rvalue_type.items), context):
  3306. star_index = next(
  3307. (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
  3308. )
  3309. left_lvs = lvalues[:star_index]
  3310. star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
  3311. right_lvs = lvalues[star_index + 1 :]
  3312. if not undefined_rvalue:
  3313. # Infer rvalue again, now in the correct type context.
  3314. lvalue_type = self.lvalue_type_for_inference(lvalues, rvalue_type)
  3315. reinferred_rvalue_type = get_proper_type(
  3316. self.expr_checker.accept(rvalue, lvalue_type)
  3317. )
  3318. if isinstance(reinferred_rvalue_type, UnionType):
  3319. # If this is an Optional type in non-strict Optional code, unwrap it.
  3320. relevant_items = reinferred_rvalue_type.relevant_items()
  3321. if len(relevant_items) == 1:
  3322. reinferred_rvalue_type = get_proper_type(relevant_items[0])
  3323. if isinstance(reinferred_rvalue_type, UnionType):
  3324. self.check_multi_assignment_from_union(
  3325. lvalues, rvalue, reinferred_rvalue_type, context, infer_lvalue_type
  3326. )
  3327. return
  3328. if isinstance(reinferred_rvalue_type, AnyType):
  3329. # We can get Any if the current node is
  3330. # deferred. Doing more inference in deferred nodes
  3331. # is hard, so give up for now. We can also get
  3332. # here if reinferring types above changes the
  3333. # inferred return type for an overloaded function
  3334. # to be ambiguous.
  3335. return
  3336. assert isinstance(reinferred_rvalue_type, TupleType)
  3337. rvalue_type = reinferred_rvalue_type
  3338. left_rv_types, star_rv_types, right_rv_types = self.split_around_star(
  3339. rvalue_type.items, star_index, len(lvalues)
  3340. )
  3341. for lv, rv_type in zip(left_lvs, left_rv_types):
  3342. self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)
  3343. if star_lv:
  3344. list_expr = ListExpr(
  3345. [self.temp_node(rv_type, context) for rv_type in star_rv_types]
  3346. )
  3347. list_expr.set_line(context)
  3348. self.check_assignment(star_lv.expr, list_expr, infer_lvalue_type)
  3349. for lv, rv_type in zip(right_lvs, right_rv_types):
  3350. self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)
  3351. def lvalue_type_for_inference(self, lvalues: list[Lvalue], rvalue_type: TupleType) -> Type:
  3352. star_index = next(
  3353. (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)
  3354. )
  3355. left_lvs = lvalues[:star_index]
  3356. star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None
  3357. right_lvs = lvalues[star_index + 1 :]
  3358. left_rv_types, star_rv_types, right_rv_types = self.split_around_star(
  3359. rvalue_type.items, star_index, len(lvalues)
  3360. )
  3361. type_parameters: list[Type] = []
  3362. def append_types_for_inference(lvs: list[Expression], rv_types: list[Type]) -> None:
  3363. for lv, rv_type in zip(lvs, rv_types):
  3364. sub_lvalue_type, index_expr, inferred = self.check_lvalue(lv)
  3365. if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):
  3366. type_parameters.append(sub_lvalue_type)
  3367. else: # index lvalue
  3368. # TODO Figure out more precise type context, probably
  3369. # based on the type signature of the _set method.
  3370. type_parameters.append(rv_type)
  3371. append_types_for_inference(left_lvs, left_rv_types)
  3372. if star_lv:
  3373. sub_lvalue_type, index_expr, inferred = self.check_lvalue(star_lv.expr)
  3374. if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):
  3375. type_parameters.extend([sub_lvalue_type] * len(star_rv_types))
  3376. else: # index lvalue
  3377. # TODO Figure out more precise type context, probably
  3378. # based on the type signature of the _set method.
  3379. type_parameters.extend(star_rv_types)
  3380. append_types_for_inference(right_lvs, right_rv_types)
  3381. return TupleType(type_parameters, self.named_type("builtins.tuple"))
  3382. def split_around_star(
  3383. self, items: list[T], star_index: int, length: int
  3384. ) -> tuple[list[T], list[T], list[T]]:
  3385. """Splits a list of items in three to match another list of length 'length'
  3386. that contains a starred expression at 'star_index' in the following way:
  3387. star_index = 2, length = 5 (i.e., [a,b,*,c,d]), items = [1,2,3,4,5,6,7]
  3388. returns in: ([1,2], [3,4,5], [6,7])
  3389. """
  3390. nr_right_of_star = length - star_index - 1
  3391. right_index = -nr_right_of_star if nr_right_of_star != 0 else len(items)
  3392. left = items[:star_index]
  3393. star = items[star_index:right_index]
  3394. right = items[right_index:]
  3395. return left, star, right
  3396. def type_is_iterable(self, type: Type) -> bool:
  3397. type = get_proper_type(type)
  3398. if isinstance(type, CallableType) and type.is_type_obj():
  3399. type = type.fallback
  3400. return is_subtype(
  3401. type, self.named_generic_type("typing.Iterable", [AnyType(TypeOfAny.special_form)])
  3402. )
  3403. def check_multi_assignment_from_iterable(
  3404. self,
  3405. lvalues: list[Lvalue],
  3406. rvalue_type: Type,
  3407. context: Context,
  3408. infer_lvalue_type: bool = True,
  3409. ) -> None:
  3410. rvalue_type = get_proper_type(rvalue_type)
  3411. if self.type_is_iterable(rvalue_type) and isinstance(
  3412. rvalue_type, (Instance, CallableType, TypeType, Overloaded)
  3413. ):
  3414. item_type = self.iterable_item_type(rvalue_type, context)
  3415. for lv in lvalues:
  3416. if isinstance(lv, StarExpr):
  3417. items_type = self.named_generic_type("builtins.list", [item_type])
  3418. self.check_assignment(
  3419. lv.expr, self.temp_node(items_type, context), infer_lvalue_type
  3420. )
  3421. else:
  3422. self.check_assignment(
  3423. lv, self.temp_node(item_type, context), infer_lvalue_type
  3424. )
  3425. else:
  3426. self.msg.type_not_iterable(rvalue_type, context)
  3427. def check_lvalue(self, lvalue: Lvalue) -> tuple[Type | None, IndexExpr | None, Var | None]:
  3428. lvalue_type = None
  3429. index_lvalue = None
  3430. inferred = None
  3431. if self.is_definition(lvalue) and (
  3432. not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)
  3433. ):
  3434. if isinstance(lvalue, NameExpr):
  3435. assert isinstance(lvalue.node, Var)
  3436. inferred = lvalue.node
  3437. else:
  3438. assert isinstance(lvalue, MemberExpr)
  3439. self.expr_checker.accept(lvalue.expr)
  3440. inferred = lvalue.def_var
  3441. elif isinstance(lvalue, IndexExpr):
  3442. index_lvalue = lvalue
  3443. elif isinstance(lvalue, MemberExpr):
  3444. lvalue_type = self.expr_checker.analyze_ordinary_member_access(lvalue, True)
  3445. self.store_type(lvalue, lvalue_type)
  3446. elif isinstance(lvalue, NameExpr):
  3447. lvalue_type = self.expr_checker.analyze_ref_expr(lvalue, lvalue=True)
  3448. self.store_type(lvalue, lvalue_type)
  3449. elif isinstance(lvalue, (TupleExpr, ListExpr)):
  3450. types = [
  3451. self.check_lvalue(sub_expr)[0] or
  3452. # This type will be used as a context for further inference of rvalue,
  3453. # we put Uninhabited if there is no information available from lvalue.
  3454. UninhabitedType()
  3455. for sub_expr in lvalue.items
  3456. ]
  3457. lvalue_type = TupleType(types, self.named_type("builtins.tuple"))
  3458. elif isinstance(lvalue, StarExpr):
  3459. lvalue_type, _, _ = self.check_lvalue(lvalue.expr)
  3460. else:
  3461. lvalue_type = self.expr_checker.accept(lvalue)
  3462. return lvalue_type, index_lvalue, inferred
  3463. def is_definition(self, s: Lvalue) -> bool:
  3464. if isinstance(s, NameExpr):
  3465. if s.is_inferred_def:
  3466. return True
  3467. # If the node type is not defined, this must the first assignment
  3468. # that we process => this is a definition, even though the semantic
  3469. # analyzer did not recognize this as such. This can arise in code
  3470. # that uses isinstance checks, if type checking of the primary
  3471. # definition is skipped due to an always False type check.
  3472. node = s.node
  3473. if isinstance(node, Var):
  3474. return node.type is None
  3475. elif isinstance(s, MemberExpr):
  3476. return s.is_inferred_def
  3477. return False
  3478. def infer_variable_type(
  3479. self, name: Var, lvalue: Lvalue, init_type: Type, context: Context
  3480. ) -> None:
  3481. """Infer the type of initialized variables from initializer type."""
  3482. if isinstance(init_type, DeletedType):
  3483. self.msg.deleted_as_rvalue(init_type, context)
  3484. elif (
  3485. not is_valid_inferred_type(init_type, is_lvalue_final=name.is_final)
  3486. and not self.no_partial_types
  3487. ):
  3488. # We cannot use the type of the initialization expression for full type
  3489. # inference (it's not specific enough), but we might be able to give
  3490. # partial type which will be made more specific later. A partial type
  3491. # gets generated in assignment like 'x = []' where item type is not known.
  3492. if not self.infer_partial_type(name, lvalue, init_type):
  3493. self.msg.need_annotation_for_var(name, context, self.options.python_version)
  3494. self.set_inference_error_fallback_type(name, lvalue, init_type)
  3495. elif (
  3496. isinstance(lvalue, MemberExpr)
  3497. and self.inferred_attribute_types is not None
  3498. and lvalue.def_var
  3499. and lvalue.def_var in self.inferred_attribute_types
  3500. and not is_same_type(self.inferred_attribute_types[lvalue.def_var], init_type)
  3501. ):
  3502. # Multiple, inconsistent types inferred for an attribute.
  3503. self.msg.need_annotation_for_var(name, context, self.options.python_version)
  3504. name.type = AnyType(TypeOfAny.from_error)
  3505. else:
  3506. # Infer type of the target.
  3507. # Make the type more general (strip away function names etc.).
  3508. init_type = strip_type(init_type)
  3509. self.set_inferred_type(name, lvalue, init_type)
  3510. def infer_partial_type(self, name: Var, lvalue: Lvalue, init_type: Type) -> bool:
  3511. init_type = get_proper_type(init_type)
  3512. if isinstance(init_type, NoneType):
  3513. partial_type = PartialType(None, name)
  3514. elif isinstance(init_type, Instance):
  3515. fullname = init_type.type.fullname
  3516. is_ref = isinstance(lvalue, RefExpr)
  3517. if (
  3518. is_ref
  3519. and (
  3520. fullname == "builtins.list"
  3521. or fullname == "builtins.set"
  3522. or fullname == "builtins.dict"
  3523. or fullname == "collections.OrderedDict"
  3524. )
  3525. and all(
  3526. isinstance(t, (NoneType, UninhabitedType))
  3527. for t in get_proper_types(init_type.args)
  3528. )
  3529. ):
  3530. partial_type = PartialType(init_type.type, name)
  3531. elif is_ref and fullname == "collections.defaultdict":
  3532. arg0 = get_proper_type(init_type.args[0])
  3533. arg1 = get_proper_type(init_type.args[1])
  3534. if isinstance(
  3535. arg0, (NoneType, UninhabitedType)
  3536. ) and self.is_valid_defaultdict_partial_value_type(arg1):
  3537. arg1 = erase_type(arg1)
  3538. assert isinstance(arg1, Instance)
  3539. partial_type = PartialType(init_type.type, name, arg1)
  3540. else:
  3541. return False
  3542. else:
  3543. return False
  3544. else:
  3545. return False
  3546. self.set_inferred_type(name, lvalue, partial_type)
  3547. self.partial_types[-1].map[name] = lvalue
  3548. return True
  3549. def is_valid_defaultdict_partial_value_type(self, t: ProperType) -> bool:
  3550. """Check if t can be used as the basis for a partial defaultdict value type.
  3551. Examples:
  3552. * t is 'int' --> True
  3553. * t is 'list[<nothing>]' --> True
  3554. * t is 'dict[...]' --> False (only generic types with a single type
  3555. argument supported)
  3556. """
  3557. if not isinstance(t, Instance):
  3558. return False
  3559. if len(t.args) == 0:
  3560. return True
  3561. if len(t.args) == 1:
  3562. arg = get_proper_type(t.args[0])
  3563. # TODO: This is too permissive -- we only allow TypeVarType since
  3564. # they leak in cases like defaultdict(list) due to a bug.
  3565. # This can result in incorrect types being inferred, but only
  3566. # in rare cases.
  3567. if isinstance(arg, (TypeVarType, UninhabitedType, NoneType)):
  3568. return True
  3569. return False
  3570. def set_inferred_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:
  3571. """Store inferred variable type.
  3572. Store the type to both the variable node and the expression node that
  3573. refers to the variable (lvalue). If var is None, do nothing.
  3574. """
  3575. if var and not self.current_node_deferred:
  3576. var.type = type
  3577. var.is_inferred = True
  3578. if var not in self.var_decl_frames:
  3579. # Used for the hack to improve optional type inference in conditionals
  3580. self.var_decl_frames[var] = {frame.id for frame in self.binder.frames}
  3581. if isinstance(lvalue, MemberExpr) and self.inferred_attribute_types is not None:
  3582. # Store inferred attribute type so that we can check consistency afterwards.
  3583. if lvalue.def_var is not None:
  3584. self.inferred_attribute_types[lvalue.def_var] = type
  3585. self.store_type(lvalue, type)
  3586. def set_inference_error_fallback_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:
  3587. """Store best known type for variable if type inference failed.
  3588. If a program ignores error on type inference error, the variable should get some
  3589. inferred type so that if can used later on in the program. Example:
  3590. x = [] # type: ignore
  3591. x.append(1) # Should be ok!
  3592. We implement this here by giving x a valid type (replacing inferred <nothing> with Any).
  3593. """
  3594. fallback = self.inference_error_fallback_type(type)
  3595. self.set_inferred_type(var, lvalue, fallback)
  3596. def inference_error_fallback_type(self, type: Type) -> Type:
  3597. fallback = type.accept(SetNothingToAny())
  3598. # Type variables may leak from inference, see https://github.com/python/mypy/issues/5738,
  3599. # we therefore need to erase them.
  3600. return erase_typevars(fallback)
  3601. def simple_rvalue(self, rvalue: Expression) -> bool:
  3602. """Returns True for expressions for which inferred type should not depend on context.
  3603. Note that this function can still return False for some expressions where inferred type
  3604. does not depend on context. It only exists for performance optimizations.
  3605. """
  3606. if isinstance(rvalue, (IntExpr, StrExpr, BytesExpr, FloatExpr, RefExpr)):
  3607. return True
  3608. if isinstance(rvalue, CallExpr):
  3609. if isinstance(rvalue.callee, RefExpr) and isinstance(rvalue.callee.node, FuncBase):
  3610. typ = rvalue.callee.node.type
  3611. if isinstance(typ, CallableType):
  3612. return not typ.variables
  3613. elif isinstance(typ, Overloaded):
  3614. return not any(item.variables for item in typ.items)
  3615. return False
  3616. def check_simple_assignment(
  3617. self,
  3618. lvalue_type: Type | None,
  3619. rvalue: Expression,
  3620. context: Context,
  3621. msg: ErrorMessage = message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,
  3622. lvalue_name: str = "variable",
  3623. rvalue_name: str = "expression",
  3624. *,
  3625. notes: list[str] | None = None,
  3626. ) -> Type:
  3627. if self.is_stub and isinstance(rvalue, EllipsisExpr):
  3628. # '...' is always a valid initializer in a stub.
  3629. return AnyType(TypeOfAny.special_form)
  3630. else:
  3631. always_allow_any = lvalue_type is not None and not isinstance(
  3632. get_proper_type(lvalue_type), AnyType
  3633. )
  3634. rvalue_type = self.expr_checker.accept(
  3635. rvalue, lvalue_type, always_allow_any=always_allow_any
  3636. )
  3637. if (
  3638. isinstance(get_proper_type(lvalue_type), UnionType)
  3639. # Skip literal types, as they have special logic (for better errors).
  3640. and not isinstance(get_proper_type(rvalue_type), LiteralType)
  3641. and not self.simple_rvalue(rvalue)
  3642. ):
  3643. # Try re-inferring r.h.s. in empty context, and use that if it
  3644. # results in a narrower type. We don't do this always because this
  3645. # may cause some perf impact, plus we want to partially preserve
  3646. # the old behavior. This helps with various practical examples, see
  3647. # e.g. testOptionalTypeNarrowedByGenericCall.
  3648. with self.msg.filter_errors() as local_errors, self.local_type_map() as type_map:
  3649. alt_rvalue_type = self.expr_checker.accept(
  3650. rvalue, None, always_allow_any=always_allow_any
  3651. )
  3652. if (
  3653. not local_errors.has_new_errors()
  3654. # Skip Any type, since it is special cased in binder.
  3655. and not isinstance(get_proper_type(alt_rvalue_type), AnyType)
  3656. and is_valid_inferred_type(alt_rvalue_type)
  3657. and is_proper_subtype(alt_rvalue_type, rvalue_type)
  3658. ):
  3659. rvalue_type = alt_rvalue_type
  3660. self.store_types(type_map)
  3661. if isinstance(rvalue_type, DeletedType):
  3662. self.msg.deleted_as_rvalue(rvalue_type, context)
  3663. if isinstance(lvalue_type, DeletedType):
  3664. self.msg.deleted_as_lvalue(lvalue_type, context)
  3665. elif lvalue_type:
  3666. self.check_subtype(
  3667. # Preserve original aliases for error messages when possible.
  3668. rvalue_type,
  3669. lvalue_type,
  3670. context,
  3671. msg,
  3672. f"{rvalue_name} has type",
  3673. f"{lvalue_name} has type",
  3674. notes=notes,
  3675. )
  3676. return rvalue_type
  3677. def check_member_assignment(
  3678. self, instance_type: Type, attribute_type: Type, rvalue: Expression, context: Context
  3679. ) -> tuple[Type, Type, bool]:
  3680. """Type member assignment.
  3681. This defers to check_simple_assignment, unless the member expression
  3682. is a descriptor, in which case this checks descriptor semantics as well.
  3683. Return the inferred rvalue_type, inferred lvalue_type, and whether to use the binder
  3684. for this assignment.
  3685. Note: this method exists here and not in checkmember.py, because we need to take
  3686. care about interaction between binder and __set__().
  3687. """
  3688. instance_type = get_proper_type(instance_type)
  3689. attribute_type = get_proper_type(attribute_type)
  3690. # Descriptors don't participate in class-attribute access
  3691. if (isinstance(instance_type, FunctionLike) and instance_type.is_type_obj()) or isinstance(
  3692. instance_type, TypeType
  3693. ):
  3694. rvalue_type = self.check_simple_assignment(attribute_type, rvalue, context)
  3695. return rvalue_type, attribute_type, True
  3696. if not isinstance(attribute_type, Instance):
  3697. # TODO: support __set__() for union types.
  3698. rvalue_type = self.check_simple_assignment(attribute_type, rvalue, context)
  3699. return rvalue_type, attribute_type, True
  3700. mx = MemberContext(
  3701. is_lvalue=False,
  3702. is_super=False,
  3703. is_operator=False,
  3704. original_type=instance_type,
  3705. context=context,
  3706. self_type=None,
  3707. msg=self.msg,
  3708. chk=self,
  3709. )
  3710. get_type = analyze_descriptor_access(attribute_type, mx)
  3711. if not attribute_type.type.has_readable_member("__set__"):
  3712. # If there is no __set__, we type-check that the assigned value matches
  3713. # the return type of __get__. This doesn't match the python semantics,
  3714. # (which allow you to override the descriptor with any value), but preserves
  3715. # the type of accessing the attribute (even after the override).
  3716. rvalue_type = self.check_simple_assignment(get_type, rvalue, context)
  3717. return rvalue_type, get_type, True
  3718. dunder_set = attribute_type.type.get_method("__set__")
  3719. if dunder_set is None:
  3720. self.fail(
  3721. message_registry.DESCRIPTOR_SET_NOT_CALLABLE.format(
  3722. attribute_type.str_with_options(self.options)
  3723. ),
  3724. context,
  3725. )
  3726. return AnyType(TypeOfAny.from_error), get_type, False
  3727. bound_method = analyze_decorator_or_funcbase_access(
  3728. defn=dunder_set,
  3729. itype=attribute_type,
  3730. info=attribute_type.type,
  3731. self_type=attribute_type,
  3732. name="__set__",
  3733. mx=mx,
  3734. )
  3735. typ = map_instance_to_supertype(attribute_type, dunder_set.info)
  3736. dunder_set_type = expand_type_by_instance(bound_method, typ)
  3737. callable_name = self.expr_checker.method_fullname(attribute_type, "__set__")
  3738. dunder_set_type = self.expr_checker.transform_callee_type(
  3739. callable_name,
  3740. dunder_set_type,
  3741. [TempNode(instance_type, context=context), rvalue],
  3742. [nodes.ARG_POS, nodes.ARG_POS],
  3743. context,
  3744. object_type=attribute_type,
  3745. )
  3746. # For non-overloaded setters, the result should be type-checked like a regular assignment.
  3747. # Hence, we first only try to infer the type by using the rvalue as type context.
  3748. type_context = rvalue
  3749. with self.msg.filter_errors():
  3750. _, inferred_dunder_set_type = self.expr_checker.check_call(
  3751. dunder_set_type,
  3752. [TempNode(instance_type, context=context), type_context],
  3753. [nodes.ARG_POS, nodes.ARG_POS],
  3754. context,
  3755. object_type=attribute_type,
  3756. callable_name=callable_name,
  3757. )
  3758. # And now we in fact type check the call, to show errors related to wrong arguments
  3759. # count, etc., replacing the type context for non-overloaded setters only.
  3760. inferred_dunder_set_type = get_proper_type(inferred_dunder_set_type)
  3761. if isinstance(inferred_dunder_set_type, CallableType):
  3762. type_context = TempNode(AnyType(TypeOfAny.special_form), context=context)
  3763. self.expr_checker.check_call(
  3764. dunder_set_type,
  3765. [TempNode(instance_type, context=context), type_context],
  3766. [nodes.ARG_POS, nodes.ARG_POS],
  3767. context,
  3768. object_type=attribute_type,
  3769. callable_name=callable_name,
  3770. )
  3771. # In the following cases, a message already will have been recorded in check_call.
  3772. if (not isinstance(inferred_dunder_set_type, CallableType)) or (
  3773. len(inferred_dunder_set_type.arg_types) < 2
  3774. ):
  3775. return AnyType(TypeOfAny.from_error), get_type, False
  3776. set_type = inferred_dunder_set_type.arg_types[1]
  3777. # Special case: if the rvalue_type is a subtype of both '__get__' and '__set__' types,
  3778. # and '__get__' type is narrower than '__set__', then we invoke the binder to narrow type
  3779. # by this assignment. Technically, this is not safe, but in practice this is
  3780. # what a user expects.
  3781. rvalue_type = self.check_simple_assignment(set_type, rvalue, context)
  3782. infer = is_subtype(rvalue_type, get_type) and is_subtype(get_type, set_type)
  3783. return rvalue_type if infer else set_type, get_type, infer
  3784. def check_indexed_assignment(
  3785. self, lvalue: IndexExpr, rvalue: Expression, context: Context
  3786. ) -> None:
  3787. """Type check indexed assignment base[index] = rvalue.
  3788. The lvalue argument is the base[index] expression.
  3789. """
  3790. self.try_infer_partial_type_from_indexed_assignment(lvalue, rvalue)
  3791. basetype = get_proper_type(self.expr_checker.accept(lvalue.base))
  3792. method_type = self.expr_checker.analyze_external_member_access(
  3793. "__setitem__", basetype, lvalue
  3794. )
  3795. lvalue.method_type = method_type
  3796. res_type, _ = self.expr_checker.check_method_call(
  3797. "__setitem__",
  3798. basetype,
  3799. method_type,
  3800. [lvalue.index, rvalue],
  3801. [nodes.ARG_POS, nodes.ARG_POS],
  3802. context,
  3803. )
  3804. res_type = get_proper_type(res_type)
  3805. if isinstance(res_type, UninhabitedType) and not res_type.ambiguous:
  3806. self.binder.unreachable()
  3807. def try_infer_partial_type_from_indexed_assignment(
  3808. self, lvalue: IndexExpr, rvalue: Expression
  3809. ) -> None:
  3810. # TODO: Should we share some of this with try_infer_partial_type?
  3811. var = None
  3812. if isinstance(lvalue.base, RefExpr) and isinstance(lvalue.base.node, Var):
  3813. var = lvalue.base.node
  3814. elif isinstance(lvalue.base, MemberExpr):
  3815. var = self.expr_checker.get_partial_self_var(lvalue.base)
  3816. if isinstance(var, Var):
  3817. if isinstance(var.type, PartialType):
  3818. type_type = var.type.type
  3819. if type_type is None:
  3820. return # The partial type is None.
  3821. partial_types = self.find_partial_types(var)
  3822. if partial_types is None:
  3823. return
  3824. typename = type_type.fullname
  3825. if (
  3826. typename == "builtins.dict"
  3827. or typename == "collections.OrderedDict"
  3828. or typename == "collections.defaultdict"
  3829. ):
  3830. # TODO: Don't infer things twice.
  3831. key_type = self.expr_checker.accept(lvalue.index)
  3832. value_type = self.expr_checker.accept(rvalue)
  3833. if (
  3834. is_valid_inferred_type(key_type)
  3835. and is_valid_inferred_type(value_type)
  3836. and not self.current_node_deferred
  3837. and not (
  3838. typename == "collections.defaultdict"
  3839. and var.type.value_type is not None
  3840. and not is_equivalent(value_type, var.type.value_type)
  3841. )
  3842. ):
  3843. var.type = self.named_generic_type(typename, [key_type, value_type])
  3844. del partial_types[var]
  3845. def type_requires_usage(self, typ: Type) -> tuple[str, ErrorCode] | None:
  3846. """Some types require usage in all cases. The classic example is
  3847. an unused coroutine.
  3848. In the case that it does require usage, returns a note to attach
  3849. to the error message.
  3850. """
  3851. proper_type = get_proper_type(typ)
  3852. if isinstance(proper_type, Instance):
  3853. # We use different error codes for generic awaitable vs coroutine.
  3854. # Coroutines are on by default, whereas generic awaitables are not.
  3855. if proper_type.type.fullname == "typing.Coroutine":
  3856. return ("Are you missing an await?", UNUSED_COROUTINE)
  3857. if proper_type.type.get("__await__") is not None:
  3858. return ("Are you missing an await?", UNUSED_AWAITABLE)
  3859. return None
  3860. def visit_expression_stmt(self, s: ExpressionStmt) -> None:
  3861. expr_type = self.expr_checker.accept(s.expr, allow_none_return=True, always_allow_any=True)
  3862. error_note_and_code = self.type_requires_usage(expr_type)
  3863. if error_note_and_code:
  3864. error_note, code = error_note_and_code
  3865. self.fail(
  3866. message_registry.TYPE_MUST_BE_USED.format(format_type(expr_type, self.options)),
  3867. s,
  3868. code=code,
  3869. )
  3870. self.note(error_note, s, code=code)
  3871. def visit_return_stmt(self, s: ReturnStmt) -> None:
  3872. """Type check a return statement."""
  3873. self.check_return_stmt(s)
  3874. self.binder.unreachable()
  3875. def check_return_stmt(self, s: ReturnStmt) -> None:
  3876. defn = self.scope.top_function()
  3877. if defn is not None:
  3878. if defn.is_generator:
  3879. return_type = self.get_generator_return_type(
  3880. self.return_types[-1], defn.is_coroutine
  3881. )
  3882. elif defn.is_coroutine:
  3883. return_type = self.get_coroutine_return_type(self.return_types[-1])
  3884. else:
  3885. return_type = self.return_types[-1]
  3886. return_type = get_proper_type(return_type)
  3887. if isinstance(return_type, UninhabitedType):
  3888. self.fail(message_registry.NO_RETURN_EXPECTED, s)
  3889. return
  3890. if s.expr:
  3891. is_lambda = isinstance(self.scope.top_function(), LambdaExpr)
  3892. declared_none_return = isinstance(return_type, NoneType)
  3893. declared_any_return = isinstance(return_type, AnyType)
  3894. # This controls whether or not we allow a function call that
  3895. # returns None as the expression of this return statement.
  3896. # E.g. `return f()` for some `f` that returns None. We allow
  3897. # this only if we're in a lambda or in a function that returns
  3898. # `None` or `Any`.
  3899. allow_none_func_call = is_lambda or declared_none_return or declared_any_return
  3900. # Return with a value.
  3901. typ = get_proper_type(
  3902. self.expr_checker.accept(
  3903. s.expr, return_type, allow_none_return=allow_none_func_call
  3904. )
  3905. )
  3906. if defn.is_async_generator:
  3907. self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s)
  3908. return
  3909. # Returning a value of type Any is always fine.
  3910. if isinstance(typ, AnyType):
  3911. # (Unless you asked to be warned in that case, and the
  3912. # function is not declared to return Any)
  3913. if (
  3914. self.options.warn_return_any
  3915. and not self.current_node_deferred
  3916. and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)
  3917. and not (
  3918. defn.name in BINARY_MAGIC_METHODS
  3919. and is_literal_not_implemented(s.expr)
  3920. )
  3921. and not (
  3922. isinstance(return_type, Instance)
  3923. and return_type.type.fullname == "builtins.object"
  3924. )
  3925. and not is_lambda
  3926. ):
  3927. self.msg.incorrectly_returning_any(return_type, s)
  3928. return
  3929. # Disallow return expressions in functions declared to return
  3930. # None, subject to two exceptions below.
  3931. if declared_none_return:
  3932. # Lambdas are allowed to have None returns.
  3933. # Functions returning a value of type None are allowed to have a None return.
  3934. if is_lambda or isinstance(typ, NoneType):
  3935. return
  3936. self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s)
  3937. else:
  3938. self.check_subtype(
  3939. subtype_label="got",
  3940. subtype=typ,
  3941. supertype_label="expected",
  3942. supertype=return_type,
  3943. context=s.expr,
  3944. outer_context=s,
  3945. msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE,
  3946. )
  3947. else:
  3948. # Empty returns are valid in Generators with Any typed returns, but not in
  3949. # coroutines.
  3950. if (
  3951. defn.is_generator
  3952. and not defn.is_coroutine
  3953. and isinstance(return_type, AnyType)
  3954. ):
  3955. return
  3956. if isinstance(return_type, (NoneType, AnyType)):
  3957. return
  3958. if self.in_checked_function():
  3959. self.fail(message_registry.RETURN_VALUE_EXPECTED, s)
  3960. def visit_if_stmt(self, s: IfStmt) -> None:
  3961. """Type check an if statement."""
  3962. # This frame records the knowledge from previous if/elif clauses not being taken.
  3963. # Fall-through to the original frame is handled explicitly in each block.
  3964. with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=0):
  3965. for e, b in zip(s.expr, s.body):
  3966. t = get_proper_type(self.expr_checker.accept(e))
  3967. if isinstance(t, DeletedType):
  3968. self.msg.deleted_as_rvalue(t, s)
  3969. if_map, else_map = self.find_isinstance_check(e)
  3970. # XXX Issue a warning if condition is always False?
  3971. with self.binder.frame_context(can_skip=True, fall_through=2):
  3972. self.push_type_map(if_map)
  3973. self.accept(b)
  3974. # XXX Issue a warning if condition is always True?
  3975. self.push_type_map(else_map)
  3976. with self.binder.frame_context(can_skip=False, fall_through=2):
  3977. if s.else_body:
  3978. self.accept(s.else_body)
  3979. def visit_while_stmt(self, s: WhileStmt) -> None:
  3980. """Type check a while statement."""
  3981. if_stmt = IfStmt([s.expr], [s.body], None)
  3982. if_stmt.set_line(s)
  3983. self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr)
  3984. def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None:
  3985. """Type check an operator assignment statement, e.g. x += 1."""
  3986. self.try_infer_partial_generic_type_from_assignment(s.lvalue, s.rvalue, s.op)
  3987. if isinstance(s.lvalue, MemberExpr):
  3988. # Special case, some additional errors may be given for
  3989. # assignments to read-only or final attributes.
  3990. lvalue_type = self.expr_checker.visit_member_expr(s.lvalue, True)
  3991. else:
  3992. lvalue_type = self.expr_checker.accept(s.lvalue)
  3993. inplace, method = infer_operator_assignment_method(lvalue_type, s.op)
  3994. if inplace:
  3995. # There is __ifoo__, treat as x = x.__ifoo__(y)
  3996. rvalue_type, method_type = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s)
  3997. if not is_subtype(rvalue_type, lvalue_type):
  3998. self.msg.incompatible_operator_assignment(s.op, s)
  3999. else:
  4000. # There is no __ifoo__, treat as x = x <foo> y
  4001. expr = OpExpr(s.op, s.lvalue, s.rvalue)
  4002. expr.set_line(s)
  4003. self.check_assignment(
  4004. lvalue=s.lvalue, rvalue=expr, infer_lvalue_type=True, new_syntax=False
  4005. )
  4006. self.check_final(s)
  4007. def visit_assert_stmt(self, s: AssertStmt) -> None:
  4008. self.expr_checker.accept(s.expr)
  4009. if isinstance(s.expr, TupleExpr) and len(s.expr.items) > 0:
  4010. self.fail(message_registry.MALFORMED_ASSERT, s)
  4011. # If this is asserting some isinstance check, bind that type in the following code
  4012. true_map, else_map = self.find_isinstance_check(s.expr)
  4013. if s.msg is not None:
  4014. self.expr_checker.analyze_cond_branch(else_map, s.msg, None)
  4015. self.push_type_map(true_map)
  4016. def visit_raise_stmt(self, s: RaiseStmt) -> None:
  4017. """Type check a raise statement."""
  4018. if s.expr:
  4019. self.type_check_raise(s.expr, s)
  4020. if s.from_expr:
  4021. self.type_check_raise(s.from_expr, s, optional=True)
  4022. self.binder.unreachable()
  4023. def type_check_raise(self, e: Expression, s: RaiseStmt, optional: bool = False) -> None:
  4024. typ = get_proper_type(self.expr_checker.accept(e))
  4025. if isinstance(typ, DeletedType):
  4026. self.msg.deleted_as_rvalue(typ, e)
  4027. return
  4028. exc_type = self.named_type("builtins.BaseException")
  4029. expected_type_items = [exc_type, TypeType(exc_type)]
  4030. if optional:
  4031. # This is used for `x` part in a case like `raise e from x`,
  4032. # where we allow `raise e from None`.
  4033. expected_type_items.append(NoneType())
  4034. self.check_subtype(
  4035. typ, UnionType.make_union(expected_type_items), s, message_registry.INVALID_EXCEPTION
  4036. )
  4037. if isinstance(typ, FunctionLike):
  4038. # https://github.com/python/mypy/issues/11089
  4039. self.expr_checker.check_call(typ, [], [], e)
  4040. def visit_try_stmt(self, s: TryStmt) -> None:
  4041. """Type check a try statement."""
  4042. # Our enclosing frame will get the result if the try/except falls through.
  4043. # This one gets all possible states after the try block exited abnormally
  4044. # (by exception, return, break, etc.)
  4045. with self.binder.frame_context(can_skip=False, fall_through=0):
  4046. # Not only might the body of the try statement exit
  4047. # abnormally, but so might an exception handler or else
  4048. # clause. The finally clause runs in *all* cases, so we
  4049. # need an outer try frame to catch all intermediate states
  4050. # in case an exception is raised during an except or else
  4051. # clause. As an optimization, only create the outer try
  4052. # frame when there actually is a finally clause.
  4053. self.visit_try_without_finally(s, try_frame=bool(s.finally_body))
  4054. if s.finally_body:
  4055. # First we check finally_body is type safe on all abnormal exit paths
  4056. self.accept(s.finally_body)
  4057. if s.finally_body:
  4058. # Then we try again for the more restricted set of options
  4059. # that can fall through. (Why do we need to check the
  4060. # finally clause twice? Depending on whether the finally
  4061. # clause was reached by the try clause falling off the end
  4062. # or exiting abnormally, after completing the finally clause
  4063. # either flow will continue to after the entire try statement
  4064. # or the exception/return/etc. will be processed and control
  4065. # flow will escape. We need to check that the finally clause
  4066. # type checks in both contexts, but only the resulting types
  4067. # from the latter context affect the type state in the code
  4068. # that follows the try statement.)
  4069. if not self.binder.is_unreachable():
  4070. self.accept(s.finally_body)
  4071. def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:
  4072. """Type check a try statement, ignoring the finally block.
  4073. On entry, the top frame should receive all flow that exits the
  4074. try block abnormally (i.e., such that the else block does not
  4075. execute), and its parent should receive all flow that exits
  4076. the try block normally.
  4077. """
  4078. # This frame will run the else block if the try fell through.
  4079. # In that case, control flow continues to the parent of what
  4080. # was the top frame on entry.
  4081. with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=try_frame):
  4082. # This frame receives exit via exception, and runs exception handlers
  4083. with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=2):
  4084. # Finally, the body of the try statement
  4085. with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=True):
  4086. self.accept(s.body)
  4087. for i in range(len(s.handlers)):
  4088. with self.binder.frame_context(can_skip=True, fall_through=4):
  4089. typ = s.types[i]
  4090. if typ:
  4091. t = self.check_except_handler_test(typ, s.is_star)
  4092. var = s.vars[i]
  4093. if var:
  4094. # To support local variables, we make this a definition line,
  4095. # causing assignment to set the variable's type.
  4096. var.is_inferred_def = True
  4097. self.check_assignment(var, self.temp_node(t, var))
  4098. self.accept(s.handlers[i])
  4099. var = s.vars[i]
  4100. if var:
  4101. # Exception variables are deleted.
  4102. # Unfortunately, this doesn't let us detect usage before the
  4103. # try/except block.
  4104. source = var.name
  4105. if isinstance(var.node, Var):
  4106. var.node.type = DeletedType(source=source)
  4107. self.binder.cleanse(var)
  4108. if s.else_body:
  4109. self.accept(s.else_body)
  4110. def check_except_handler_test(self, n: Expression, is_star: bool) -> Type:
  4111. """Type check an exception handler test clause."""
  4112. typ = self.expr_checker.accept(n)
  4113. all_types: list[Type] = []
  4114. test_types = self.get_types_from_except_handler(typ, n)
  4115. for ttype in get_proper_types(test_types):
  4116. if isinstance(ttype, AnyType):
  4117. all_types.append(ttype)
  4118. continue
  4119. if isinstance(ttype, FunctionLike):
  4120. item = ttype.items[0]
  4121. if not item.is_type_obj():
  4122. self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
  4123. return self.default_exception_type(is_star)
  4124. exc_type = erase_typevars(item.ret_type)
  4125. elif isinstance(ttype, TypeType):
  4126. exc_type = ttype.item
  4127. else:
  4128. self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
  4129. return self.default_exception_type(is_star)
  4130. if not is_subtype(exc_type, self.named_type("builtins.BaseException")):
  4131. self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)
  4132. return self.default_exception_type(is_star)
  4133. all_types.append(exc_type)
  4134. if is_star:
  4135. new_all_types: list[Type] = []
  4136. for typ in all_types:
  4137. if is_proper_subtype(typ, self.named_type("builtins.BaseExceptionGroup")):
  4138. self.fail(message_registry.INVALID_EXCEPTION_GROUP, n)
  4139. new_all_types.append(AnyType(TypeOfAny.from_error))
  4140. else:
  4141. new_all_types.append(typ)
  4142. return self.wrap_exception_group(new_all_types)
  4143. return make_simplified_union(all_types)
  4144. def default_exception_type(self, is_star: bool) -> Type:
  4145. """Exception type to return in case of a previous type error."""
  4146. any_type = AnyType(TypeOfAny.from_error)
  4147. if is_star:
  4148. return self.named_generic_type("builtins.ExceptionGroup", [any_type])
  4149. return any_type
  4150. def wrap_exception_group(self, types: Sequence[Type]) -> Type:
  4151. """Transform except* variable type into an appropriate exception group."""
  4152. arg = make_simplified_union(types)
  4153. if is_subtype(arg, self.named_type("builtins.Exception")):
  4154. base = "builtins.ExceptionGroup"
  4155. else:
  4156. base = "builtins.BaseExceptionGroup"
  4157. return self.named_generic_type(base, [arg])
  4158. def get_types_from_except_handler(self, typ: Type, n: Expression) -> list[Type]:
  4159. """Helper for check_except_handler_test to retrieve handler types."""
  4160. typ = get_proper_type(typ)
  4161. if isinstance(typ, TupleType):
  4162. return typ.items
  4163. elif isinstance(typ, UnionType):
  4164. return [
  4165. union_typ
  4166. for item in typ.relevant_items()
  4167. for union_typ in self.get_types_from_except_handler(item, n)
  4168. ]
  4169. elif is_named_instance(typ, "builtins.tuple"):
  4170. # variadic tuple
  4171. return [typ.args[0]]
  4172. else:
  4173. return [typ]
  4174. def visit_for_stmt(self, s: ForStmt) -> None:
  4175. """Type check a for statement."""
  4176. if s.is_async:
  4177. iterator_type, item_type = self.analyze_async_iterable_item_type(s.expr)
  4178. else:
  4179. iterator_type, item_type = self.analyze_iterable_item_type(s.expr)
  4180. s.inferred_item_type = item_type
  4181. s.inferred_iterator_type = iterator_type
  4182. self.analyze_index_variables(s.index, item_type, s.index_type is None, s)
  4183. self.accept_loop(s.body, s.else_body)
  4184. def analyze_async_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:
  4185. """Analyse async iterable expression and return iterator and iterator item types."""
  4186. echk = self.expr_checker
  4187. iterable = echk.accept(expr)
  4188. iterator = echk.check_method_call_by_name("__aiter__", iterable, [], [], expr)[0]
  4189. awaitable = echk.check_method_call_by_name("__anext__", iterator, [], [], expr)[0]
  4190. item_type = echk.check_awaitable_expr(
  4191. awaitable, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_FOR
  4192. )
  4193. return iterator, item_type
  4194. def analyze_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:
  4195. """Analyse iterable expression and return iterator and iterator item types."""
  4196. echk = self.expr_checker
  4197. iterable = get_proper_type(echk.accept(expr))
  4198. iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], expr)[0]
  4199. int_type = self.analyze_range_native_int_type(expr)
  4200. if int_type:
  4201. return iterator, int_type
  4202. if isinstance(iterable, TupleType):
  4203. joined: Type = UninhabitedType()
  4204. for item in iterable.items:
  4205. joined = join_types(joined, item)
  4206. return iterator, joined
  4207. else:
  4208. # Non-tuple iterable.
  4209. return iterator, echk.check_method_call_by_name("__next__", iterator, [], [], expr)[0]
  4210. def analyze_iterable_item_type_without_expression(
  4211. self, type: Type, context: Context
  4212. ) -> tuple[Type, Type]:
  4213. """Analyse iterable type and return iterator and iterator item types."""
  4214. echk = self.expr_checker
  4215. iterable = get_proper_type(type)
  4216. iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], context)[0]
  4217. if isinstance(iterable, TupleType):
  4218. joined: Type = UninhabitedType()
  4219. for item in iterable.items:
  4220. joined = join_types(joined, item)
  4221. return iterator, joined
  4222. else:
  4223. # Non-tuple iterable.
  4224. return (
  4225. iterator,
  4226. echk.check_method_call_by_name("__next__", iterator, [], [], context)[0],
  4227. )
  4228. def analyze_range_native_int_type(self, expr: Expression) -> Type | None:
  4229. """Try to infer native int item type from arguments to range(...).
  4230. For example, return i64 if the expression is "range(0, i64(n))".
  4231. Return None if unsuccessful.
  4232. """
  4233. if (
  4234. isinstance(expr, CallExpr)
  4235. and isinstance(expr.callee, RefExpr)
  4236. and expr.callee.fullname == "builtins.range"
  4237. and 1 <= len(expr.args) <= 3
  4238. and all(kind == ARG_POS for kind in expr.arg_kinds)
  4239. ):
  4240. native_int: Type | None = None
  4241. ok = True
  4242. for arg in expr.args:
  4243. argt = get_proper_type(self.lookup_type(arg))
  4244. if isinstance(argt, Instance) and argt.type.fullname in MYPYC_NATIVE_INT_NAMES:
  4245. if native_int is None:
  4246. native_int = argt
  4247. elif argt != native_int:
  4248. ok = False
  4249. if ok and native_int:
  4250. return native_int
  4251. return None
  4252. def analyze_container_item_type(self, typ: Type) -> Type | None:
  4253. """Check if a type is a nominal container of a union of such.
  4254. Return the corresponding container item type.
  4255. """
  4256. typ = get_proper_type(typ)
  4257. if isinstance(typ, UnionType):
  4258. types: list[Type] = []
  4259. for item in typ.items:
  4260. c_type = self.analyze_container_item_type(item)
  4261. if c_type:
  4262. types.append(c_type)
  4263. return UnionType.make_union(types)
  4264. if isinstance(typ, Instance) and typ.type.has_base("typing.Container"):
  4265. supertype = self.named_type("typing.Container").type
  4266. super_instance = map_instance_to_supertype(typ, supertype)
  4267. assert len(super_instance.args) == 1
  4268. return super_instance.args[0]
  4269. if isinstance(typ, TupleType):
  4270. return self.analyze_container_item_type(tuple_fallback(typ))
  4271. return None
  4272. def analyze_index_variables(
  4273. self, index: Expression, item_type: Type, infer_lvalue_type: bool, context: Context
  4274. ) -> None:
  4275. """Type check or infer for loop or list comprehension index vars."""
  4276. self.check_assignment(index, self.temp_node(item_type, context), infer_lvalue_type)
  4277. def visit_del_stmt(self, s: DelStmt) -> None:
  4278. if isinstance(s.expr, IndexExpr):
  4279. e = s.expr
  4280. m = MemberExpr(e.base, "__delitem__")
  4281. m.line = s.line
  4282. m.column = s.column
  4283. c = CallExpr(m, [e.index], [nodes.ARG_POS], [None])
  4284. c.line = s.line
  4285. c.column = s.column
  4286. self.expr_checker.accept(c, allow_none_return=True)
  4287. else:
  4288. s.expr.accept(self.expr_checker)
  4289. for elt in flatten(s.expr):
  4290. if isinstance(elt, NameExpr):
  4291. self.binder.assign_type(
  4292. elt, DeletedType(source=elt.name), get_declaration(elt), False
  4293. )
  4294. def visit_decorator(self, e: Decorator) -> None:
  4295. for d in e.decorators:
  4296. if isinstance(d, RefExpr):
  4297. if d.fullname == "typing.no_type_check":
  4298. e.var.type = AnyType(TypeOfAny.special_form)
  4299. e.var.is_ready = True
  4300. return
  4301. if self.recurse_into_functions:
  4302. with self.tscope.function_scope(e.func):
  4303. self.check_func_item(e.func, name=e.func.name)
  4304. # Process decorators from the inside out to determine decorated signature, which
  4305. # may be different from the declared signature.
  4306. sig: Type = self.function_type(e.func)
  4307. for d in reversed(e.decorators):
  4308. if refers_to_fullname(d, OVERLOAD_NAMES):
  4309. self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, e)
  4310. continue
  4311. dec = self.expr_checker.accept(d)
  4312. temp = self.temp_node(sig, context=e)
  4313. fullname = None
  4314. if isinstance(d, RefExpr):
  4315. fullname = d.fullname or None
  4316. # if this is a expression like @b.a where b is an object, get the type of b
  4317. # so we can pass it the method hook in the plugins
  4318. object_type: Type | None = None
  4319. if fullname is None and isinstance(d, MemberExpr) and self.has_type(d.expr):
  4320. object_type = self.lookup_type(d.expr)
  4321. fullname = self.expr_checker.method_fullname(object_type, d.name)
  4322. self.check_for_untyped_decorator(e.func, dec, d)
  4323. sig, t2 = self.expr_checker.check_call(
  4324. dec, [temp], [nodes.ARG_POS], e, callable_name=fullname, object_type=object_type
  4325. )
  4326. self.check_untyped_after_decorator(sig, e.func)
  4327. sig = set_callable_name(sig, e.func)
  4328. e.var.type = sig
  4329. e.var.is_ready = True
  4330. if e.func.is_property:
  4331. if isinstance(sig, CallableType):
  4332. if len([k for k in sig.arg_kinds if k.is_required()]) > 1:
  4333. self.msg.fail("Too many arguments for property", e)
  4334. self.check_incompatible_property_override(e)
  4335. # For overloaded functions we already checked override for overload as a whole.
  4336. if e.func.info and not e.func.is_dynamic() and not e.is_overload:
  4337. found_method_base_classes = self.check_method_override(e)
  4338. if (
  4339. e.func.is_explicit_override
  4340. and not found_method_base_classes
  4341. and found_method_base_classes is not None
  4342. ):
  4343. self.msg.no_overridable_method(e.func.name, e.func)
  4344. self.check_explicit_override_decorator(e.func, found_method_base_classes)
  4345. if e.func.info and e.func.name in ("__init__", "__new__"):
  4346. if e.type and not isinstance(get_proper_type(e.type), (FunctionLike, AnyType)):
  4347. self.fail(message_registry.BAD_CONSTRUCTOR_TYPE, e)
  4348. def check_for_untyped_decorator(
  4349. self, func: FuncDef, dec_type: Type, dec_expr: Expression
  4350. ) -> None:
  4351. if (
  4352. self.options.disallow_untyped_decorators
  4353. and is_typed_callable(func.type)
  4354. and is_untyped_decorator(dec_type)
  4355. ):
  4356. self.msg.typed_function_untyped_decorator(func.name, dec_expr)
  4357. def check_incompatible_property_override(self, e: Decorator) -> None:
  4358. if not e.var.is_settable_property and e.func.info:
  4359. name = e.func.name
  4360. for base in e.func.info.mro[1:]:
  4361. base_attr = base.names.get(name)
  4362. if not base_attr:
  4363. continue
  4364. if (
  4365. isinstance(base_attr.node, OverloadedFuncDef)
  4366. and base_attr.node.is_property
  4367. and cast(Decorator, base_attr.node.items[0]).var.is_settable_property
  4368. ):
  4369. self.fail(message_registry.READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE, e)
  4370. def visit_with_stmt(self, s: WithStmt) -> None:
  4371. exceptions_maybe_suppressed = False
  4372. for expr, target in zip(s.expr, s.target):
  4373. if s.is_async:
  4374. exit_ret_type = self.check_async_with_item(expr, target, s.unanalyzed_type is None)
  4375. else:
  4376. exit_ret_type = self.check_with_item(expr, target, s.unanalyzed_type is None)
  4377. # Based on the return type, determine if this context manager 'swallows'
  4378. # exceptions or not. We determine this using a heuristic based on the
  4379. # return type of the __exit__ method -- see the discussion in
  4380. # https://github.com/python/mypy/issues/7214 and the section about context managers
  4381. # in https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions
  4382. # for more details.
  4383. exit_ret_type = get_proper_type(exit_ret_type)
  4384. if is_literal_type(exit_ret_type, "builtins.bool", False):
  4385. continue
  4386. if is_literal_type(exit_ret_type, "builtins.bool", True) or (
  4387. isinstance(exit_ret_type, Instance)
  4388. and exit_ret_type.type.fullname == "builtins.bool"
  4389. and state.strict_optional
  4390. ):
  4391. # Note: if strict-optional is disabled, this bool instance
  4392. # could actually be an Optional[bool].
  4393. exceptions_maybe_suppressed = True
  4394. if exceptions_maybe_suppressed:
  4395. # Treat this 'with' block in the same way we'd treat a 'try: BODY; except: pass'
  4396. # block. This means control flow can continue after the 'with' even if the 'with'
  4397. # block immediately returns.
  4398. with self.binder.frame_context(can_skip=True, try_frame=True):
  4399. self.accept(s.body)
  4400. else:
  4401. self.accept(s.body)
  4402. def check_untyped_after_decorator(self, typ: Type, func: FuncDef) -> None:
  4403. if not self.options.disallow_any_decorated or self.is_stub:
  4404. return
  4405. if mypy.checkexpr.has_any_type(typ):
  4406. self.msg.untyped_decorated_function(typ, func)
  4407. def check_async_with_item(
  4408. self, expr: Expression, target: Expression | None, infer_lvalue_type: bool
  4409. ) -> Type:
  4410. echk = self.expr_checker
  4411. ctx = echk.accept(expr)
  4412. obj = echk.check_method_call_by_name("__aenter__", ctx, [], [], expr)[0]
  4413. obj = echk.check_awaitable_expr(
  4414. obj, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER
  4415. )
  4416. if target:
  4417. self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)
  4418. arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)
  4419. res, _ = echk.check_method_call_by_name(
  4420. "__aexit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr
  4421. )
  4422. return echk.check_awaitable_expr(
  4423. res, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT
  4424. )
  4425. def check_with_item(
  4426. self, expr: Expression, target: Expression | None, infer_lvalue_type: bool
  4427. ) -> Type:
  4428. echk = self.expr_checker
  4429. ctx = echk.accept(expr)
  4430. obj = echk.check_method_call_by_name("__enter__", ctx, [], [], expr)[0]
  4431. if target:
  4432. self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)
  4433. arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)
  4434. res, _ = echk.check_method_call_by_name(
  4435. "__exit__", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr
  4436. )
  4437. return res
  4438. def visit_break_stmt(self, s: BreakStmt) -> None:
  4439. self.binder.handle_break()
  4440. def visit_continue_stmt(self, s: ContinueStmt) -> None:
  4441. self.binder.handle_continue()
  4442. return None
  4443. def visit_match_stmt(self, s: MatchStmt) -> None:
  4444. with self.binder.frame_context(can_skip=False, fall_through=0):
  4445. subject_type = get_proper_type(self.expr_checker.accept(s.subject))
  4446. if isinstance(subject_type, DeletedType):
  4447. self.msg.deleted_as_rvalue(subject_type, s)
  4448. # We infer types of patterns twice. The first pass is used
  4449. # to infer the types of capture variables. The type of a
  4450. # capture variable may depend on multiple patterns (it
  4451. # will be a union of all capture types). This pass ignores
  4452. # guard expressions.
  4453. pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]
  4454. type_maps: list[TypeMap] = [t.captures for t in pattern_types]
  4455. inferred_types = self.infer_variable_types_from_type_maps(type_maps)
  4456. # The second pass narrows down the types and type checks bodies.
  4457. for p, g, b in zip(s.patterns, s.guards, s.bodies):
  4458. current_subject_type = self.expr_checker.narrow_type_from_binder(
  4459. s.subject, subject_type
  4460. )
  4461. pattern_type = self.pattern_checker.accept(p, current_subject_type)
  4462. with self.binder.frame_context(can_skip=True, fall_through=2):
  4463. if b.is_unreachable or isinstance(
  4464. get_proper_type(pattern_type.type), UninhabitedType
  4465. ):
  4466. self.push_type_map(None)
  4467. else_map: TypeMap = {}
  4468. else:
  4469. pattern_map, else_map = conditional_types_to_typemaps(
  4470. s.subject, pattern_type.type, pattern_type.rest_type
  4471. )
  4472. self.remove_capture_conflicts(pattern_type.captures, inferred_types)
  4473. self.push_type_map(pattern_map)
  4474. self.push_type_map(pattern_type.captures)
  4475. if g is not None:
  4476. with self.binder.frame_context(can_skip=True, fall_through=3):
  4477. gt = get_proper_type(self.expr_checker.accept(g))
  4478. if isinstance(gt, DeletedType):
  4479. self.msg.deleted_as_rvalue(gt, s)
  4480. guard_map, guard_else_map = self.find_isinstance_check(g)
  4481. else_map = or_conditional_maps(else_map, guard_else_map)
  4482. self.push_type_map(guard_map)
  4483. self.accept(b)
  4484. else:
  4485. self.accept(b)
  4486. self.push_type_map(else_map)
  4487. # This is needed due to a quirk in frame_context. Without it types will stay narrowed
  4488. # after the match.
  4489. with self.binder.frame_context(can_skip=False, fall_through=2):
  4490. pass
  4491. def infer_variable_types_from_type_maps(self, type_maps: list[TypeMap]) -> dict[Var, Type]:
  4492. all_captures: dict[Var, list[tuple[NameExpr, Type]]] = defaultdict(list)
  4493. for tm in type_maps:
  4494. if tm is not None:
  4495. for expr, typ in tm.items():
  4496. if isinstance(expr, NameExpr):
  4497. node = expr.node
  4498. assert isinstance(node, Var)
  4499. all_captures[node].append((expr, typ))
  4500. inferred_types: dict[Var, Type] = {}
  4501. for var, captures in all_captures.items():
  4502. already_exists = False
  4503. types: list[Type] = []
  4504. for expr, typ in captures:
  4505. types.append(typ)
  4506. previous_type, _, _ = self.check_lvalue(expr)
  4507. if previous_type is not None:
  4508. already_exists = True
  4509. if self.check_subtype(
  4510. typ,
  4511. previous_type,
  4512. expr,
  4513. msg=message_registry.INCOMPATIBLE_TYPES_IN_CAPTURE,
  4514. subtype_label="pattern captures type",
  4515. supertype_label="variable has type",
  4516. ):
  4517. inferred_types[var] = previous_type
  4518. if not already_exists:
  4519. new_type = UnionType.make_union(types)
  4520. # Infer the union type at the first occurrence
  4521. first_occurrence, _ = captures[0]
  4522. inferred_types[var] = new_type
  4523. self.infer_variable_type(var, first_occurrence, new_type, first_occurrence)
  4524. return inferred_types
  4525. def remove_capture_conflicts(self, type_map: TypeMap, inferred_types: dict[Var, Type]) -> None:
  4526. if type_map:
  4527. for expr, typ in list(type_map.items()):
  4528. if isinstance(expr, NameExpr):
  4529. node = expr.node
  4530. assert isinstance(node, Var)
  4531. if node not in inferred_types or not is_subtype(typ, inferred_types[node]):
  4532. del type_map[expr]
  4533. def make_fake_typeinfo(
  4534. self,
  4535. curr_module_fullname: str,
  4536. class_gen_name: str,
  4537. class_short_name: str,
  4538. bases: list[Instance],
  4539. ) -> tuple[ClassDef, TypeInfo]:
  4540. # Build the fake ClassDef and TypeInfo together.
  4541. # The ClassDef is full of lies and doesn't actually contain a body.
  4542. # Use format_bare to generate a nice name for error messages.
  4543. # We skip fully filling out a handful of TypeInfo fields because they
  4544. # should be irrelevant for a generated type like this:
  4545. # is_protocol, protocol_members, is_abstract
  4546. cdef = ClassDef(class_short_name, Block([]))
  4547. cdef.fullname = curr_module_fullname + "." + class_gen_name
  4548. info = TypeInfo(SymbolTable(), cdef, curr_module_fullname)
  4549. cdef.info = info
  4550. info.bases = bases
  4551. calculate_mro(info)
  4552. info.metaclass_type = info.calculate_metaclass_type()
  4553. return cdef, info
  4554. def intersect_instances(
  4555. self, instances: tuple[Instance, Instance], errors: list[tuple[str, str]]
  4556. ) -> Instance | None:
  4557. """Try creating an ad-hoc intersection of the given instances.
  4558. Note that this function does *not* try and create a full-fledged
  4559. intersection type. Instead, it returns an instance of a new ad-hoc
  4560. subclass of the given instances.
  4561. This is mainly useful when you need a way of representing some
  4562. theoretical subclass of the instances the user may be trying to use
  4563. the generated intersection can serve as a placeholder.
  4564. This function will create a fresh subclass every time you call it,
  4565. even if you pass in the exact same arguments. So this means calling
  4566. `self.intersect_intersection([inst_1, inst_2], ctx)` twice will result
  4567. in instances of two distinct subclasses of inst_1 and inst_2.
  4568. This is by design: we want each ad-hoc intersection to be unique since
  4569. they're supposed represent some other unknown subclass.
  4570. Returns None if creating the subclass is impossible (e.g. due to
  4571. MRO errors or incompatible signatures). If we do successfully create
  4572. a subclass, its TypeInfo will automatically be added to the global scope.
  4573. """
  4574. curr_module = self.scope.stack[0]
  4575. assert isinstance(curr_module, MypyFile)
  4576. # First, retry narrowing while allowing promotions (they are disabled by default
  4577. # for isinstance() checks, etc). This way we will still type-check branches like
  4578. # x: complex = 1
  4579. # if isinstance(x, int):
  4580. # ...
  4581. left, right = instances
  4582. if is_proper_subtype(left, right, ignore_promotions=False):
  4583. return left
  4584. if is_proper_subtype(right, left, ignore_promotions=False):
  4585. return right
  4586. def _get_base_classes(instances_: tuple[Instance, Instance]) -> list[Instance]:
  4587. base_classes_ = []
  4588. for inst in instances_:
  4589. if inst.type.is_intersection:
  4590. expanded = inst.type.bases
  4591. else:
  4592. expanded = [inst]
  4593. for expanded_inst in expanded:
  4594. base_classes_.append(expanded_inst)
  4595. return base_classes_
  4596. def _make_fake_typeinfo_and_full_name(
  4597. base_classes_: list[Instance], curr_module_: MypyFile
  4598. ) -> tuple[TypeInfo, str]:
  4599. names_list = pretty_seq([x.type.name for x in base_classes_], "and")
  4600. short_name = f"<subclass of {names_list}>"
  4601. full_name_ = gen_unique_name(short_name, curr_module_.names)
  4602. cdef, info_ = self.make_fake_typeinfo(
  4603. curr_module_.fullname, full_name_, short_name, base_classes_
  4604. )
  4605. return info_, full_name_
  4606. base_classes = _get_base_classes(instances)
  4607. # We use the pretty_names_list for error messages but can't
  4608. # use it for the real name that goes into the symbol table
  4609. # because it can have dots in it.
  4610. pretty_names_list = pretty_seq(
  4611. format_type_distinctly(*base_classes, options=self.options, bare=True), "and"
  4612. )
  4613. try:
  4614. info, full_name = _make_fake_typeinfo_and_full_name(base_classes, curr_module)
  4615. with self.msg.filter_errors() as local_errors:
  4616. self.check_multiple_inheritance(info)
  4617. if local_errors.has_new_errors():
  4618. # "class A(B, C)" unsafe, now check "class A(C, B)":
  4619. base_classes = _get_base_classes(instances[::-1])
  4620. info, full_name = _make_fake_typeinfo_and_full_name(base_classes, curr_module)
  4621. with self.msg.filter_errors() as local_errors:
  4622. self.check_multiple_inheritance(info)
  4623. info.is_intersection = True
  4624. except MroError:
  4625. errors.append((pretty_names_list, "inconsistent method resolution order"))
  4626. return None
  4627. if local_errors.has_new_errors():
  4628. errors.append((pretty_names_list, "incompatible method signatures"))
  4629. return None
  4630. curr_module.names[full_name] = SymbolTableNode(GDEF, info)
  4631. return Instance(info, [], extra_attrs=instances[0].extra_attrs or instances[1].extra_attrs)
  4632. def intersect_instance_callable(self, typ: Instance, callable_type: CallableType) -> Instance:
  4633. """Creates a fake type that represents the intersection of an Instance and a CallableType.
  4634. It operates by creating a bare-minimum dummy TypeInfo that
  4635. subclasses type and adds a __call__ method matching callable_type.
  4636. """
  4637. # In order for this to work in incremental mode, the type we generate needs to
  4638. # have a valid fullname and a corresponding entry in a symbol table. We generate
  4639. # a unique name inside the symbol table of the current module.
  4640. cur_module = self.scope.stack[0]
  4641. assert isinstance(cur_module, MypyFile)
  4642. gen_name = gen_unique_name(f"<callable subtype of {typ.type.name}>", cur_module.names)
  4643. # Synthesize a fake TypeInfo
  4644. short_name = format_type_bare(typ, self.options)
  4645. cdef, info = self.make_fake_typeinfo(cur_module.fullname, gen_name, short_name, [typ])
  4646. # Build up a fake FuncDef so we can populate the symbol table.
  4647. func_def = FuncDef("__call__", [], Block([]), callable_type)
  4648. func_def._fullname = cdef.fullname + ".__call__"
  4649. func_def.info = info
  4650. info.names["__call__"] = SymbolTableNode(MDEF, func_def)
  4651. cur_module.names[gen_name] = SymbolTableNode(GDEF, info)
  4652. return Instance(info, [], extra_attrs=typ.extra_attrs)
  4653. def make_fake_callable(self, typ: Instance) -> Instance:
  4654. """Produce a new type that makes type Callable with a generic callable type."""
  4655. fallback = self.named_type("builtins.function")
  4656. callable_type = CallableType(
  4657. [AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)],
  4658. [nodes.ARG_STAR, nodes.ARG_STAR2],
  4659. [None, None],
  4660. ret_type=AnyType(TypeOfAny.explicit),
  4661. fallback=fallback,
  4662. is_ellipsis_args=True,
  4663. )
  4664. return self.intersect_instance_callable(typ, callable_type)
  4665. def partition_by_callable(
  4666. self, typ: Type, unsound_partition: bool
  4667. ) -> tuple[list[Type], list[Type]]:
  4668. """Partitions a type into callable subtypes and uncallable subtypes.
  4669. Thus, given:
  4670. `callables, uncallables = partition_by_callable(type)`
  4671. If we assert `callable(type)` then `type` has type Union[*callables], and
  4672. If we assert `not callable(type)` then `type` has type Union[*uncallables]
  4673. If unsound_partition is set, assume that anything that is not
  4674. clearly callable is in fact not callable. Otherwise we generate a
  4675. new subtype that *is* callable.
  4676. Guaranteed to not return [], [].
  4677. """
  4678. typ = get_proper_type(typ)
  4679. if isinstance(typ, (FunctionLike, TypeType)):
  4680. return [typ], []
  4681. if isinstance(typ, AnyType):
  4682. return [typ], [typ]
  4683. if isinstance(typ, NoneType):
  4684. return [], [typ]
  4685. if isinstance(typ, UnionType):
  4686. callables = []
  4687. uncallables = []
  4688. for subtype in typ.items:
  4689. # Use unsound_partition when handling unions in order to
  4690. # allow the expected type discrimination.
  4691. subcallables, subuncallables = self.partition_by_callable(
  4692. subtype, unsound_partition=True
  4693. )
  4694. callables.extend(subcallables)
  4695. uncallables.extend(subuncallables)
  4696. return callables, uncallables
  4697. if isinstance(typ, TypeVarType):
  4698. # We could do better probably?
  4699. # Refine the the type variable's bound as our type in the case that
  4700. # callable() is true. This unfortunately loses the information that
  4701. # the type is a type variable in that branch.
  4702. # This matches what is done for isinstance, but it may be possible to
  4703. # do better.
  4704. # If it is possible for the false branch to execute, return the original
  4705. # type to avoid losing type information.
  4706. callables, uncallables = self.partition_by_callable(
  4707. erase_to_union_or_bound(typ), unsound_partition
  4708. )
  4709. uncallables = [typ] if uncallables else []
  4710. return callables, uncallables
  4711. # A TupleType is callable if its fallback is, but needs special handling
  4712. # when we dummy up a new type.
  4713. ityp = typ
  4714. if isinstance(typ, TupleType):
  4715. ityp = tuple_fallback(typ)
  4716. if isinstance(ityp, Instance):
  4717. method = ityp.type.get_method("__call__")
  4718. if method and method.type:
  4719. callables, uncallables = self.partition_by_callable(
  4720. method.type, unsound_partition=False
  4721. )
  4722. if callables and not uncallables:
  4723. # Only consider the type callable if its __call__ method is
  4724. # definitely callable.
  4725. return [typ], []
  4726. if not unsound_partition:
  4727. fake = self.make_fake_callable(ityp)
  4728. if isinstance(typ, TupleType):
  4729. fake.type.tuple_type = TupleType(typ.items, fake)
  4730. return [fake.type.tuple_type], [typ]
  4731. return [fake], [typ]
  4732. if unsound_partition:
  4733. return [], [typ]
  4734. else:
  4735. # We don't know how properly make the type callable.
  4736. return [typ], [typ]
  4737. def conditional_callable_type_map(
  4738. self, expr: Expression, current_type: Type | None
  4739. ) -> tuple[TypeMap, TypeMap]:
  4740. """Takes in an expression and the current type of the expression.
  4741. Returns a 2-tuple: The first element is a map from the expression to
  4742. the restricted type if it were callable. The second element is a
  4743. map from the expression to the type it would hold if it weren't
  4744. callable.
  4745. """
  4746. if not current_type:
  4747. return {}, {}
  4748. if isinstance(get_proper_type(current_type), AnyType):
  4749. return {}, {}
  4750. callables, uncallables = self.partition_by_callable(current_type, unsound_partition=False)
  4751. if callables and uncallables:
  4752. callable_map = {expr: UnionType.make_union(callables)} if callables else None
  4753. uncallable_map = {expr: UnionType.make_union(uncallables)} if uncallables else None
  4754. return callable_map, uncallable_map
  4755. elif callables:
  4756. return {}, None
  4757. return None, {}
  4758. def conditional_types_for_iterable(
  4759. self, item_type: Type, iterable_type: Type
  4760. ) -> tuple[Type | None, Type | None]:
  4761. """
  4762. Narrows the type of `iterable_type` based on the type of `item_type`.
  4763. For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s).
  4764. """
  4765. if_types: list[Type] = []
  4766. else_types: list[Type] = []
  4767. iterable_type = get_proper_type(iterable_type)
  4768. if isinstance(iterable_type, UnionType):
  4769. possible_iterable_types = get_proper_types(iterable_type.relevant_items())
  4770. else:
  4771. possible_iterable_types = [iterable_type]
  4772. item_str_literals = try_getting_str_literals_from_type(item_type)
  4773. for possible_iterable_type in possible_iterable_types:
  4774. if item_str_literals and isinstance(possible_iterable_type, TypedDictType):
  4775. for key in item_str_literals:
  4776. if key in possible_iterable_type.required_keys:
  4777. if_types.append(possible_iterable_type)
  4778. elif (
  4779. key in possible_iterable_type.items or not possible_iterable_type.is_final
  4780. ):
  4781. if_types.append(possible_iterable_type)
  4782. else_types.append(possible_iterable_type)
  4783. else:
  4784. else_types.append(possible_iterable_type)
  4785. else:
  4786. if_types.append(possible_iterable_type)
  4787. else_types.append(possible_iterable_type)
  4788. return (
  4789. UnionType.make_union(if_types) if if_types else None,
  4790. UnionType.make_union(else_types) if else_types else None,
  4791. )
  4792. def _is_truthy_type(self, t: ProperType) -> bool:
  4793. return (
  4794. (
  4795. isinstance(t, Instance)
  4796. and bool(t.type)
  4797. and not t.type.has_readable_member("__bool__")
  4798. and not t.type.has_readable_member("__len__")
  4799. and t.type.fullname != "builtins.object"
  4800. )
  4801. or isinstance(t, FunctionLike)
  4802. or (
  4803. isinstance(t, UnionType)
  4804. and all(self._is_truthy_type(t) for t in get_proper_types(t.items))
  4805. )
  4806. )
  4807. def _check_for_truthy_type(self, t: Type, expr: Expression) -> None:
  4808. if not state.strict_optional:
  4809. return # if everything can be None, all bets are off
  4810. t = get_proper_type(t)
  4811. if not self._is_truthy_type(t):
  4812. return
  4813. def format_expr_type() -> str:
  4814. typ = format_type(t, self.options)
  4815. if isinstance(expr, MemberExpr):
  4816. return f'Member "{expr.name}" has type {typ}'
  4817. elif isinstance(expr, RefExpr) and expr.fullname:
  4818. return f'"{expr.fullname}" has type {typ}'
  4819. elif isinstance(expr, CallExpr):
  4820. if isinstance(expr.callee, MemberExpr):
  4821. return f'"{expr.callee.name}" returns {typ}'
  4822. elif isinstance(expr.callee, RefExpr) and expr.callee.fullname:
  4823. return f'"{expr.callee.fullname}" returns {typ}'
  4824. return f"Call returns {typ}"
  4825. else:
  4826. return f"Expression has type {typ}"
  4827. def get_expr_name() -> str:
  4828. if isinstance(expr, (NameExpr, MemberExpr)):
  4829. return f'"{expr.name}"'
  4830. else:
  4831. # return type if expr has no name
  4832. return format_type(t, self.options)
  4833. if isinstance(t, FunctionLike):
  4834. self.fail(message_registry.FUNCTION_ALWAYS_TRUE.format(get_expr_name()), expr)
  4835. elif isinstance(t, UnionType):
  4836. self.fail(message_registry.TYPE_ALWAYS_TRUE_UNIONTYPE.format(format_expr_type()), expr)
  4837. elif isinstance(t, Instance) and t.type.fullname == "typing.Iterable":
  4838. _, info = self.make_fake_typeinfo("typing", "Collection", "Collection", [])
  4839. self.fail(
  4840. message_registry.ITERABLE_ALWAYS_TRUE.format(
  4841. format_expr_type(), format_type(Instance(info, t.args), self.options)
  4842. ),
  4843. expr,
  4844. )
  4845. else:
  4846. self.fail(message_registry.TYPE_ALWAYS_TRUE.format(format_expr_type()), expr)
  4847. def find_type_equals_check(
  4848. self, node: ComparisonExpr, expr_indices: list[int]
  4849. ) -> tuple[TypeMap, TypeMap]:
  4850. """Narrow types based on any checks of the type ``type(x) == T``
  4851. Args:
  4852. node: The node that might contain the comparison
  4853. expr_indices: The list of indices of expressions in ``node`` that are being
  4854. compared
  4855. """
  4856. def is_type_call(expr: CallExpr) -> bool:
  4857. """Is expr a call to type with one argument?"""
  4858. return refers_to_fullname(expr.callee, "builtins.type") and len(expr.args) == 1
  4859. # exprs that are being passed into type
  4860. exprs_in_type_calls: list[Expression] = []
  4861. # type that is being compared to type(expr)
  4862. type_being_compared: list[TypeRange] | None = None
  4863. # whether the type being compared to is final
  4864. is_final = False
  4865. for index in expr_indices:
  4866. expr = node.operands[index]
  4867. if isinstance(expr, CallExpr) and is_type_call(expr):
  4868. exprs_in_type_calls.append(expr.args[0])
  4869. else:
  4870. current_type = self.get_isinstance_type(expr)
  4871. if current_type is None:
  4872. continue
  4873. if type_being_compared is not None:
  4874. # It doesn't really make sense to have several types being
  4875. # compared to the output of type (like type(x) == int == str)
  4876. # because whether that's true is solely dependent on what the
  4877. # types being compared are, so we don't try to narrow types any
  4878. # further because we can't really get any information about the
  4879. # type of x from that check
  4880. return {}, {}
  4881. else:
  4882. if isinstance(expr, RefExpr) and isinstance(expr.node, TypeInfo):
  4883. is_final = expr.node.is_final
  4884. type_being_compared = current_type
  4885. if not exprs_in_type_calls:
  4886. return {}, {}
  4887. if_maps: list[TypeMap] = []
  4888. else_maps: list[TypeMap] = []
  4889. for expr in exprs_in_type_calls:
  4890. current_if_type, current_else_type = self.conditional_types_with_intersection(
  4891. self.lookup_type(expr), type_being_compared, expr
  4892. )
  4893. current_if_map, current_else_map = conditional_types_to_typemaps(
  4894. expr, current_if_type, current_else_type
  4895. )
  4896. if_maps.append(current_if_map)
  4897. else_maps.append(current_else_map)
  4898. def combine_maps(list_maps: list[TypeMap]) -> TypeMap:
  4899. """Combine all typemaps in list_maps into one typemap"""
  4900. result_map = {}
  4901. for d in list_maps:
  4902. if d is not None:
  4903. result_map.update(d)
  4904. return result_map
  4905. if_map = combine_maps(if_maps)
  4906. # type(x) == T is only true when x has the same type as T, meaning
  4907. # that it can be false if x is an instance of a subclass of T. That means
  4908. # we can't do any narrowing in the else case unless T is final, in which
  4909. # case T can't be subclassed
  4910. if is_final:
  4911. else_map = combine_maps(else_maps)
  4912. else:
  4913. else_map = {}
  4914. return if_map, else_map
  4915. def find_isinstance_check(self, node: Expression) -> tuple[TypeMap, TypeMap]:
  4916. """Find any isinstance checks (within a chain of ands). Includes
  4917. implicit and explicit checks for None and calls to callable.
  4918. Also includes TypeGuard functions.
  4919. Return value is a map of variables to their types if the condition
  4920. is true and a map of variables to their types if the condition is false.
  4921. If either of the values in the tuple is None, then that particular
  4922. branch can never occur.
  4923. May return {}, {}.
  4924. Can return None, None in situations involving NoReturn.
  4925. """
  4926. if_map, else_map = self.find_isinstance_check_helper(node)
  4927. new_if_map = self.propagate_up_typemap_info(if_map)
  4928. new_else_map = self.propagate_up_typemap_info(else_map)
  4929. return new_if_map, new_else_map
  4930. def find_isinstance_check_helper(self, node: Expression) -> tuple[TypeMap, TypeMap]:
  4931. if is_true_literal(node):
  4932. return {}, None
  4933. if is_false_literal(node):
  4934. return None, {}
  4935. if isinstance(node, CallExpr) and len(node.args) != 0:
  4936. expr = collapse_walrus(node.args[0])
  4937. if refers_to_fullname(node.callee, "builtins.isinstance"):
  4938. if len(node.args) != 2: # the error will be reported elsewhere
  4939. return {}, {}
  4940. if literal(expr) == LITERAL_TYPE:
  4941. return conditional_types_to_typemaps(
  4942. expr,
  4943. *self.conditional_types_with_intersection(
  4944. self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr
  4945. ),
  4946. )
  4947. elif refers_to_fullname(node.callee, "builtins.issubclass"):
  4948. if len(node.args) != 2: # the error will be reported elsewhere
  4949. return {}, {}
  4950. if literal(expr) == LITERAL_TYPE:
  4951. return self.infer_issubclass_maps(node, expr)
  4952. elif refers_to_fullname(node.callee, "builtins.callable"):
  4953. if len(node.args) != 1: # the error will be reported elsewhere
  4954. return {}, {}
  4955. if literal(expr) == LITERAL_TYPE:
  4956. vartype = self.lookup_type(expr)
  4957. return self.conditional_callable_type_map(expr, vartype)
  4958. elif refers_to_fullname(node.callee, "builtins.hasattr"):
  4959. if len(node.args) != 2: # the error will be reported elsewhere
  4960. return {}, {}
  4961. attr = try_getting_str_literals(node.args[1], self.lookup_type(node.args[1]))
  4962. if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1:
  4963. return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0])
  4964. elif isinstance(node.callee, RefExpr):
  4965. if node.callee.type_guard is not None:
  4966. # TODO: Follow *args, **kwargs
  4967. if node.arg_kinds[0] != nodes.ARG_POS:
  4968. # the first argument might be used as a kwarg
  4969. called_type = get_proper_type(self.lookup_type(node.callee))
  4970. assert isinstance(called_type, (CallableType, Overloaded))
  4971. # *assuming* the overloaded function is correct, there's a couple cases:
  4972. # 1) The first argument has different names, but is pos-only. We don't
  4973. # care about this case, the argument must be passed positionally.
  4974. # 2) The first argument allows keyword reference, therefore must be the
  4975. # same between overloads.
  4976. name = called_type.items[0].arg_names[0]
  4977. if name in node.arg_names:
  4978. idx = node.arg_names.index(name)
  4979. # we want the idx-th variable to be narrowed
  4980. expr = collapse_walrus(node.args[idx])
  4981. else:
  4982. self.fail(message_registry.TYPE_GUARD_POS_ARG_REQUIRED, node)
  4983. return {}, {}
  4984. if literal(expr) == LITERAL_TYPE:
  4985. # Note: we wrap the target type, so that we can special case later.
  4986. # Namely, for isinstance() we use a normal meet, while TypeGuard is
  4987. # considered "always right" (i.e. even if the types are not overlapping).
  4988. # Also note that a care must be taken to unwrap this back at read places
  4989. # where we use this to narrow down declared type.
  4990. return {expr: TypeGuardedType(node.callee.type_guard)}, {}
  4991. elif isinstance(node, ComparisonExpr):
  4992. # Step 1: Obtain the types of each operand and whether or not we can
  4993. # narrow their types. (For example, we shouldn't try narrowing the
  4994. # types of literal string or enum expressions).
  4995. operands = [collapse_walrus(x) for x in node.operands]
  4996. operand_types = []
  4997. narrowable_operand_index_to_hash = {}
  4998. for i, expr in enumerate(operands):
  4999. if not self.has_type(expr):
  5000. return {}, {}
  5001. expr_type = self.lookup_type(expr)
  5002. operand_types.append(expr_type)
  5003. if (
  5004. literal(expr) == LITERAL_TYPE
  5005. and not is_literal_none(expr)
  5006. and not self.is_literal_enum(expr)
  5007. ):
  5008. h = literal_hash(expr)
  5009. if h is not None:
  5010. narrowable_operand_index_to_hash[i] = h
  5011. # Step 2: Group operands chained by either the 'is' or '==' operands
  5012. # together. For all other operands, we keep them in groups of size 2.
  5013. # So the expression:
  5014. #
  5015. # x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8
  5016. #
  5017. # ...is converted into the simplified operator list:
  5018. #
  5019. # [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]),
  5020. # ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])]
  5021. #
  5022. # We group identity/equality expressions so we can propagate information
  5023. # we discover about one operand across the entire chain. We don't bother
  5024. # handling 'is not' and '!=' chains in a special way: those are very rare
  5025. # in practice.
  5026. simplified_operator_list = group_comparison_operands(
  5027. node.pairwise(), narrowable_operand_index_to_hash, {"==", "is"}
  5028. )
  5029. # Step 3: Analyze each group and infer more precise type maps for each
  5030. # assignable operand, if possible. We combine these type maps together
  5031. # in the final step.
  5032. partial_type_maps = []
  5033. for operator, expr_indices in simplified_operator_list:
  5034. if operator in {"is", "is not", "==", "!="}:
  5035. # is_valid_target:
  5036. # Controls which types we're allowed to narrow exprs to. Note that
  5037. # we cannot use 'is_literal_type_like' in both cases since doing
  5038. # 'x = 10000 + 1; x is 10001' is not always True in all Python
  5039. # implementations.
  5040. #
  5041. # coerce_only_in_literal_context:
  5042. # If true, coerce types into literal types only if one or more of
  5043. # the provided exprs contains an explicit Literal type. This could
  5044. # technically be set to any arbitrary value, but it seems being liberal
  5045. # with narrowing when using 'is' and conservative when using '==' seems
  5046. # to break the least amount of real-world code.
  5047. #
  5048. # should_narrow_by_identity:
  5049. # Set to 'false' only if the user defines custom __eq__ or __ne__ methods
  5050. # that could cause identity-based narrowing to produce invalid results.
  5051. if operator in {"is", "is not"}:
  5052. is_valid_target: Callable[[Type], bool] = is_singleton_type
  5053. coerce_only_in_literal_context = False
  5054. should_narrow_by_identity = True
  5055. else:
  5056. def is_exactly_literal_type(t: Type) -> bool:
  5057. return isinstance(get_proper_type(t), LiteralType)
  5058. def has_no_custom_eq_checks(t: Type) -> bool:
  5059. return not custom_special_method(
  5060. t, "__eq__", check_all=False
  5061. ) and not custom_special_method(t, "__ne__", check_all=False)
  5062. is_valid_target = is_exactly_literal_type
  5063. coerce_only_in_literal_context = True
  5064. expr_types = [operand_types[i] for i in expr_indices]
  5065. should_narrow_by_identity = all(map(has_no_custom_eq_checks, expr_types))
  5066. if_map: TypeMap = {}
  5067. else_map: TypeMap = {}
  5068. if should_narrow_by_identity:
  5069. if_map, else_map = self.refine_identity_comparison_expression(
  5070. operands,
  5071. operand_types,
  5072. expr_indices,
  5073. narrowable_operand_index_to_hash.keys(),
  5074. is_valid_target,
  5075. coerce_only_in_literal_context,
  5076. )
  5077. # Strictly speaking, we should also skip this check if the objects in the expr
  5078. # chain have custom __eq__ or __ne__ methods. But we (maybe optimistically)
  5079. # assume nobody would actually create a custom objects that considers itself
  5080. # equal to None.
  5081. if if_map == {} and else_map == {}:
  5082. if_map, else_map = self.refine_away_none_in_comparison(
  5083. operands,
  5084. operand_types,
  5085. expr_indices,
  5086. narrowable_operand_index_to_hash.keys(),
  5087. )
  5088. # If we haven't been able to narrow types yet, we might be dealing with a
  5089. # explicit type(x) == some_type check
  5090. if if_map == {} and else_map == {}:
  5091. if_map, else_map = self.find_type_equals_check(node, expr_indices)
  5092. elif operator in {"in", "not in"}:
  5093. assert len(expr_indices) == 2
  5094. left_index, right_index = expr_indices
  5095. item_type = operand_types[left_index]
  5096. iterable_type = operand_types[right_index]
  5097. if_map, else_map = {}, {}
  5098. if left_index in narrowable_operand_index_to_hash:
  5099. # We only try and narrow away 'None' for now
  5100. if is_optional(item_type):
  5101. collection_item_type = get_proper_type(
  5102. builtin_item_type(iterable_type)
  5103. )
  5104. if (
  5105. collection_item_type is not None
  5106. and not is_optional(collection_item_type)
  5107. and not (
  5108. isinstance(collection_item_type, Instance)
  5109. and collection_item_type.type.fullname == "builtins.object"
  5110. )
  5111. and is_overlapping_erased_types(item_type, collection_item_type)
  5112. ):
  5113. if_map[operands[left_index]] = remove_optional(item_type)
  5114. if right_index in narrowable_operand_index_to_hash:
  5115. if_type, else_type = self.conditional_types_for_iterable(
  5116. item_type, iterable_type
  5117. )
  5118. expr = operands[right_index]
  5119. if if_type is None:
  5120. if_map = None
  5121. else:
  5122. if_map[expr] = if_type
  5123. if else_type is None:
  5124. else_map = None
  5125. else:
  5126. else_map[expr] = else_type
  5127. else:
  5128. if_map = {}
  5129. else_map = {}
  5130. if operator in {"is not", "!=", "not in"}:
  5131. if_map, else_map = else_map, if_map
  5132. partial_type_maps.append((if_map, else_map))
  5133. return reduce_conditional_maps(partial_type_maps)
  5134. elif isinstance(node, AssignmentExpr):
  5135. if_map = {}
  5136. else_map = {}
  5137. if_assignment_map, else_assignment_map = self.find_isinstance_check(node.target)
  5138. if if_assignment_map is not None:
  5139. if_map.update(if_assignment_map)
  5140. if else_assignment_map is not None:
  5141. else_map.update(else_assignment_map)
  5142. if_condition_map, else_condition_map = self.find_isinstance_check(node.value)
  5143. if if_condition_map is not None:
  5144. if_map.update(if_condition_map)
  5145. if else_condition_map is not None:
  5146. else_map.update(else_condition_map)
  5147. return (
  5148. (None if if_assignment_map is None or if_condition_map is None else if_map),
  5149. (None if else_assignment_map is None or else_condition_map is None else else_map),
  5150. )
  5151. elif isinstance(node, OpExpr) and node.op == "and":
  5152. left_if_vars, left_else_vars = self.find_isinstance_check(node.left)
  5153. right_if_vars, right_else_vars = self.find_isinstance_check(node.right)
  5154. # (e1 and e2) is true if both e1 and e2 are true,
  5155. # and false if at least one of e1 and e2 is false.
  5156. return (
  5157. and_conditional_maps(left_if_vars, right_if_vars),
  5158. or_conditional_maps(left_else_vars, right_else_vars),
  5159. )
  5160. elif isinstance(node, OpExpr) and node.op == "or":
  5161. left_if_vars, left_else_vars = self.find_isinstance_check(node.left)
  5162. right_if_vars, right_else_vars = self.find_isinstance_check(node.right)
  5163. # (e1 or e2) is true if at least one of e1 or e2 is true,
  5164. # and false if both e1 and e2 are false.
  5165. return (
  5166. or_conditional_maps(left_if_vars, right_if_vars),
  5167. and_conditional_maps(left_else_vars, right_else_vars),
  5168. )
  5169. elif isinstance(node, UnaryExpr) and node.op == "not":
  5170. left, right = self.find_isinstance_check(node.expr)
  5171. return right, left
  5172. # Restrict the type of the variable to True-ish/False-ish in the if and else branches
  5173. # respectively
  5174. original_vartype = self.lookup_type(node)
  5175. self._check_for_truthy_type(original_vartype, node)
  5176. vartype = try_expanding_sum_type_to_union(original_vartype, "builtins.bool")
  5177. if_type = true_only(vartype)
  5178. else_type = false_only(vartype)
  5179. if_map = {node: if_type} if not isinstance(if_type, UninhabitedType) else None
  5180. else_map = {node: else_type} if not isinstance(else_type, UninhabitedType) else None
  5181. return if_map, else_map
  5182. def propagate_up_typemap_info(self, new_types: TypeMap) -> TypeMap:
  5183. """Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types.
  5184. Specifically, this function accepts two mappings of expression to original types:
  5185. the original mapping (existing_types), and a new mapping (new_types) intended to
  5186. update the original.
  5187. This function iterates through new_types and attempts to use the information to try
  5188. refining any parent types that happen to be unions.
  5189. For example, suppose there are two types "A = Tuple[int, int]" and "B = Tuple[str, str]".
  5190. Next, suppose that 'new_types' specifies the expression 'foo[0]' has a refined type
  5191. of 'int' and that 'foo' was previously deduced to be of type Union[A, B].
  5192. Then, this function will observe that since A[0] is an int and B[0] is not, the type of
  5193. 'foo' can be further refined from Union[A, B] into just B.
  5194. We perform this kind of "parent narrowing" for member lookup expressions and indexing
  5195. expressions into tuples, namedtuples, and typeddicts. We repeat this narrowing
  5196. recursively if the parent is also a "lookup expression". So for example, if we have
  5197. the expression "foo['bar'].baz[0]", we'd potentially end up refining types for the
  5198. expressions "foo", "foo['bar']", and "foo['bar'].baz".
  5199. We return the newly refined map. This map is guaranteed to be a superset of 'new_types'.
  5200. """
  5201. if new_types is None:
  5202. return None
  5203. output_map = {}
  5204. for expr, expr_type in new_types.items():
  5205. # The original inferred type should always be present in the output map, of course
  5206. output_map[expr] = expr_type
  5207. # Next, try using this information to refine the parent types, if applicable.
  5208. new_mapping = self.refine_parent_types(expr, expr_type)
  5209. for parent_expr, proposed_parent_type in new_mapping.items():
  5210. # We don't try inferring anything if we've already inferred something for
  5211. # the parent expression.
  5212. # TODO: Consider picking the narrower type instead of always discarding this?
  5213. if parent_expr in new_types:
  5214. continue
  5215. output_map[parent_expr] = proposed_parent_type
  5216. return output_map
  5217. def refine_parent_types(self, expr: Expression, expr_type: Type) -> Mapping[Expression, Type]:
  5218. """Checks if the given expr is a 'lookup operation' into a union and iteratively refines
  5219. the parent types based on the 'expr_type'.
  5220. For example, if 'expr' is an expression like 'a.b.c.d', we'll potentially return refined
  5221. types for expressions 'a', 'a.b', and 'a.b.c'.
  5222. For more details about what a 'lookup operation' is and how we use the expr_type to refine
  5223. the parent types of lookup_expr, see the docstring in 'propagate_up_typemap_info'.
  5224. """
  5225. output: dict[Expression, Type] = {}
  5226. # Note: parent_expr and parent_type are progressively refined as we crawl up the
  5227. # parent lookup chain.
  5228. while True:
  5229. # First, check if this expression is one that's attempting to
  5230. # "lookup" some key in the parent type. If so, save the parent type
  5231. # and create function that will try replaying the same lookup
  5232. # operation against arbitrary types.
  5233. if isinstance(expr, MemberExpr):
  5234. parent_expr = collapse_walrus(expr.expr)
  5235. parent_type = self.lookup_type_or_none(parent_expr)
  5236. member_name = expr.name
  5237. def replay_lookup(new_parent_type: ProperType) -> Type | None:
  5238. with self.msg.filter_errors() as w:
  5239. member_type = analyze_member_access(
  5240. name=member_name,
  5241. typ=new_parent_type,
  5242. context=parent_expr,
  5243. is_lvalue=False,
  5244. is_super=False,
  5245. is_operator=False,
  5246. msg=self.msg,
  5247. original_type=new_parent_type,
  5248. chk=self,
  5249. in_literal_context=False,
  5250. )
  5251. if w.has_new_errors():
  5252. return None
  5253. else:
  5254. return member_type
  5255. elif isinstance(expr, IndexExpr):
  5256. parent_expr = collapse_walrus(expr.base)
  5257. parent_type = self.lookup_type_or_none(parent_expr)
  5258. index_type = self.lookup_type_or_none(expr.index)
  5259. if index_type is None:
  5260. return output
  5261. str_literals = try_getting_str_literals_from_type(index_type)
  5262. if str_literals is not None:
  5263. # Refactoring these two indexing replay functions is surprisingly
  5264. # tricky -- see https://github.com/python/mypy/pull/7917, which
  5265. # was blocked by https://github.com/mypyc/mypyc/issues/586
  5266. def replay_lookup(new_parent_type: ProperType) -> Type | None:
  5267. if not isinstance(new_parent_type, TypedDictType):
  5268. return None
  5269. try:
  5270. assert str_literals is not None
  5271. member_types = [new_parent_type.items[key] for key in str_literals]
  5272. except KeyError:
  5273. return None
  5274. return make_simplified_union(member_types)
  5275. else:
  5276. int_literals = try_getting_int_literals_from_type(index_type)
  5277. if int_literals is not None:
  5278. def replay_lookup(new_parent_type: ProperType) -> Type | None:
  5279. if not isinstance(new_parent_type, TupleType):
  5280. return None
  5281. try:
  5282. assert int_literals is not None
  5283. member_types = [new_parent_type.items[key] for key in int_literals]
  5284. except IndexError:
  5285. return None
  5286. return make_simplified_union(member_types)
  5287. else:
  5288. return output
  5289. else:
  5290. return output
  5291. # If we somehow didn't previously derive the parent type, abort completely
  5292. # with what we have so far: something went wrong at an earlier stage.
  5293. if parent_type is None:
  5294. return output
  5295. # We currently only try refining the parent type if it's a Union.
  5296. # If not, there's no point in trying to refine any further parents
  5297. # since we have no further information we can use to refine the lookup
  5298. # chain, so we end early as an optimization.
  5299. parent_type = get_proper_type(parent_type)
  5300. if not isinstance(parent_type, UnionType):
  5301. return output
  5302. # Take each element in the parent union and replay the original lookup procedure
  5303. # to figure out which parents are compatible.
  5304. new_parent_types = []
  5305. for item in flatten_nested_unions(parent_type.items):
  5306. member_type = replay_lookup(get_proper_type(item))
  5307. if member_type is None:
  5308. # We were unable to obtain the member type. So, we give up on refining this
  5309. # parent type entirely and abort.
  5310. return output
  5311. if is_overlapping_types(member_type, expr_type):
  5312. new_parent_types.append(item)
  5313. # If none of the parent types overlap (if we derived an empty union), something
  5314. # went wrong. We should never hit this case, but deriving the uninhabited type or
  5315. # reporting an error both seem unhelpful. So we abort.
  5316. if not new_parent_types:
  5317. return output
  5318. expr = parent_expr
  5319. expr_type = output[parent_expr] = make_simplified_union(new_parent_types)
  5320. def refine_identity_comparison_expression(
  5321. self,
  5322. operands: list[Expression],
  5323. operand_types: list[Type],
  5324. chain_indices: list[int],
  5325. narrowable_operand_indices: AbstractSet[int],
  5326. is_valid_target: Callable[[ProperType], bool],
  5327. coerce_only_in_literal_context: bool,
  5328. ) -> tuple[TypeMap, TypeMap]:
  5329. """Produce conditional type maps refining expressions by an identity/equality comparison.
  5330. The 'operands' and 'operand_types' lists should be the full list of operands used
  5331. in the overall comparison expression. The 'chain_indices' list is the list of indices
  5332. actually used within this identity comparison chain.
  5333. So if we have the expression:
  5334. a <= b is c is d <= e
  5335. ...then 'operands' and 'operand_types' would be lists of length 5 and 'chain_indices'
  5336. would be the list [1, 2, 3].
  5337. The 'narrowable_operand_indices' parameter is the set of all indices we are allowed
  5338. to refine the types of: that is, all operands that will potentially be a part of
  5339. the output TypeMaps.
  5340. Although this function could theoretically try setting the types of the operands
  5341. in the chains to the meet, doing that causes too many issues in real-world code.
  5342. Instead, we use 'is_valid_target' to identify which of the given chain types
  5343. we could plausibly use as the refined type for the expressions in the chain.
  5344. Similarly, 'coerce_only_in_literal_context' controls whether we should try coercing
  5345. expressions in the chain to a Literal type. Performing this coercion is sometimes
  5346. too aggressive of a narrowing, depending on context.
  5347. """
  5348. should_coerce = True
  5349. if coerce_only_in_literal_context:
  5350. def should_coerce_inner(typ: Type) -> bool:
  5351. typ = get_proper_type(typ)
  5352. return is_literal_type_like(typ) or (
  5353. isinstance(typ, Instance) and typ.type.is_enum
  5354. )
  5355. should_coerce = any(should_coerce_inner(operand_types[i]) for i in chain_indices)
  5356. target: Type | None = None
  5357. possible_target_indices = []
  5358. for i in chain_indices:
  5359. expr_type = operand_types[i]
  5360. if should_coerce:
  5361. expr_type = coerce_to_literal(expr_type)
  5362. if not is_valid_target(get_proper_type(expr_type)):
  5363. continue
  5364. if target and not is_same_type(target, expr_type):
  5365. # We have multiple disjoint target types. So the 'if' branch
  5366. # must be unreachable.
  5367. return None, {}
  5368. target = expr_type
  5369. possible_target_indices.append(i)
  5370. # There's nothing we can currently infer if none of the operands are valid targets,
  5371. # so we end early and infer nothing.
  5372. if target is None:
  5373. return {}, {}
  5374. # If possible, use an unassignable expression as the target.
  5375. # We skip refining the type of the target below, so ideally we'd
  5376. # want to pick an expression we were going to skip anyways.
  5377. singleton_index = -1
  5378. for i in possible_target_indices:
  5379. if i not in narrowable_operand_indices:
  5380. singleton_index = i
  5381. # But if none of the possible singletons are unassignable ones, we give up
  5382. # and arbitrarily pick the last item, mostly because other parts of the
  5383. # type narrowing logic bias towards picking the rightmost item and it'd be
  5384. # nice to stay consistent.
  5385. #
  5386. # That said, it shouldn't matter which index we pick. For example, suppose we
  5387. # have this if statement, where 'x' and 'y' both have singleton types:
  5388. #
  5389. # if x is y:
  5390. # reveal_type(x)
  5391. # reveal_type(y)
  5392. # else:
  5393. # reveal_type(x)
  5394. # reveal_type(y)
  5395. #
  5396. # At this point, 'x' and 'y' *must* have the same singleton type: we would have
  5397. # ended early in the first for-loop in this function if they weren't.
  5398. #
  5399. # So, we should always get the same result in the 'if' case no matter which
  5400. # index we pick. And while we do end up getting different results in the 'else'
  5401. # case depending on the index (e.g. if we pick 'y', then its type stays the same
  5402. # while 'x' is narrowed to '<uninhabited>'), this distinction is also moot: mypy
  5403. # currently will just mark the whole branch as unreachable if either operand is
  5404. # narrowed to <uninhabited>.
  5405. if singleton_index == -1:
  5406. singleton_index = possible_target_indices[-1]
  5407. sum_type_name = None
  5408. target = get_proper_type(target)
  5409. if isinstance(target, LiteralType) and (
  5410. target.is_enum_literal() or isinstance(target.value, bool)
  5411. ):
  5412. sum_type_name = target.fallback.type.fullname
  5413. target_type = [TypeRange(target, is_upper_bound=False)]
  5414. partial_type_maps = []
  5415. for i in chain_indices:
  5416. # If we try refining a type against itself, conditional_type_map
  5417. # will end up assuming that the 'else' branch is unreachable. This is
  5418. # typically not what we want: generally the user will intend for the
  5419. # target type to be some fixed 'sentinel' value and will want to refine
  5420. # the other exprs against this one instead.
  5421. if i == singleton_index:
  5422. continue
  5423. # Naturally, we can't refine operands which are not permitted to be refined.
  5424. if i not in narrowable_operand_indices:
  5425. continue
  5426. expr = operands[i]
  5427. expr_type = coerce_to_literal(operand_types[i])
  5428. if sum_type_name is not None:
  5429. expr_type = try_expanding_sum_type_to_union(expr_type, sum_type_name)
  5430. # We intentionally use 'conditional_types' directly here instead of
  5431. # 'self.conditional_types_with_intersection': we only compute ad-hoc
  5432. # intersections when working with pure instances.
  5433. types = conditional_types(expr_type, target_type)
  5434. partial_type_maps.append(conditional_types_to_typemaps(expr, *types))
  5435. return reduce_conditional_maps(partial_type_maps)
  5436. def refine_away_none_in_comparison(
  5437. self,
  5438. operands: list[Expression],
  5439. operand_types: list[Type],
  5440. chain_indices: list[int],
  5441. narrowable_operand_indices: AbstractSet[int],
  5442. ) -> tuple[TypeMap, TypeMap]:
  5443. """Produces conditional type maps refining away None in an identity/equality chain.
  5444. For more details about what the different arguments mean, see the
  5445. docstring of 'refine_identity_comparison_expression' up above.
  5446. """
  5447. non_optional_types = []
  5448. for i in chain_indices:
  5449. typ = operand_types[i]
  5450. if not is_optional(typ):
  5451. non_optional_types.append(typ)
  5452. # Make sure we have a mixture of optional and non-optional types.
  5453. if len(non_optional_types) == 0 or len(non_optional_types) == len(chain_indices):
  5454. return {}, {}
  5455. if_map = {}
  5456. for i in narrowable_operand_indices:
  5457. expr_type = operand_types[i]
  5458. if not is_optional(expr_type):
  5459. continue
  5460. if any(is_overlapping_erased_types(expr_type, t) for t in non_optional_types):
  5461. if_map[operands[i]] = remove_optional(expr_type)
  5462. return if_map, {}
  5463. #
  5464. # Helpers
  5465. #
  5466. @overload
  5467. def check_subtype(
  5468. self,
  5469. subtype: Type,
  5470. supertype: Type,
  5471. context: Context,
  5472. msg: str,
  5473. subtype_label: str | None = None,
  5474. supertype_label: str | None = None,
  5475. *,
  5476. notes: list[str] | None = None,
  5477. code: ErrorCode | None = None,
  5478. outer_context: Context | None = None,
  5479. ) -> bool:
  5480. ...
  5481. @overload
  5482. def check_subtype(
  5483. self,
  5484. subtype: Type,
  5485. supertype: Type,
  5486. context: Context,
  5487. msg: ErrorMessage,
  5488. subtype_label: str | None = None,
  5489. supertype_label: str | None = None,
  5490. *,
  5491. notes: list[str] | None = None,
  5492. outer_context: Context | None = None,
  5493. ) -> bool:
  5494. ...
  5495. def check_subtype(
  5496. self,
  5497. subtype: Type,
  5498. supertype: Type,
  5499. context: Context,
  5500. msg: str | ErrorMessage,
  5501. subtype_label: str | None = None,
  5502. supertype_label: str | None = None,
  5503. *,
  5504. notes: list[str] | None = None,
  5505. code: ErrorCode | None = None,
  5506. outer_context: Context | None = None,
  5507. ) -> bool:
  5508. """Generate an error if the subtype is not compatible with supertype."""
  5509. if is_subtype(subtype, supertype, options=self.options):
  5510. return True
  5511. if isinstance(msg, str):
  5512. msg = ErrorMessage(msg, code=code)
  5513. if self.msg.prefer_simple_messages():
  5514. self.fail(msg, context) # Fast path -- skip all fancy logic
  5515. return False
  5516. orig_subtype = subtype
  5517. subtype = get_proper_type(subtype)
  5518. orig_supertype = supertype
  5519. supertype = get_proper_type(supertype)
  5520. if self.msg.try_report_long_tuple_assignment_error(
  5521. subtype, supertype, context, msg, subtype_label, supertype_label
  5522. ):
  5523. return False
  5524. extra_info: list[str] = []
  5525. note_msg = ""
  5526. notes = notes or []
  5527. if subtype_label is not None or supertype_label is not None:
  5528. subtype_str, supertype_str = format_type_distinctly(
  5529. orig_subtype, orig_supertype, options=self.options
  5530. )
  5531. if subtype_label is not None:
  5532. extra_info.append(subtype_label + " " + subtype_str)
  5533. if supertype_label is not None:
  5534. extra_info.append(supertype_label + " " + supertype_str)
  5535. note_msg = make_inferred_type_note(
  5536. outer_context or context, subtype, supertype, supertype_str
  5537. )
  5538. if isinstance(subtype, Instance) and isinstance(supertype, Instance):
  5539. notes = append_invariance_notes(notes, subtype, supertype)
  5540. if extra_info:
  5541. msg = msg.with_additional_msg(" (" + ", ".join(extra_info) + ")")
  5542. self.fail(msg, context)
  5543. for note in notes:
  5544. self.msg.note(note, context, code=msg.code)
  5545. if note_msg:
  5546. self.note(note_msg, context, code=msg.code)
  5547. self.msg.maybe_note_concatenate_pos_args(subtype, supertype, context, code=msg.code)
  5548. if (
  5549. isinstance(supertype, Instance)
  5550. and supertype.type.is_protocol
  5551. and isinstance(subtype, (CallableType, Instance, TupleType, TypedDictType))
  5552. ):
  5553. self.msg.report_protocol_problems(subtype, supertype, context, code=msg.code)
  5554. if isinstance(supertype, CallableType) and isinstance(subtype, Instance):
  5555. call = find_member("__call__", subtype, subtype, is_operator=True)
  5556. if call:
  5557. self.msg.note_call(subtype, call, context, code=msg.code)
  5558. if isinstance(subtype, (CallableType, Overloaded)) and isinstance(supertype, Instance):
  5559. if supertype.type.is_protocol and "__call__" in supertype.type.protocol_members:
  5560. call = find_member("__call__", supertype, subtype, is_operator=True)
  5561. assert call is not None
  5562. if not is_subtype(subtype, call, options=self.options):
  5563. self.msg.note_call(supertype, call, context, code=msg.code)
  5564. self.check_possible_missing_await(subtype, supertype, context)
  5565. return False
  5566. def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:
  5567. """If type implements Awaitable[X] with non-Any X, return X.
  5568. In all other cases return None. This method must be called in context
  5569. of local_errors.
  5570. """
  5571. if isinstance(get_proper_type(typ), PartialType):
  5572. # Partial types are special, ignore them here.
  5573. return None
  5574. try:
  5575. aw_type = self.expr_checker.check_awaitable_expr(
  5576. typ, Context(), "", ignore_binder=True
  5577. )
  5578. except KeyError:
  5579. # This is a hack to speed up tests by not including Awaitable in all typing stubs.
  5580. return None
  5581. if local_errors.has_new_errors():
  5582. return None
  5583. if isinstance(get_proper_type(aw_type), (AnyType, UnboundType)):
  5584. return None
  5585. return aw_type
  5586. @contextmanager
  5587. def checking_await_set(self) -> Iterator[None]:
  5588. self.checking_missing_await = True
  5589. try:
  5590. yield
  5591. finally:
  5592. self.checking_missing_await = False
  5593. def check_possible_missing_await(
  5594. self, subtype: Type, supertype: Type, context: Context
  5595. ) -> None:
  5596. """Check if the given type becomes a subtype when awaited."""
  5597. if self.checking_missing_await:
  5598. # Avoid infinite recursion.
  5599. return
  5600. with self.checking_await_set(), self.msg.filter_errors() as local_errors:
  5601. aw_type = self.get_precise_awaitable_type(subtype, local_errors)
  5602. if aw_type is None:
  5603. return
  5604. if not self.check_subtype(
  5605. aw_type, supertype, context, msg=message_registry.INCOMPATIBLE_TYPES
  5606. ):
  5607. return
  5608. self.msg.possible_missing_await(context)
  5609. def contains_none(self, t: Type) -> bool:
  5610. t = get_proper_type(t)
  5611. return (
  5612. isinstance(t, NoneType)
  5613. or (isinstance(t, UnionType) and any(self.contains_none(ut) for ut in t.items))
  5614. or (isinstance(t, TupleType) and any(self.contains_none(tt) for tt in t.items))
  5615. or (
  5616. isinstance(t, Instance)
  5617. and bool(t.args)
  5618. and any(self.contains_none(it) for it in t.args)
  5619. )
  5620. )
  5621. def named_type(self, name: str) -> Instance:
  5622. """Return an instance type with given name and implicit Any type args.
  5623. For example, named_type('builtins.object') produces the 'object' type.
  5624. """
  5625. # Assume that the name refers to a type.
  5626. sym = self.lookup_qualified(name)
  5627. node = sym.node
  5628. if isinstance(node, TypeAlias):
  5629. assert isinstance(node.target, Instance) # type: ignore[misc]
  5630. node = node.target.type
  5631. assert isinstance(node, TypeInfo)
  5632. any_type = AnyType(TypeOfAny.from_omitted_generics)
  5633. return Instance(node, [any_type] * len(node.defn.type_vars))
  5634. def named_generic_type(self, name: str, args: list[Type]) -> Instance:
  5635. """Return an instance with the given name and type arguments.
  5636. Assume that the number of arguments is correct. Assume that
  5637. the name refers to a compatible generic type.
  5638. """
  5639. info = self.lookup_typeinfo(name)
  5640. args = [remove_instance_last_known_values(arg) for arg in args]
  5641. # TODO: assert len(args) == len(info.defn.type_vars)
  5642. return Instance(info, args)
  5643. def lookup_typeinfo(self, fullname: str) -> TypeInfo:
  5644. # Assume that the name refers to a class.
  5645. sym = self.lookup_qualified(fullname)
  5646. node = sym.node
  5647. assert isinstance(node, TypeInfo)
  5648. return node
  5649. def type_type(self) -> Instance:
  5650. """Return instance type 'type'."""
  5651. return self.named_type("builtins.type")
  5652. def str_type(self) -> Instance:
  5653. """Return instance type 'str'."""
  5654. return self.named_type("builtins.str")
  5655. def store_type(self, node: Expression, typ: Type) -> None:
  5656. """Store the type of a node in the type map."""
  5657. self._type_maps[-1][node] = typ
  5658. def has_type(self, node: Expression) -> bool:
  5659. return any(node in m for m in reversed(self._type_maps))
  5660. def lookup_type_or_none(self, node: Expression) -> Type | None:
  5661. for m in reversed(self._type_maps):
  5662. if node in m:
  5663. return m[node]
  5664. return None
  5665. def lookup_type(self, node: Expression) -> Type:
  5666. for m in reversed(self._type_maps):
  5667. t = m.get(node)
  5668. if t is not None:
  5669. return t
  5670. raise KeyError(node)
  5671. def store_types(self, d: dict[Expression, Type]) -> None:
  5672. self._type_maps[-1].update(d)
  5673. @contextmanager
  5674. def local_type_map(self) -> Iterator[dict[Expression, Type]]:
  5675. """Store inferred types into a temporary type map (returned).
  5676. This can be used to perform type checking "experiments" without
  5677. affecting exported types (which are used by mypyc).
  5678. """
  5679. temp_type_map: dict[Expression, Type] = {}
  5680. self._type_maps.append(temp_type_map)
  5681. yield temp_type_map
  5682. self._type_maps.pop()
  5683. def in_checked_function(self) -> bool:
  5684. """Should we type-check the current function?
  5685. - Yes if --check-untyped-defs is set.
  5686. - Yes outside functions.
  5687. - Yes in annotated functions.
  5688. - No otherwise.
  5689. """
  5690. return (
  5691. self.options.check_untyped_defs or not self.dynamic_funcs or not self.dynamic_funcs[-1]
  5692. )
  5693. def lookup(self, name: str) -> SymbolTableNode:
  5694. """Look up a definition from the symbol table with the given name."""
  5695. if name in self.globals:
  5696. return self.globals[name]
  5697. else:
  5698. b = self.globals.get("__builtins__", None)
  5699. if b:
  5700. assert isinstance(b.node, MypyFile)
  5701. table = b.node.names
  5702. if name in table:
  5703. return table[name]
  5704. raise KeyError(f"Failed lookup: {name}")
  5705. def lookup_qualified(self, name: str) -> SymbolTableNode:
  5706. if "." not in name:
  5707. return self.lookup(name)
  5708. else:
  5709. parts = name.split(".")
  5710. n = self.modules[parts[0]]
  5711. for i in range(1, len(parts) - 1):
  5712. sym = n.names.get(parts[i])
  5713. assert sym is not None, "Internal error: attempted lookup of unknown name"
  5714. assert isinstance(sym.node, MypyFile)
  5715. n = sym.node
  5716. last = parts[-1]
  5717. if last in n.names:
  5718. return n.names[last]
  5719. elif len(parts) == 2 and parts[0] in ("builtins", "typing"):
  5720. fullname = ".".join(parts)
  5721. if fullname in SUGGESTED_TEST_FIXTURES:
  5722. suggestion = ", e.g. add '[{} fixtures/{}]' to your test".format(
  5723. parts[0], SUGGESTED_TEST_FIXTURES[fullname]
  5724. )
  5725. else:
  5726. suggestion = ""
  5727. raise KeyError(
  5728. "Could not find builtin symbol '{}' (If you are running a "
  5729. "test case, use a fixture that "
  5730. "defines this symbol{})".format(last, suggestion)
  5731. )
  5732. else:
  5733. msg = "Failed qualified lookup: '{}' (fullname = '{}')."
  5734. raise KeyError(msg.format(last, name))
  5735. @contextmanager
  5736. def enter_partial_types(
  5737. self, *, is_function: bool = False, is_class: bool = False
  5738. ) -> Iterator[None]:
  5739. """Enter a new scope for collecting partial types.
  5740. Also report errors for (some) variables which still have partial
  5741. types, i.e. we couldn't infer a complete type.
  5742. """
  5743. is_local = (self.partial_types and self.partial_types[-1].is_local) or is_function
  5744. self.partial_types.append(PartialTypeScope({}, is_function, is_local))
  5745. yield
  5746. # Don't complain about not being able to infer partials if it is
  5747. # at the toplevel (with allow_untyped_globals) or if it is in an
  5748. # untyped function being checked with check_untyped_defs.
  5749. permissive = (self.options.allow_untyped_globals and not is_local) or (
  5750. self.options.check_untyped_defs and self.dynamic_funcs and self.dynamic_funcs[-1]
  5751. )
  5752. partial_types, _, _ = self.partial_types.pop()
  5753. if not self.current_node_deferred:
  5754. for var, context in partial_types.items():
  5755. # If we require local partial types, there are a few exceptions where
  5756. # we fall back to inferring just "None" as the type from a None initializer:
  5757. #
  5758. # 1. If all happens within a single function this is acceptable, since only
  5759. # the topmost function is a separate target in fine-grained incremental mode.
  5760. # We primarily want to avoid "splitting" partial types across targets.
  5761. #
  5762. # 2. A None initializer in the class body if the attribute is defined in a base
  5763. # class is fine, since the attribute is already defined and it's currently okay
  5764. # to vary the type of an attribute covariantly. The None type will still be
  5765. # checked for compatibility with base classes elsewhere. Without this exception
  5766. # mypy could require an annotation for an attribute that already has been
  5767. # declared in a base class, which would be bad.
  5768. allow_none = (
  5769. not self.options.local_partial_types
  5770. or is_function
  5771. or (is_class and self.is_defined_in_base_class(var))
  5772. )
  5773. if (
  5774. allow_none
  5775. and isinstance(var.type, PartialType)
  5776. and var.type.type is None
  5777. and not permissive
  5778. ):
  5779. var.type = NoneType()
  5780. else:
  5781. if var not in self.partial_reported and not permissive:
  5782. self.msg.need_annotation_for_var(var, context, self.options.python_version)
  5783. self.partial_reported.add(var)
  5784. if var.type:
  5785. fixed = fixup_partial_type(var.type)
  5786. var.invalid_partial_type = fixed != var.type
  5787. var.type = fixed
  5788. def handle_partial_var_type(
  5789. self, typ: PartialType, is_lvalue: bool, node: Var, context: Context
  5790. ) -> Type:
  5791. """Handle a reference to a partial type through a var.
  5792. (Used by checkexpr and checkmember.)
  5793. """
  5794. in_scope, is_local, partial_types = self.find_partial_types_in_all_scopes(node)
  5795. if typ.type is None and in_scope:
  5796. # 'None' partial type. It has a well-defined type. In an lvalue context
  5797. # we want to preserve the knowledge of it being a partial type.
  5798. if not is_lvalue:
  5799. return NoneType()
  5800. else:
  5801. return typ
  5802. else:
  5803. if partial_types is not None and not self.current_node_deferred:
  5804. if in_scope:
  5805. context = partial_types[node]
  5806. if is_local or not self.options.allow_untyped_globals:
  5807. self.msg.need_annotation_for_var(
  5808. node, context, self.options.python_version
  5809. )
  5810. self.partial_reported.add(node)
  5811. else:
  5812. # Defer the node -- we might get a better type in the outer scope
  5813. self.handle_cannot_determine_type(node.name, context)
  5814. return fixup_partial_type(typ)
  5815. def is_defined_in_base_class(self, var: Var) -> bool:
  5816. if not var.info:
  5817. return False
  5818. return var.info.fallback_to_any or any(
  5819. base.get(var.name) is not None for base in var.info.mro[1:]
  5820. )
  5821. def find_partial_types(self, var: Var) -> dict[Var, Context] | None:
  5822. """Look for an active partial type scope containing variable.
  5823. A scope is active if assignments in the current context can refine a partial
  5824. type originally defined in the scope. This is affected by the local_partial_types
  5825. configuration option.
  5826. """
  5827. in_scope, _, partial_types = self.find_partial_types_in_all_scopes(var)
  5828. if in_scope:
  5829. return partial_types
  5830. return None
  5831. def find_partial_types_in_all_scopes(
  5832. self, var: Var
  5833. ) -> tuple[bool, bool, dict[Var, Context] | None]:
  5834. """Look for partial type scope containing variable.
  5835. Return tuple (is the scope active, is the scope a local scope, scope).
  5836. """
  5837. for scope in reversed(self.partial_types):
  5838. if var in scope.map:
  5839. # All scopes within the outermost function are active. Scopes out of
  5840. # the outermost function are inactive to allow local reasoning (important
  5841. # for fine-grained incremental mode).
  5842. disallow_other_scopes = self.options.local_partial_types
  5843. if isinstance(var.type, PartialType) and var.type.type is not None and var.info:
  5844. # This is an ugly hack to make partial generic self attributes behave
  5845. # as if --local-partial-types is always on (because it used to be like this).
  5846. disallow_other_scopes = True
  5847. scope_active = (
  5848. not disallow_other_scopes or scope.is_local == self.partial_types[-1].is_local
  5849. )
  5850. return scope_active, scope.is_local, scope.map
  5851. return False, False, None
  5852. def temp_node(self, t: Type, context: Context | None = None) -> TempNode:
  5853. """Create a temporary node with the given, fixed type."""
  5854. return TempNode(t, context=context)
  5855. def fail(
  5856. self, msg: str | ErrorMessage, context: Context, *, code: ErrorCode | None = None
  5857. ) -> None:
  5858. """Produce an error message."""
  5859. if isinstance(msg, ErrorMessage):
  5860. self.msg.fail(msg.value, context, code=msg.code)
  5861. return
  5862. self.msg.fail(msg, context, code=code)
  5863. def note(
  5864. self,
  5865. msg: str | ErrorMessage,
  5866. context: Context,
  5867. offset: int = 0,
  5868. *,
  5869. code: ErrorCode | None = None,
  5870. ) -> None:
  5871. """Produce a note."""
  5872. if isinstance(msg, ErrorMessage):
  5873. self.msg.note(msg.value, context, code=msg.code)
  5874. return
  5875. self.msg.note(msg, context, offset=offset, code=code)
  5876. def iterable_item_type(
  5877. self, it: Instance | CallableType | TypeType | Overloaded, context: Context
  5878. ) -> Type:
  5879. if isinstance(it, Instance):
  5880. iterable = map_instance_to_supertype(it, self.lookup_typeinfo("typing.Iterable"))
  5881. item_type = iterable.args[0]
  5882. if not isinstance(get_proper_type(item_type), AnyType):
  5883. # This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'
  5884. # in case there is no explicit base class.
  5885. return item_type
  5886. # Try also structural typing.
  5887. return self.analyze_iterable_item_type_without_expression(it, context)[1]
  5888. def function_type(self, func: FuncBase) -> FunctionLike:
  5889. return function_type(func, self.named_type("builtins.function"))
  5890. def push_type_map(self, type_map: TypeMap) -> None:
  5891. if type_map is None:
  5892. self.binder.unreachable()
  5893. else:
  5894. for expr, type in type_map.items():
  5895. self.binder.put(expr, type)
  5896. def infer_issubclass_maps(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]:
  5897. """Infer type restrictions for an expression in issubclass call."""
  5898. vartype = self.lookup_type(expr)
  5899. type = self.get_isinstance_type(node.args[1])
  5900. if isinstance(vartype, TypeVarType):
  5901. vartype = vartype.upper_bound
  5902. vartype = get_proper_type(vartype)
  5903. if isinstance(vartype, UnionType):
  5904. union_list = []
  5905. for t in get_proper_types(vartype.items):
  5906. if isinstance(t, TypeType):
  5907. union_list.append(t.item)
  5908. else:
  5909. # This is an error that should be reported earlier
  5910. # if we reach here, we refuse to do any type inference.
  5911. return {}, {}
  5912. vartype = UnionType(union_list)
  5913. elif isinstance(vartype, TypeType):
  5914. vartype = vartype.item
  5915. elif isinstance(vartype, Instance) and vartype.type.is_metaclass():
  5916. vartype = self.named_type("builtins.object")
  5917. else:
  5918. # Any other object whose type we don't know precisely
  5919. # for example, Any or a custom metaclass.
  5920. return {}, {} # unknown type
  5921. yes_type, no_type = self.conditional_types_with_intersection(vartype, type, expr)
  5922. yes_map, no_map = conditional_types_to_typemaps(expr, yes_type, no_type)
  5923. yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))
  5924. return yes_map, no_map
  5925. @overload
  5926. def conditional_types_with_intersection(
  5927. self,
  5928. expr_type: Type,
  5929. type_ranges: list[TypeRange] | None,
  5930. ctx: Context,
  5931. default: None = None,
  5932. ) -> tuple[Type | None, Type | None]:
  5933. ...
  5934. @overload
  5935. def conditional_types_with_intersection(
  5936. self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type
  5937. ) -> tuple[Type, Type]:
  5938. ...
  5939. def conditional_types_with_intersection(
  5940. self,
  5941. expr_type: Type,
  5942. type_ranges: list[TypeRange] | None,
  5943. ctx: Context,
  5944. default: Type | None = None,
  5945. ) -> tuple[Type | None, Type | None]:
  5946. initial_types = conditional_types(expr_type, type_ranges, default)
  5947. # For some reason, doing "yes_map, no_map = conditional_types_to_typemaps(...)"
  5948. # doesn't work: mypyc will decide that 'yes_map' is of type None if we try.
  5949. yes_type: Type | None = initial_types[0]
  5950. no_type: Type | None = initial_types[1]
  5951. if not isinstance(get_proper_type(yes_type), UninhabitedType) or type_ranges is None:
  5952. return yes_type, no_type
  5953. # If conditional_types was unable to successfully narrow the expr_type
  5954. # using the type_ranges and concluded if-branch is unreachable, we try
  5955. # computing it again using a different algorithm that tries to generate
  5956. # an ad-hoc intersection between the expr_type and the type_ranges.
  5957. proper_type = get_proper_type(expr_type)
  5958. if isinstance(proper_type, UnionType):
  5959. possible_expr_types = get_proper_types(proper_type.relevant_items())
  5960. else:
  5961. possible_expr_types = [proper_type]
  5962. possible_target_types = []
  5963. for tr in type_ranges:
  5964. item = get_proper_type(tr.item)
  5965. if not isinstance(item, Instance) or tr.is_upper_bound:
  5966. return yes_type, no_type
  5967. possible_target_types.append(item)
  5968. out = []
  5969. errors: list[tuple[str, str]] = []
  5970. for v in possible_expr_types:
  5971. if not isinstance(v, Instance):
  5972. return yes_type, no_type
  5973. for t in possible_target_types:
  5974. intersection = self.intersect_instances((v, t), errors)
  5975. if intersection is None:
  5976. continue
  5977. out.append(intersection)
  5978. if not out:
  5979. # Only report errors if no element in the union worked.
  5980. if self.should_report_unreachable_issues():
  5981. for types, reason in errors:
  5982. self.msg.impossible_intersection(types, reason, ctx)
  5983. return UninhabitedType(), expr_type
  5984. new_yes_type = make_simplified_union(out)
  5985. return new_yes_type, expr_type
  5986. def is_writable_attribute(self, node: Node) -> bool:
  5987. """Check if an attribute is writable"""
  5988. if isinstance(node, Var):
  5989. if node.is_property and not node.is_settable_property:
  5990. return False
  5991. return True
  5992. elif isinstance(node, OverloadedFuncDef) and node.is_property:
  5993. first_item = node.items[0]
  5994. assert isinstance(first_item, Decorator)
  5995. return first_item.var.is_settable_property
  5996. return False
  5997. def get_isinstance_type(self, expr: Expression) -> list[TypeRange] | None:
  5998. if isinstance(expr, OpExpr) and expr.op == "|":
  5999. left = self.get_isinstance_type(expr.left)
  6000. right = self.get_isinstance_type(expr.right)
  6001. if left is None or right is None:
  6002. return None
  6003. return left + right
  6004. all_types = get_proper_types(flatten_types(self.lookup_type(expr)))
  6005. types: list[TypeRange] = []
  6006. for typ in all_types:
  6007. if isinstance(typ, FunctionLike) and typ.is_type_obj():
  6008. # Type variables may be present -- erase them, which is the best
  6009. # we can do (outside disallowing them here).
  6010. erased_type = erase_typevars(typ.items[0].ret_type)
  6011. types.append(TypeRange(erased_type, is_upper_bound=False))
  6012. elif isinstance(typ, TypeType):
  6013. # Type[A] means "any type that is a subtype of A" rather than "precisely type A"
  6014. # we indicate this by setting is_upper_bound flag
  6015. types.append(TypeRange(typ.item, is_upper_bound=True))
  6016. elif isinstance(typ, Instance) and typ.type.fullname == "builtins.type":
  6017. object_type = Instance(typ.type.mro[-1], [])
  6018. types.append(TypeRange(object_type, is_upper_bound=True))
  6019. elif isinstance(typ, AnyType):
  6020. types.append(TypeRange(typ, is_upper_bound=False))
  6021. else: # we didn't see an actual type, but rather a variable with unknown value
  6022. return None
  6023. if not types:
  6024. # this can happen if someone has empty tuple as 2nd argument to isinstance
  6025. # strictly speaking, we should return UninhabitedType but for simplicity we will simply
  6026. # refuse to do any type inference for now
  6027. return None
  6028. return types
  6029. def is_literal_enum(self, n: Expression) -> bool:
  6030. """Returns true if this expression (with the given type context) is an Enum literal.
  6031. For example, if we had an enum:
  6032. class Foo(Enum):
  6033. A = 1
  6034. B = 2
  6035. ...and if the expression 'Foo' referred to that enum within the current type context,
  6036. then the expression 'Foo.A' would be a literal enum. However, if we did 'a = Foo.A',
  6037. then the variable 'a' would *not* be a literal enum.
  6038. We occasionally special-case expressions like 'Foo.A' and treat them as a single primitive
  6039. unit for the same reasons we sometimes treat 'True', 'False', or 'None' as a single
  6040. primitive unit.
  6041. """
  6042. if not isinstance(n, MemberExpr) or not isinstance(n.expr, NameExpr):
  6043. return False
  6044. parent_type = self.lookup_type_or_none(n.expr)
  6045. member_type = self.lookup_type_or_none(n)
  6046. if member_type is None or parent_type is None:
  6047. return False
  6048. parent_type = get_proper_type(parent_type)
  6049. member_type = get_proper_type(coerce_to_literal(member_type))
  6050. if not isinstance(parent_type, FunctionLike) or not isinstance(member_type, LiteralType):
  6051. return False
  6052. if not parent_type.is_type_obj():
  6053. return False
  6054. return (
  6055. member_type.is_enum_literal()
  6056. and member_type.fallback.type == parent_type.type_object()
  6057. )
  6058. def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:
  6059. """Inject an extra attribute with Any type using fallbacks."""
  6060. orig_typ = typ
  6061. typ = get_proper_type(typ)
  6062. any_type = AnyType(TypeOfAny.unannotated)
  6063. if isinstance(typ, Instance):
  6064. result = typ.copy_with_extra_attr(name, any_type)
  6065. # For instances, we erase the possible module name, so that restrictions
  6066. # become anonymous types.ModuleType instances, allowing hasattr() to
  6067. # have effect on modules.
  6068. assert result.extra_attrs is not None
  6069. result.extra_attrs.mod_name = None
  6070. return result
  6071. if isinstance(typ, TupleType):
  6072. fallback = typ.partial_fallback.copy_with_extra_attr(name, any_type)
  6073. return typ.copy_modified(fallback=fallback)
  6074. if isinstance(typ, CallableType):
  6075. fallback = typ.fallback.copy_with_extra_attr(name, any_type)
  6076. return typ.copy_modified(fallback=fallback)
  6077. if isinstance(typ, TypeType) and isinstance(typ.item, Instance):
  6078. return TypeType.make_normalized(self.add_any_attribute_to_type(typ.item, name))
  6079. if isinstance(typ, TypeVarType):
  6080. return typ.copy_modified(
  6081. upper_bound=self.add_any_attribute_to_type(typ.upper_bound, name),
  6082. values=[self.add_any_attribute_to_type(v, name) for v in typ.values],
  6083. )
  6084. if isinstance(typ, UnionType):
  6085. with_attr, without_attr = self.partition_union_by_attr(typ, name)
  6086. return make_simplified_union(
  6087. with_attr + [self.add_any_attribute_to_type(typ, name) for typ in without_attr]
  6088. )
  6089. return orig_typ
  6090. def hasattr_type_maps(
  6091. self, expr: Expression, source_type: Type, name: str
  6092. ) -> tuple[TypeMap, TypeMap]:
  6093. """Simple support for hasattr() checks.
  6094. Essentially the logic is following:
  6095. * In the if branch, keep types that already has a valid attribute as is,
  6096. for other inject an attribute with `Any` type.
  6097. * In the else branch, remove types that already have a valid attribute,
  6098. while keeping the rest.
  6099. """
  6100. if self.has_valid_attribute(source_type, name):
  6101. return {expr: source_type}, {}
  6102. source_type = get_proper_type(source_type)
  6103. if isinstance(source_type, UnionType):
  6104. _, without_attr = self.partition_union_by_attr(source_type, name)
  6105. yes_map = {expr: self.add_any_attribute_to_type(source_type, name)}
  6106. return yes_map, {expr: make_simplified_union(without_attr)}
  6107. type_with_attr = self.add_any_attribute_to_type(source_type, name)
  6108. if type_with_attr != source_type:
  6109. return {expr: type_with_attr}, {}
  6110. return {}, {}
  6111. def partition_union_by_attr(
  6112. self, source_type: UnionType, name: str
  6113. ) -> tuple[list[Type], list[Type]]:
  6114. with_attr = []
  6115. without_attr = []
  6116. for item in source_type.items:
  6117. if self.has_valid_attribute(item, name):
  6118. with_attr.append(item)
  6119. else:
  6120. without_attr.append(item)
  6121. return with_attr, without_attr
  6122. def has_valid_attribute(self, typ: Type, name: str) -> bool:
  6123. p_typ = get_proper_type(typ)
  6124. if isinstance(p_typ, AnyType):
  6125. return False
  6126. if isinstance(p_typ, Instance) and p_typ.extra_attrs and p_typ.extra_attrs.mod_name:
  6127. # Presence of module_symbol_table means this check will skip ModuleType.__getattr__
  6128. module_symbol_table = p_typ.type.names
  6129. else:
  6130. module_symbol_table = None
  6131. with self.msg.filter_errors() as watcher:
  6132. analyze_member_access(
  6133. name,
  6134. typ,
  6135. TempNode(AnyType(TypeOfAny.special_form)),
  6136. False,
  6137. False,
  6138. False,
  6139. self.msg,
  6140. original_type=typ,
  6141. chk=self,
  6142. # This is not a real attribute lookup so don't mess with deferring nodes.
  6143. no_deferral=True,
  6144. module_symbol_table=module_symbol_table,
  6145. )
  6146. return not watcher.has_new_errors()
  6147. def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type:
  6148. return self.expr_checker.accept(node, type_context=type_context)
  6149. class CollectArgTypeVarTypes(TypeTraverserVisitor):
  6150. """Collects the non-nested argument types in a set."""
  6151. def __init__(self) -> None:
  6152. self.arg_types: set[TypeVarType] = set()
  6153. def visit_type_var(self, t: TypeVarType) -> None:
  6154. self.arg_types.add(t)
  6155. @overload
  6156. def conditional_types(
  6157. current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: None = None
  6158. ) -> tuple[Type | None, Type | None]:
  6159. ...
  6160. @overload
  6161. def conditional_types(
  6162. current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: Type
  6163. ) -> tuple[Type, Type]:
  6164. ...
  6165. def conditional_types(
  6166. current_type: Type, proposed_type_ranges: list[TypeRange] | None, default: Type | None = None
  6167. ) -> tuple[Type | None, Type | None]:
  6168. """Takes in the current type and a proposed type of an expression.
  6169. Returns a 2-tuple: The first element is the proposed type, if the expression
  6170. can be the proposed type. The second element is the type it would hold
  6171. if it was not the proposed type, if any. UninhabitedType means unreachable.
  6172. None means no new information can be inferred. If default is set it is returned
  6173. instead."""
  6174. if proposed_type_ranges:
  6175. if len(proposed_type_ranges) == 1:
  6176. target = proposed_type_ranges[0].item
  6177. target = get_proper_type(target)
  6178. if isinstance(target, LiteralType) and (
  6179. target.is_enum_literal() or isinstance(target.value, bool)
  6180. ):
  6181. enum_name = target.fallback.type.fullname
  6182. current_type = try_expanding_sum_type_to_union(current_type, enum_name)
  6183. proposed_items = [type_range.item for type_range in proposed_type_ranges]
  6184. proposed_type = make_simplified_union(proposed_items)
  6185. if isinstance(proposed_type, AnyType):
  6186. # We don't really know much about the proposed type, so we shouldn't
  6187. # attempt to narrow anything. Instead, we broaden the expr to Any to
  6188. # avoid false positives
  6189. return proposed_type, default
  6190. elif not any(
  6191. type_range.is_upper_bound for type_range in proposed_type_ranges
  6192. ) and is_proper_subtype(current_type, proposed_type, ignore_promotions=True):
  6193. # Expression is always of one of the types in proposed_type_ranges
  6194. return default, UninhabitedType()
  6195. elif not is_overlapping_types(
  6196. current_type, proposed_type, prohibit_none_typevar_overlap=True, ignore_promotions=True
  6197. ):
  6198. # Expression is never of any type in proposed_type_ranges
  6199. return UninhabitedType(), default
  6200. else:
  6201. # we can only restrict when the type is precise, not bounded
  6202. proposed_precise_type = UnionType.make_union(
  6203. [
  6204. type_range.item
  6205. for type_range in proposed_type_ranges
  6206. if not type_range.is_upper_bound
  6207. ]
  6208. )
  6209. remaining_type = restrict_subtype_away(current_type, proposed_precise_type)
  6210. return proposed_type, remaining_type
  6211. else:
  6212. # An isinstance check, but we don't understand the type
  6213. return current_type, default
  6214. def conditional_types_to_typemaps(
  6215. expr: Expression, yes_type: Type | None, no_type: Type | None
  6216. ) -> tuple[TypeMap, TypeMap]:
  6217. expr = collapse_walrus(expr)
  6218. maps: list[TypeMap] = []
  6219. for typ in (yes_type, no_type):
  6220. proper_type = get_proper_type(typ)
  6221. if isinstance(proper_type, UninhabitedType):
  6222. maps.append(None)
  6223. elif proper_type is None:
  6224. maps.append({})
  6225. else:
  6226. assert typ is not None
  6227. maps.append({expr: typ})
  6228. return cast(Tuple[TypeMap, TypeMap], tuple(maps))
  6229. def gen_unique_name(base: str, table: SymbolTable) -> str:
  6230. """Generate a name that does not appear in table by appending numbers to base."""
  6231. if base not in table:
  6232. return base
  6233. i = 1
  6234. while base + str(i) in table:
  6235. i += 1
  6236. return base + str(i)
  6237. def is_true_literal(n: Expression) -> bool:
  6238. """Returns true if this expression is the 'True' literal/keyword."""
  6239. return refers_to_fullname(n, "builtins.True") or isinstance(n, IntExpr) and n.value != 0
  6240. def is_false_literal(n: Expression) -> bool:
  6241. """Returns true if this expression is the 'False' literal/keyword."""
  6242. return refers_to_fullname(n, "builtins.False") or isinstance(n, IntExpr) and n.value == 0
  6243. def is_literal_none(n: Expression) -> bool:
  6244. """Returns true if this expression is the 'None' literal/keyword."""
  6245. return isinstance(n, NameExpr) and n.fullname == "builtins.None"
  6246. def is_literal_not_implemented(n: Expression) -> bool:
  6247. return isinstance(n, NameExpr) and n.fullname == "builtins.NotImplemented"
  6248. def builtin_item_type(tp: Type) -> Type | None:
  6249. """Get the item type of a builtin container.
  6250. If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict)
  6251. or if the container is not parameterized (like List or List[Any])
  6252. return None. This function is used to narrow optional types in situations like this:
  6253. x: Optional[int]
  6254. if x in (1, 2, 3):
  6255. x + 42 # OK
  6256. Note: this is only OK for built-in containers, where we know the behavior
  6257. of __contains__.
  6258. """
  6259. tp = get_proper_type(tp)
  6260. if isinstance(tp, Instance):
  6261. if tp.type.fullname in [
  6262. "builtins.list",
  6263. "builtins.tuple",
  6264. "builtins.dict",
  6265. "builtins.set",
  6266. "builtins.frozenset",
  6267. "_collections_abc.dict_keys",
  6268. "typing.KeysView",
  6269. ]:
  6270. if not tp.args:
  6271. # TODO: fix tuple in lib-stub/builtins.pyi (it should be generic).
  6272. return None
  6273. if not isinstance(get_proper_type(tp.args[0]), AnyType):
  6274. return tp.args[0]
  6275. elif isinstance(tp, TupleType) and all(
  6276. not isinstance(it, AnyType) for it in get_proper_types(tp.items)
  6277. ):
  6278. return make_simplified_union(tp.items) # this type is not externally visible
  6279. elif isinstance(tp, TypedDictType):
  6280. # TypedDict always has non-optional string keys. Find the key type from the Mapping
  6281. # base class.
  6282. for base in tp.fallback.type.mro:
  6283. if base.fullname == "typing.Mapping":
  6284. return map_instance_to_supertype(tp.fallback, base).args[0]
  6285. assert False, "No Mapping base class found for TypedDict fallback"
  6286. return None
  6287. def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
  6288. """Calculate what information we can learn from the truth of (e1 and e2)
  6289. in terms of the information that we can learn from the truth of e1 and
  6290. the truth of e2.
  6291. """
  6292. if m1 is None or m2 is None:
  6293. # One of the conditions can never be true.
  6294. return None
  6295. # Both conditions can be true; combine the information. Anything
  6296. # we learn from either conditions's truth is valid. If the same
  6297. # expression's type is refined by both conditions, we somewhat
  6298. # arbitrarily give precedence to m2. (In the future, we could use
  6299. # an intersection type.)
  6300. result = m2.copy()
  6301. m2_keys = {literal_hash(n2) for n2 in m2}
  6302. for n1 in m1:
  6303. if literal_hash(n1) not in m2_keys:
  6304. result[n1] = m1[n1]
  6305. return result
  6306. def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
  6307. """Calculate what information we can learn from the truth of (e1 or e2)
  6308. in terms of the information that we can learn from the truth of e1 and
  6309. the truth of e2.
  6310. """
  6311. if m1 is None:
  6312. return m2
  6313. if m2 is None:
  6314. return m1
  6315. # Both conditions can be true. Combine information about
  6316. # expressions whose type is refined by both conditions. (We do not
  6317. # learn anything about expressions whose type is refined by only
  6318. # one condition.)
  6319. result: dict[Expression, Type] = {}
  6320. for n1 in m1:
  6321. for n2 in m2:
  6322. if literal_hash(n1) == literal_hash(n2):
  6323. result[n1] = make_simplified_union([m1[n1], m2[n2]])
  6324. return result
  6325. def reduce_conditional_maps(type_maps: list[tuple[TypeMap, TypeMap]]) -> tuple[TypeMap, TypeMap]:
  6326. """Reduces a list containing pairs of if/else TypeMaps into a single pair.
  6327. We "and" together all of the if TypeMaps and "or" together the else TypeMaps. So
  6328. for example, if we had the input:
  6329. [
  6330. ({x: TypeIfX, shared: TypeIfShared1}, {x: TypeElseX, shared: TypeElseShared1}),
  6331. ({y: TypeIfY, shared: TypeIfShared2}, {y: TypeElseY, shared: TypeElseShared2}),
  6332. ]
  6333. ...we'd return the output:
  6334. (
  6335. {x: TypeIfX, y: TypeIfY, shared: PseudoIntersection[TypeIfShared1, TypeIfShared2]},
  6336. {shared: Union[TypeElseShared1, TypeElseShared2]},
  6337. )
  6338. ...where "PseudoIntersection[X, Y] == Y" because mypy actually doesn't understand intersections
  6339. yet, so we settle for just arbitrarily picking the right expr's type.
  6340. We only retain the shared expression in the 'else' case because we don't actually know
  6341. whether x was refined or y was refined -- only just that one of the two was refined.
  6342. """
  6343. if len(type_maps) == 0:
  6344. return {}, {}
  6345. elif len(type_maps) == 1:
  6346. return type_maps[0]
  6347. else:
  6348. final_if_map, final_else_map = type_maps[0]
  6349. for if_map, else_map in type_maps[1:]:
  6350. final_if_map = and_conditional_maps(final_if_map, if_map)
  6351. final_else_map = or_conditional_maps(final_else_map, else_map)
  6352. return final_if_map, final_else_map
  6353. def convert_to_typetype(type_map: TypeMap) -> TypeMap:
  6354. converted_type_map: dict[Expression, Type] = {}
  6355. if type_map is None:
  6356. return None
  6357. for expr, typ in type_map.items():
  6358. t = typ
  6359. if isinstance(t, TypeVarType):
  6360. t = t.upper_bound
  6361. # TODO: should we only allow unions of instances as per PEP 484?
  6362. if not isinstance(get_proper_type(t), (UnionType, Instance)):
  6363. # unknown type; error was likely reported earlier
  6364. return {}
  6365. converted_type_map[expr] = TypeType.make_normalized(typ)
  6366. return converted_type_map
  6367. def flatten(t: Expression) -> list[Expression]:
  6368. """Flatten a nested sequence of tuples/lists into one list of nodes."""
  6369. if isinstance(t, (TupleExpr, ListExpr)):
  6370. return [b for a in t.items for b in flatten(a)]
  6371. elif isinstance(t, StarExpr):
  6372. return flatten(t.expr)
  6373. else:
  6374. return [t]
  6375. def flatten_types(t: Type) -> list[Type]:
  6376. """Flatten a nested sequence of tuples into one list of nodes."""
  6377. t = get_proper_type(t)
  6378. if isinstance(t, TupleType):
  6379. return [b for a in t.items for b in flatten_types(a)]
  6380. else:
  6381. return [t]
  6382. def expand_func(defn: FuncItem, map: dict[TypeVarId, Type]) -> FuncItem:
  6383. visitor = TypeTransformVisitor(map)
  6384. ret = visitor.node(defn)
  6385. assert isinstance(ret, FuncItem)
  6386. return ret
  6387. class TypeTransformVisitor(TransformVisitor):
  6388. def __init__(self, map: dict[TypeVarId, Type]) -> None:
  6389. super().__init__()
  6390. self.map = map
  6391. def type(self, type: Type) -> Type:
  6392. return expand_type(type, self.map)
  6393. def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool:
  6394. """Can a single call match both t and s, based just on positional argument counts?"""
  6395. min_args = max(t.min_args, s.min_args)
  6396. max_args = min(t.max_possible_positional_args(), s.max_possible_positional_args())
  6397. return min_args <= max_args
  6398. def is_unsafe_overlapping_overload_signatures(
  6399. signature: CallableType, other: CallableType
  6400. ) -> bool:
  6401. """Check if two overloaded signatures are unsafely overlapping or partially overlapping.
  6402. We consider two functions 's' and 't' to be unsafely overlapping if both
  6403. of the following are true:
  6404. 1. s's parameters are all more precise or partially overlapping with t's
  6405. 2. s's return type is NOT a subtype of t's.
  6406. Assumes that 'signature' appears earlier in the list of overload
  6407. alternatives then 'other' and that their argument counts are overlapping.
  6408. """
  6409. # Try detaching callables from the containing class so that all TypeVars
  6410. # are treated as being free.
  6411. #
  6412. # This lets us identify cases where the two signatures use completely
  6413. # incompatible types -- e.g. see the testOverloadingInferUnionReturnWithMixedTypevars
  6414. # test case.
  6415. signature = detach_callable(signature)
  6416. other = detach_callable(other)
  6417. # Note: We repeat this check twice in both directions due to a slight
  6418. # asymmetry in 'is_callable_compatible'. When checking for partial overlaps,
  6419. # we attempt to unify 'signature' and 'other' both against each other.
  6420. #
  6421. # If 'signature' cannot be unified with 'other', we end early. However,
  6422. # if 'other' cannot be modified with 'signature', the function continues
  6423. # using the older version of 'other'.
  6424. #
  6425. # This discrepancy is unfortunately difficult to get rid of, so we repeat the
  6426. # checks twice in both directions for now.
  6427. return is_callable_compatible(
  6428. signature,
  6429. other,
  6430. is_compat=is_overlapping_types_no_promote_no_uninhabited,
  6431. is_compat_return=lambda l, r: not is_subtype_no_promote(l, r),
  6432. ignore_return=False,
  6433. check_args_covariantly=True,
  6434. allow_partial_overlap=True,
  6435. ) or is_callable_compatible(
  6436. other,
  6437. signature,
  6438. is_compat=is_overlapping_types_no_promote_no_uninhabited,
  6439. is_compat_return=lambda l, r: not is_subtype_no_promote(r, l),
  6440. ignore_return=False,
  6441. check_args_covariantly=False,
  6442. allow_partial_overlap=True,
  6443. )
  6444. def detach_callable(typ: CallableType) -> CallableType:
  6445. """Ensures that the callable's type variables are 'detached' and independent of the context.
  6446. A callable normally keeps track of the type variables it uses within its 'variables' field.
  6447. However, if the callable is from a method and that method is using a class type variable,
  6448. the callable will not keep track of that type variable since it belongs to the class.
  6449. This function will traverse the callable and find all used type vars and add them to the
  6450. variables field if it isn't already present.
  6451. The caller can then unify on all type variables whether or not the callable is originally
  6452. from a class or not."""
  6453. type_list = typ.arg_types + [typ.ret_type]
  6454. appear_map: dict[str, list[int]] = {}
  6455. for i, inner_type in enumerate(type_list):
  6456. typevars_available = get_type_vars(inner_type)
  6457. for var in typevars_available:
  6458. if var.fullname not in appear_map:
  6459. appear_map[var.fullname] = []
  6460. appear_map[var.fullname].append(i)
  6461. used_type_var_names = set()
  6462. for var_name, appearances in appear_map.items():
  6463. used_type_var_names.add(var_name)
  6464. all_type_vars = get_type_vars(typ)
  6465. new_variables = []
  6466. for var in set(all_type_vars):
  6467. if var.fullname not in used_type_var_names:
  6468. continue
  6469. new_variables.append(
  6470. TypeVarType(
  6471. name=var.name,
  6472. fullname=var.fullname,
  6473. id=var.id,
  6474. values=var.values,
  6475. upper_bound=var.upper_bound,
  6476. default=var.default,
  6477. variance=var.variance,
  6478. )
  6479. )
  6480. out = typ.copy_modified(
  6481. variables=new_variables, arg_types=type_list[:-1], ret_type=type_list[-1]
  6482. )
  6483. return out
  6484. def overload_can_never_match(signature: CallableType, other: CallableType) -> bool:
  6485. """Check if the 'other' method can never be matched due to 'signature'.
  6486. This can happen if signature's parameters are all strictly broader then
  6487. other's parameters.
  6488. Assumes that both signatures have overlapping argument counts.
  6489. """
  6490. # The extra erasure is needed to prevent spurious errors
  6491. # in situations where an `Any` overload is used as a fallback
  6492. # for an overload with type variables. The spurious error appears
  6493. # because the type variables turn into `Any` during unification in
  6494. # the below subtype check and (surprisingly?) `is_proper_subtype(Any, Any)`
  6495. # returns `True`.
  6496. # TODO: find a cleaner solution instead of this ad-hoc erasure.
  6497. exp_signature = expand_type(
  6498. signature, {tvar.id: erase_def_to_union_or_bound(tvar) for tvar in signature.variables}
  6499. )
  6500. return is_callable_compatible(
  6501. exp_signature, other, is_compat=is_more_precise, ignore_return=True
  6502. )
  6503. def is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool:
  6504. """Does t have wider arguments than s?"""
  6505. # TODO should an overload with additional items be allowed to be more
  6506. # general than one with fewer items (or just one item)?
  6507. if isinstance(t, CallableType):
  6508. if isinstance(s, CallableType):
  6509. return is_callable_compatible(t, s, is_compat=is_proper_subtype, ignore_return=True)
  6510. elif isinstance(t, FunctionLike):
  6511. if isinstance(s, FunctionLike):
  6512. if len(t.items) == len(s.items):
  6513. return all(
  6514. is_same_arg_prefix(items, itemt) for items, itemt in zip(t.items, s.items)
  6515. )
  6516. return False
  6517. def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool:
  6518. return is_callable_compatible(
  6519. t,
  6520. s,
  6521. is_compat=is_same_type,
  6522. ignore_return=True,
  6523. check_args_covariantly=True,
  6524. ignore_pos_arg_names=True,
  6525. )
  6526. def infer_operator_assignment_method(typ: Type, operator: str) -> tuple[bool, str]:
  6527. """Determine if operator assignment on given value type is in-place, and the method name.
  6528. For example, if operator is '+', return (True, '__iadd__') or (False, '__add__')
  6529. depending on which method is supported by the type.
  6530. """
  6531. typ = get_proper_type(typ)
  6532. method = operators.op_methods[operator]
  6533. if isinstance(typ, Instance):
  6534. if operator in operators.ops_with_inplace_method:
  6535. inplace_method = "__i" + method[2:]
  6536. if typ.type.has_readable_member(inplace_method):
  6537. return True, inplace_method
  6538. return False, method
  6539. def is_valid_inferred_type(typ: Type, is_lvalue_final: bool = False) -> bool:
  6540. """Is an inferred type valid and needs no further refinement?
  6541. Examples of invalid types include the None type (when we are not assigning
  6542. None to a final lvalue) or List[<uninhabited>].
  6543. When not doing strict Optional checking, all types containing None are
  6544. invalid. When doing strict Optional checking, only None and types that are
  6545. incompletely defined (i.e. contain UninhabitedType) are invalid.
  6546. """
  6547. proper_type = get_proper_type(typ)
  6548. if isinstance(proper_type, NoneType):
  6549. # If the lvalue is final, we may immediately infer NoneType when the
  6550. # initializer is None.
  6551. #
  6552. # If not, we want to defer making this decision. The final inferred
  6553. # type could either be NoneType or an Optional type, depending on
  6554. # the context. This resolution happens in leave_partial_types when
  6555. # we pop a partial types scope.
  6556. return is_lvalue_final
  6557. elif isinstance(proper_type, UninhabitedType):
  6558. return False
  6559. return not typ.accept(InvalidInferredTypes())
  6560. class InvalidInferredTypes(BoolTypeQuery):
  6561. """Find type components that are not valid for an inferred type.
  6562. These include <Erased> type, and any <nothing> types resulting from failed
  6563. (ambiguous) type inference.
  6564. """
  6565. def __init__(self) -> None:
  6566. super().__init__(ANY_STRATEGY)
  6567. def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
  6568. return t.ambiguous
  6569. def visit_erased_type(self, t: ErasedType) -> bool:
  6570. # This can happen inside a lambda.
  6571. return True
  6572. class SetNothingToAny(TypeTranslator):
  6573. """Replace all ambiguous <nothing> types with Any (to avoid spurious extra errors)."""
  6574. def visit_uninhabited_type(self, t: UninhabitedType) -> Type:
  6575. if t.ambiguous:
  6576. return AnyType(TypeOfAny.from_error)
  6577. return t
  6578. def visit_type_alias_type(self, t: TypeAliasType) -> Type:
  6579. # Target of the alias cannot be an ambiguous <nothing>, so we just
  6580. # replace the arguments.
  6581. return t.copy_modified(args=[a.accept(self) for a in t.args])
  6582. def is_node_static(node: Node | None) -> bool | None:
  6583. """Find out if a node describes a static function method."""
  6584. if isinstance(node, FuncDef):
  6585. return node.is_static
  6586. if isinstance(node, Var):
  6587. return node.is_staticmethod
  6588. return None
  6589. class CheckerScope:
  6590. # We keep two stacks combined, to maintain the relative order
  6591. stack: list[TypeInfo | FuncItem | MypyFile]
  6592. def __init__(self, module: MypyFile) -> None:
  6593. self.stack = [module]
  6594. def top_function(self) -> FuncItem | None:
  6595. for e in reversed(self.stack):
  6596. if isinstance(e, FuncItem):
  6597. return e
  6598. return None
  6599. def top_non_lambda_function(self) -> FuncItem | None:
  6600. for e in reversed(self.stack):
  6601. if isinstance(e, FuncItem) and not isinstance(e, LambdaExpr):
  6602. return e
  6603. return None
  6604. def active_class(self) -> TypeInfo | None:
  6605. if isinstance(self.stack[-1], TypeInfo):
  6606. return self.stack[-1]
  6607. return None
  6608. def enclosing_class(self) -> TypeInfo | None:
  6609. """Is there a class *directly* enclosing this function?"""
  6610. top = self.top_function()
  6611. assert top, "This method must be called from inside a function"
  6612. index = self.stack.index(top)
  6613. assert index, "CheckerScope stack must always start with a module"
  6614. enclosing = self.stack[index - 1]
  6615. if isinstance(enclosing, TypeInfo):
  6616. return enclosing
  6617. return None
  6618. def active_self_type(self) -> Instance | TupleType | None:
  6619. """An instance or tuple type representing the current class.
  6620. This returns None unless we are in class body or in a method.
  6621. In particular, inside a function nested in method this returns None.
  6622. """
  6623. info = self.active_class()
  6624. if not info and self.top_function():
  6625. info = self.enclosing_class()
  6626. if info:
  6627. return fill_typevars(info)
  6628. return None
  6629. @contextmanager
  6630. def push_function(self, item: FuncItem) -> Iterator[None]:
  6631. self.stack.append(item)
  6632. yield
  6633. self.stack.pop()
  6634. @contextmanager
  6635. def push_class(self, info: TypeInfo) -> Iterator[None]:
  6636. self.stack.append(info)
  6637. yield
  6638. self.stack.pop()
  6639. TKey = TypeVar("TKey")
  6640. TValue = TypeVar("TValue")
  6641. class DisjointDict(Generic[TKey, TValue]):
  6642. """An variation of the union-find algorithm/data structure where instead of keeping
  6643. track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple
  6644. Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint.
  6645. This data structure is currently used exclusively by 'group_comparison_operands' below
  6646. to merge chains of '==' and 'is' comparisons when two or more chains use the same expression
  6647. in best-case O(n), where n is the number of operands.
  6648. Specifically, the `add_mapping()` function and `items()` functions will take on average
  6649. O(k + v) and O(n) respectively, where k and v are the number of keys and values we're adding
  6650. for a given chain. Note that k <= n and v <= n.
  6651. We hit these average/best-case scenarios for most user code: e.g. when the user has just
  6652. a single chain like 'a == b == c == d == ...' or multiple disjoint chains like
  6653. 'a==b < c==d < e==f < ...'. (Note that a naive iterative merging would be O(n^2) for
  6654. the latter case).
  6655. In comparison, this data structure will make 'group_comparison_operands' have a worst-case
  6656. runtime of O(n*log(n)): 'add_mapping()' and 'items()' are worst-case O(k*log(n) + v) and
  6657. O(k*log(n)) respectively. This happens only in the rare case where the user keeps repeatedly
  6658. making disjoint mappings before merging them in a way that persistently dodges the path
  6659. compression optimization in '_lookup_root_id', which would end up constructing a single
  6660. tree of height log_2(n). This makes root lookups no longer amoritized constant time when we
  6661. finally call 'items()'.
  6662. """
  6663. def __init__(self) -> None:
  6664. # Each key maps to a unique ID
  6665. self._key_to_id: dict[TKey, int] = {}
  6666. # Each id points to the parent id, forming a forest of upwards-pointing trees. If the
  6667. # current id already is the root, it points to itself. We gradually flatten these trees
  6668. # as we perform root lookups: eventually all nodes point directly to its root.
  6669. self._id_to_parent_id: dict[int, int] = {}
  6670. # Each root id in turn maps to the set of values.
  6671. self._root_id_to_values: dict[int, set[TValue]] = {}
  6672. def add_mapping(self, keys: set[TKey], values: set[TValue]) -> None:
  6673. """Adds a 'Set[TKey] -> Set[TValue]' mapping. If there already exists a mapping
  6674. containing one or more of the given keys, we merge the input mapping with the old one.
  6675. Note that the given set of keys must be non-empty -- otherwise, nothing happens.
  6676. """
  6677. if not keys:
  6678. return
  6679. subtree_roots = [self._lookup_or_make_root_id(key) for key in keys]
  6680. new_root = subtree_roots[0]
  6681. root_values = self._root_id_to_values[new_root]
  6682. root_values.update(values)
  6683. for subtree_root in subtree_roots[1:]:
  6684. if subtree_root == new_root or subtree_root not in self._root_id_to_values:
  6685. continue
  6686. self._id_to_parent_id[subtree_root] = new_root
  6687. root_values.update(self._root_id_to_values.pop(subtree_root))
  6688. def items(self) -> list[tuple[set[TKey], set[TValue]]]:
  6689. """Returns all disjoint mappings in key-value pairs."""
  6690. root_id_to_keys: dict[int, set[TKey]] = {}
  6691. for key in self._key_to_id:
  6692. root_id = self._lookup_root_id(key)
  6693. if root_id not in root_id_to_keys:
  6694. root_id_to_keys[root_id] = set()
  6695. root_id_to_keys[root_id].add(key)
  6696. output = []
  6697. for root_id, keys in root_id_to_keys.items():
  6698. output.append((keys, self._root_id_to_values[root_id]))
  6699. return output
  6700. def _lookup_or_make_root_id(self, key: TKey) -> int:
  6701. if key in self._key_to_id:
  6702. return self._lookup_root_id(key)
  6703. else:
  6704. new_id = len(self._key_to_id)
  6705. self._key_to_id[key] = new_id
  6706. self._id_to_parent_id[new_id] = new_id
  6707. self._root_id_to_values[new_id] = set()
  6708. return new_id
  6709. def _lookup_root_id(self, key: TKey) -> int:
  6710. i = self._key_to_id[key]
  6711. while i != self._id_to_parent_id[i]:
  6712. # Optimization: make keys directly point to their grandparents to speed up
  6713. # future traversals. This prevents degenerate trees of height n from forming.
  6714. new_parent = self._id_to_parent_id[self._id_to_parent_id[i]]
  6715. self._id_to_parent_id[i] = new_parent
  6716. i = new_parent
  6717. return i
  6718. def group_comparison_operands(
  6719. pairwise_comparisons: Iterable[tuple[str, Expression, Expression]],
  6720. operand_to_literal_hash: Mapping[int, Key],
  6721. operators_to_group: set[str],
  6722. ) -> list[tuple[str, list[int]]]:
  6723. """Group a series of comparison operands together chained by any operand
  6724. in the 'operators_to_group' set. All other pairwise operands are kept in
  6725. groups of size 2.
  6726. For example, suppose we have the input comparison expression:
  6727. x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8
  6728. If we get these expressions in a pairwise way (e.g. by calling ComparisionExpr's
  6729. 'pairwise()' method), we get the following as input:
  6730. [('==', x0, x1), ('==', x1, x2), ('<', x2, x3), ('<', x3, x4),
  6731. ('is', x4, x5), ('is', x5, x6), ('is not', x6, x7), ('is not', x7, x8)]
  6732. If `operators_to_group` is the set {'==', 'is'}, this function will produce
  6733. the following "simplified operator list":
  6734. [("==", [0, 1, 2]), ("<", [2, 3]), ("<", [3, 4]),
  6735. ("is", [4, 5, 6]), ("is not", [6, 7]), ("is not", [7, 8])]
  6736. Note that (a) we yield *indices* to the operands rather then the operand
  6737. expressions themselves and that (b) operands used in a consecutive chain
  6738. of '==' or 'is' are grouped together.
  6739. If two of these chains happen to contain operands with the same underlying
  6740. literal hash (e.g. are assignable and correspond to the same expression),
  6741. we combine those chains together. For example, if we had:
  6742. same == x < y == same
  6743. ...and if 'operand_to_literal_hash' contained the same values for the indices
  6744. 0 and 3, we'd produce the following output:
  6745. [("==", [0, 1, 2, 3]), ("<", [1, 2])]
  6746. But if the 'operand_to_literal_hash' did *not* contain an entry, we'd instead
  6747. default to returning:
  6748. [("==", [0, 1]), ("<", [1, 2]), ("==", [2, 3])]
  6749. This function is currently only used to assist with type-narrowing refinements
  6750. and is extracted out to a helper function so we can unit test it.
  6751. """
  6752. groups: dict[str, DisjointDict[Key, int]] = {op: DisjointDict() for op in operators_to_group}
  6753. simplified_operator_list: list[tuple[str, list[int]]] = []
  6754. last_operator: str | None = None
  6755. current_indices: set[int] = set()
  6756. current_hashes: set[Key] = set()
  6757. for i, (operator, left_expr, right_expr) in enumerate(pairwise_comparisons):
  6758. if last_operator is None:
  6759. last_operator = operator
  6760. if current_indices and (operator != last_operator or operator not in operators_to_group):
  6761. # If some of the operands in the chain are assignable, defer adding it: we might
  6762. # end up needing to merge it with other chains that appear later.
  6763. if not current_hashes:
  6764. simplified_operator_list.append((last_operator, sorted(current_indices)))
  6765. else:
  6766. groups[last_operator].add_mapping(current_hashes, current_indices)
  6767. last_operator = operator
  6768. current_indices = set()
  6769. current_hashes = set()
  6770. # Note: 'i' corresponds to the left operand index, so 'i + 1' is the
  6771. # right operand.
  6772. current_indices.add(i)
  6773. current_indices.add(i + 1)
  6774. # We only ever want to combine operands/combine chains for these operators
  6775. if operator in operators_to_group:
  6776. left_hash = operand_to_literal_hash.get(i)
  6777. if left_hash is not None:
  6778. current_hashes.add(left_hash)
  6779. right_hash = operand_to_literal_hash.get(i + 1)
  6780. if right_hash is not None:
  6781. current_hashes.add(right_hash)
  6782. if last_operator is not None:
  6783. if not current_hashes:
  6784. simplified_operator_list.append((last_operator, sorted(current_indices)))
  6785. else:
  6786. groups[last_operator].add_mapping(current_hashes, current_indices)
  6787. # Now that we know which chains happen to contain the same underlying expressions
  6788. # and can be merged together, add in this info back to the output.
  6789. for operator, disjoint_dict in groups.items():
  6790. for keys, indices in disjoint_dict.items():
  6791. simplified_operator_list.append((operator, sorted(indices)))
  6792. # For stability, reorder list by the first operand index to appear
  6793. simplified_operator_list.sort(key=lambda item: item[1][0])
  6794. return simplified_operator_list
  6795. def is_typed_callable(c: Type | None) -> bool:
  6796. c = get_proper_type(c)
  6797. if not c or not isinstance(c, CallableType):
  6798. return False
  6799. return not all(
  6800. isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated
  6801. for t in get_proper_types(c.arg_types + [c.ret_type])
  6802. )
  6803. def is_untyped_decorator(typ: Type | None) -> bool:
  6804. typ = get_proper_type(typ)
  6805. if not typ:
  6806. return True
  6807. elif isinstance(typ, CallableType):
  6808. return not is_typed_callable(typ)
  6809. elif isinstance(typ, Instance):
  6810. method = typ.type.get_method("__call__")
  6811. if method:
  6812. if isinstance(method, Decorator):
  6813. return is_untyped_decorator(method.func.type) or is_untyped_decorator(
  6814. method.var.type
  6815. )
  6816. if isinstance(method.type, Overloaded):
  6817. return any(is_untyped_decorator(item) for item in method.type.items)
  6818. else:
  6819. return not is_typed_callable(method.type)
  6820. else:
  6821. return False
  6822. elif isinstance(typ, Overloaded):
  6823. return any(is_untyped_decorator(item) for item in typ.items)
  6824. return True
  6825. def is_static(func: FuncBase | Decorator) -> bool:
  6826. if isinstance(func, Decorator):
  6827. return is_static(func.func)
  6828. elif isinstance(func, FuncBase):
  6829. return func.is_static
  6830. assert False, f"Unexpected func type: {type(func)}"
  6831. def is_property(defn: SymbolNode) -> bool:
  6832. if isinstance(defn, Decorator):
  6833. return defn.func.is_property
  6834. if isinstance(defn, OverloadedFuncDef):
  6835. if defn.items and isinstance(defn.items[0], Decorator):
  6836. return defn.items[0].func.is_property
  6837. return False
  6838. def get_property_type(t: ProperType) -> ProperType:
  6839. if isinstance(t, CallableType):
  6840. return get_proper_type(t.ret_type)
  6841. if isinstance(t, Overloaded):
  6842. return get_proper_type(t.items[0].ret_type)
  6843. return t
  6844. def is_subtype_no_promote(left: Type, right: Type) -> bool:
  6845. return is_subtype(left, right, ignore_promotions=True)
  6846. def is_overlapping_types_no_promote_no_uninhabited(left: Type, right: Type) -> bool:
  6847. # For the purpose of unsafe overload checks we consider list[<nothing>] and list[int]
  6848. # non-overlapping. This is consistent with how we treat list[int] and list[str] as
  6849. # non-overlapping, despite [] belongs to both. Also this will prevent false positives
  6850. # for failed type inference during unification.
  6851. return is_overlapping_types(left, right, ignore_promotions=True, ignore_uninhabited=True)
  6852. def is_private(node_name: str) -> bool:
  6853. """Check if node is private to class definition."""
  6854. return node_name.startswith("__") and not node_name.endswith("__")
  6855. def is_string_literal(typ: Type) -> bool:
  6856. strs = try_getting_str_literals_from_type(typ)
  6857. return strs is not None and len(strs) == 1
  6858. def has_bool_item(typ: ProperType) -> bool:
  6859. """Return True if type is 'bool' or a union with a 'bool' item."""
  6860. if is_named_instance(typ, "builtins.bool"):
  6861. return True
  6862. if isinstance(typ, UnionType):
  6863. return any(is_named_instance(item, "builtins.bool") for item in typ.items)
  6864. return False
  6865. def collapse_walrus(e: Expression) -> Expression:
  6866. """If an expression is an AssignmentExpr, pull out the assignment target.
  6867. We don't make any attempt to pull out all the targets in code like `x := (y := z)`.
  6868. We could support narrowing those if that sort of code turns out to be common.
  6869. """
  6870. if isinstance(e, AssignmentExpr):
  6871. return e.target
  6872. return e
  6873. def find_last_var_assignment_line(n: Node, v: Var) -> int:
  6874. """Find the highest line number of a potential assignment to variable within node.
  6875. This supports local and global variables.
  6876. Return -1 if no assignment was found.
  6877. """
  6878. visitor = VarAssignVisitor(v)
  6879. n.accept(visitor)
  6880. return visitor.last_line
  6881. class VarAssignVisitor(TraverserVisitor):
  6882. def __init__(self, v: Var) -> None:
  6883. self.last_line = -1
  6884. self.lvalue = False
  6885. self.var_node = v
  6886. def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
  6887. self.lvalue = True
  6888. for lv in s.lvalues:
  6889. lv.accept(self)
  6890. self.lvalue = False
  6891. def visit_name_expr(self, e: NameExpr) -> None:
  6892. if self.lvalue and e.node is self.var_node:
  6893. self.last_line = max(self.last_line, e.line)
  6894. def visit_member_expr(self, e: MemberExpr) -> None:
  6895. old_lvalue = self.lvalue
  6896. self.lvalue = False
  6897. super().visit_member_expr(e)
  6898. self.lvalue = old_lvalue
  6899. def visit_index_expr(self, e: IndexExpr) -> None:
  6900. old_lvalue = self.lvalue
  6901. self.lvalue = False
  6902. super().visit_index_expr(e)
  6903. self.lvalue = old_lvalue
  6904. def visit_with_stmt(self, s: WithStmt) -> None:
  6905. self.lvalue = True
  6906. for lv in s.target:
  6907. if lv is not None:
  6908. lv.accept(self)
  6909. self.lvalue = False
  6910. s.body.accept(self)
  6911. def visit_for_stmt(self, s: ForStmt) -> None:
  6912. self.lvalue = True
  6913. s.index.accept(self)
  6914. self.lvalue = False
  6915. s.body.accept(self)
  6916. if s.else_body:
  6917. s.else_body.accept(self)
  6918. def visit_assignment_expr(self, e: AssignmentExpr) -> None:
  6919. self.lvalue = True
  6920. e.target.accept(self)
  6921. self.lvalue = False
  6922. e.value.accept(self)
  6923. def visit_as_pattern(self, p: AsPattern) -> None:
  6924. if p.pattern is not None:
  6925. p.pattern.accept(self)
  6926. if p.name is not None:
  6927. self.lvalue = True
  6928. p.name.accept(self)
  6929. self.lvalue = False
  6930. def visit_starred_pattern(self, p: StarredPattern) -> None:
  6931. if p.capture is not None:
  6932. self.lvalue = True
  6933. p.capture.accept(self)
  6934. self.lvalue = False