1 //! Conversion from AST representation of types to the `ty.rs` representation. 2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an 3 //! instance of `AstConv`. 4 5 mod errors; 6 mod generics; 7 8 use crate::bounds::Bounds; 9 use crate::collect::PlaceholderHirTyCollector; 10 use crate::errors::{ 11 AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits, 12 TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified, 13 }; 14 use crate::middle::resolve_lifetime as rl; 15 use crate::require_c_abi_if_c_variadic; 16 use rustc_data_structures::fx::{FxHashMap, FxHashSet}; 17 use rustc_errors::{struct_span_err, Applicability, ErrorReported, FatalError}; 18 use rustc_hir as hir; 19 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; 20 use rustc_hir::def_id::{DefId, LocalDefId}; 21 use rustc_hir::intravisit::{walk_generics, Visitor as _}; 22 use rustc_hir::lang_items::LangItem; 23 use rustc_hir::{GenericArg, GenericArgs}; 24 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, Subst, SubstsRef}; 25 use rustc_middle::ty::GenericParamDefKind; 26 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable}; 27 use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; 28 use rustc_span::lev_distance::find_best_match_for_name; 29 use rustc_span::symbol::{Ident, Symbol}; 30 use rustc_span::{Span, DUMMY_SP}; 31 use rustc_target::spec::abi; 32 use rustc_trait_selection::traits; 33 use rustc_trait_selection::traits::astconv_object_safety_violations; 34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error; 35 use rustc_trait_selection::traits::wf::object_region_bounds; 36 37 use smallvec::SmallVec; 38 use std::array; 39 use std::collections::BTreeSet; 40 use std::slice; 41 42 #[derive(Debug)] 43 pub struct PathSeg(pub DefId, pub usize); 44 45 pub trait AstConv<'tcx> { tcx<'a>(&'a self) -> TyCtxt<'tcx>46 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>; 47 item_def_id(&self) -> Option<DefId>48 fn item_def_id(&self) -> Option<DefId>; 49 50 /// Returns predicates in scope of the form `X: Foo<T>`, where `X` 51 /// is a type parameter `X` with the given id `def_id` and T 52 /// matches `assoc_name`. This is a subset of the full set of 53 /// predicates. 54 /// 55 /// This is used for one specific purpose: resolving "short-hand" 56 /// associated type references like `T::Item`. In principle, we 57 /// would do that by first getting the full set of predicates in 58 /// scope and then filtering down to find those that apply to `T`, 59 /// but this can lead to cycle errors. The problem is that we have 60 /// to do this resolution *in order to create the predicates in 61 /// the first place*. Hence, we have this "special pass". get_type_parameter_bounds( &self, span: Span, def_id: DefId, assoc_name: Ident, ) -> ty::GenericPredicates<'tcx>62 fn get_type_parameter_bounds( 63 &self, 64 span: Span, 65 def_id: DefId, 66 assoc_name: Ident, 67 ) -> ty::GenericPredicates<'tcx>; 68 69 /// Returns the lifetime to use when a lifetime is omitted (and not elided). re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Option<ty::Region<'tcx>>70 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) 71 -> Option<ty::Region<'tcx>>; 72 73 /// Returns the type to use when a type is omitted. ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>74 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>; 75 76 /// Returns `true` if `_` is allowed in type signatures in the current context. allow_ty_infer(&self) -> bool77 fn allow_ty_infer(&self) -> bool; 78 79 /// Returns the const to use when a const is omitted. ct_infer( &self, ty: Ty<'tcx>, param: Option<&ty::GenericParamDef>, span: Span, ) -> &'tcx Const<'tcx>80 fn ct_infer( 81 &self, 82 ty: Ty<'tcx>, 83 param: Option<&ty::GenericParamDef>, 84 span: Span, 85 ) -> &'tcx Const<'tcx>; 86 87 /// Projecting an associated type from a (potentially) 88 /// higher-ranked trait reference is more complicated, because of 89 /// the possibility of late-bound regions appearing in the 90 /// associated type binding. This is not legal in function 91 /// signatures for that reason. In a function body, we can always 92 /// handle it because we can use inference variables to remove the 93 /// late-bound regions. projected_ty_from_poly_trait_ref( &self, span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'_>, poly_trait_ref: ty::PolyTraitRef<'tcx>, ) -> Ty<'tcx>94 fn projected_ty_from_poly_trait_ref( 95 &self, 96 span: Span, 97 item_def_id: DefId, 98 item_segment: &hir::PathSegment<'_>, 99 poly_trait_ref: ty::PolyTraitRef<'tcx>, 100 ) -> Ty<'tcx>; 101 102 /// Normalize an associated type coming from the user. normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>103 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>; 104 105 /// Invoked when we encounter an error from some prior pass 106 /// (e.g., resolve) that is translated into a ty-error. This is 107 /// used to help suppress derived errors typeck might otherwise 108 /// report. set_tainted_by_errors(&self)109 fn set_tainted_by_errors(&self); 110 record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span)111 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); 112 } 113 114 #[derive(Debug)] 115 struct ConvertedBinding<'a, 'tcx> { 116 hir_id: hir::HirId, 117 item_name: Ident, 118 kind: ConvertedBindingKind<'a, 'tcx>, 119 gen_args: &'a GenericArgs<'a>, 120 span: Span, 121 } 122 123 #[derive(Debug)] 124 enum ConvertedBindingKind<'a, 'tcx> { 125 Equality(Ty<'tcx>), 126 Constraint(&'a [hir::GenericBound<'a>]), 127 } 128 129 /// New-typed boolean indicating whether explicit late-bound lifetimes 130 /// are present in a set of generic arguments. 131 /// 132 /// For example if we have some method `fn f<'a>(&'a self)` implemented 133 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a` 134 /// is late-bound so should not be provided explicitly. Thus, if `f` is 135 /// instantiated with some generic arguments providing `'a` explicitly, 136 /// we taint those arguments with `ExplicitLateBound::Yes` so that we 137 /// can provide an appropriate diagnostic later. 138 #[derive(Copy, Clone, PartialEq)] 139 pub enum ExplicitLateBound { 140 Yes, 141 No, 142 } 143 144 #[derive(Copy, Clone, PartialEq)] 145 pub enum IsMethodCall { 146 Yes, 147 No, 148 } 149 150 /// Denotes the "position" of a generic argument, indicating if it is a generic type, 151 /// generic function or generic method call. 152 #[derive(Copy, Clone, PartialEq)] 153 pub(crate) enum GenericArgPosition { 154 Type, 155 Value, // e.g., functions 156 MethodCall, 157 } 158 159 /// A marker denoting that the generic arguments that were 160 /// provided did not match the respective generic parameters. 161 #[derive(Clone, Default)] 162 pub struct GenericArgCountMismatch { 163 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`). 164 pub reported: Option<ErrorReported>, 165 /// A list of spans of arguments provided that were not valid. 166 pub invalid_args: Vec<Span>, 167 } 168 169 /// Decorates the result of a generic argument count mismatch 170 /// check with whether explicit late bounds were provided. 171 #[derive(Clone)] 172 pub struct GenericArgCountResult { 173 pub explicit_late_bound: ExplicitLateBound, 174 pub correct: Result<(), GenericArgCountMismatch>, 175 } 176 177 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> { args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool)178 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool); 179 provided_kind( &mut self, param: &ty::GenericParamDef, arg: &GenericArg<'_>, ) -> subst::GenericArg<'tcx>180 fn provided_kind( 181 &mut self, 182 param: &ty::GenericParamDef, 183 arg: &GenericArg<'_>, 184 ) -> subst::GenericArg<'tcx>; 185 inferred_kind( &mut self, substs: Option<&[subst::GenericArg<'tcx>]>, param: &ty::GenericParamDef, infer_args: bool, ) -> subst::GenericArg<'tcx>186 fn inferred_kind( 187 &mut self, 188 substs: Option<&[subst::GenericArg<'tcx>]>, 189 param: &ty::GenericParamDef, 190 infer_args: bool, 191 ) -> subst::GenericArg<'tcx>; 192 } 193 194 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { 195 #[tracing::instrument(level = "debug", skip(self))] ast_region_to_region( &self, lifetime: &hir::Lifetime, def: Option<&ty::GenericParamDef>, ) -> ty::Region<'tcx>196 pub fn ast_region_to_region( 197 &self, 198 lifetime: &hir::Lifetime, 199 def: Option<&ty::GenericParamDef>, 200 ) -> ty::Region<'tcx> { 201 let tcx = self.tcx(); 202 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id)); 203 204 let r = match tcx.named_region(lifetime.hir_id) { 205 Some(rl::Region::Static) => tcx.lifetimes.re_static, 206 207 Some(rl::Region::LateBound(debruijn, index, def_id, _)) => { 208 let name = lifetime_name(def_id.expect_local()); 209 let br = ty::BoundRegion { 210 var: ty::BoundVar::from_u32(index), 211 kind: ty::BrNamed(def_id, name), 212 }; 213 tcx.mk_region(ty::ReLateBound(debruijn, br)) 214 } 215 216 Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => { 217 let br = ty::BoundRegion { 218 var: ty::BoundVar::from_u32(index), 219 kind: ty::BrAnon(anon_index), 220 }; 221 tcx.mk_region(ty::ReLateBound(debruijn, br)) 222 } 223 224 Some(rl::Region::EarlyBound(index, id, _)) => { 225 let name = lifetime_name(id.expect_local()); 226 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name })) 227 } 228 229 Some(rl::Region::Free(scope, id)) => { 230 let name = lifetime_name(id.expect_local()); 231 tcx.mk_region(ty::ReFree(ty::FreeRegion { 232 scope, 233 bound_region: ty::BrNamed(id, name), 234 })) 235 236 // (*) -- not late-bound, won't change 237 } 238 239 None => { 240 self.re_infer(def, lifetime.span).unwrap_or_else(|| { 241 debug!(?lifetime, "unelided lifetime in signature"); 242 243 // This indicates an illegal lifetime 244 // elision. `resolve_lifetime` should have 245 // reported an error in this case -- but if 246 // not, let's error out. 247 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature"); 248 249 // Supply some dummy value. We don't have an 250 // `re_error`, annoyingly, so use `'static`. 251 tcx.lifetimes.re_static 252 }) 253 } 254 }; 255 256 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r); 257 258 r 259 } 260 261 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, 262 /// returns an appropriate set of substitutions for this particular reference to `I`. ast_path_substs_for_ty( &self, span: Span, def_id: DefId, item_segment: &hir::PathSegment<'_>, ) -> SubstsRef<'tcx>263 pub fn ast_path_substs_for_ty( 264 &self, 265 span: Span, 266 def_id: DefId, 267 item_segment: &hir::PathSegment<'_>, 268 ) -> SubstsRef<'tcx> { 269 let (substs, _) = self.create_substs_for_ast_path( 270 span, 271 def_id, 272 &[], 273 item_segment, 274 item_segment.args(), 275 item_segment.infer_args, 276 None, 277 ); 278 let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args()); 279 280 if let Some(b) = assoc_bindings.first() { 281 Self::prohibit_assoc_ty_binding(self.tcx(), b.span); 282 } 283 284 substs 285 } 286 287 /// Given the type/lifetime/const arguments provided to some path (along with 288 /// an implicit `Self`, if this is a trait reference), returns the complete 289 /// set of substitutions. This may involve applying defaulted type parameters. 290 /// Also returns back constraints on associated types. 291 /// 292 /// Example: 293 /// 294 /// ``` 295 /// T: std::ops::Index<usize, Output = u32> 296 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4 297 /// ``` 298 /// 299 /// 1. The `self_ty` here would refer to the type `T`. 300 /// 2. The path in question is the path to the trait `std::ops::Index`, 301 /// which will have been resolved to a `def_id` 302 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type 303 /// parameters are returned in the `SubstsRef`, the associated type bindings like 304 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result. 305 /// 306 /// Note that the type listing given here is *exactly* what the user provided. 307 /// 308 /// For (generic) associated types 309 /// 310 /// ``` 311 /// <Vec<u8> as Iterable<u8>>::Iter::<'a> 312 /// ``` 313 /// 314 /// We have the parent substs are the substs for the parent trait: 315 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated 316 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two 317 /// lists: `[Vec<u8>, u8, 'a]`. 318 #[tracing::instrument(level = "debug", skip(self, span))] create_substs_for_ast_path<'a>( &self, span: Span, def_id: DefId, parent_substs: &[subst::GenericArg<'tcx>], seg: &hir::PathSegment<'_>, generic_args: &'a hir::GenericArgs<'_>, infer_args: bool, self_ty: Option<Ty<'tcx>>, ) -> (SubstsRef<'tcx>, GenericArgCountResult)319 fn create_substs_for_ast_path<'a>( 320 &self, 321 span: Span, 322 def_id: DefId, 323 parent_substs: &[subst::GenericArg<'tcx>], 324 seg: &hir::PathSegment<'_>, 325 generic_args: &'a hir::GenericArgs<'_>, 326 infer_args: bool, 327 self_ty: Option<Ty<'tcx>>, 328 ) -> (SubstsRef<'tcx>, GenericArgCountResult) { 329 // If the type is parameterized by this region, then replace this 330 // region with the current anon region binding (in other words, 331 // whatever & would get replaced with). 332 333 let tcx = self.tcx(); 334 let generics = tcx.generics_of(def_id); 335 debug!("generics: {:?}", generics); 336 337 if generics.has_self { 338 if generics.parent.is_some() { 339 // The parent is a trait so it should have at least one subst 340 // for the `Self` type. 341 assert!(!parent_substs.is_empty()) 342 } else { 343 // This item (presumably a trait) needs a self-type. 344 assert!(self_ty.is_some()); 345 } 346 } else { 347 assert!(self_ty.is_none() && parent_substs.is_empty()); 348 } 349 350 let arg_count = Self::check_generic_arg_count( 351 tcx, 352 span, 353 def_id, 354 seg, 355 generics, 356 generic_args, 357 GenericArgPosition::Type, 358 self_ty.is_some(), 359 infer_args, 360 ); 361 362 // Skip processing if type has no generic parameters. 363 // Traits always have `Self` as a generic parameter, which means they will not return early 364 // here and so associated type bindings will be handled regardless of whether there are any 365 // non-`Self` generic parameters. 366 if generics.params.is_empty() { 367 return (tcx.intern_substs(&[]), arg_count); 368 } 369 370 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self); 371 372 struct SubstsForAstPathCtxt<'a, 'tcx> { 373 astconv: &'a (dyn AstConv<'tcx> + 'a), 374 def_id: DefId, 375 generic_args: &'a GenericArgs<'a>, 376 span: Span, 377 missing_type_params: Vec<String>, 378 inferred_params: Vec<Span>, 379 infer_args: bool, 380 is_object: bool, 381 } 382 383 impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> { 384 fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool { 385 let tcx = self.astconv.tcx(); 386 if let GenericParamDefKind::Type { has_default, .. } = param.kind { 387 if self.is_object && has_default { 388 let default_ty = tcx.at(self.span).type_of(param.def_id); 389 let self_param = tcx.types.self_param; 390 if default_ty.walk(tcx).any(|arg| arg == self_param.into()) { 391 // There is no suitable inference default for a type parameter 392 // that references self, in an object type. 393 return true; 394 } 395 } 396 } 397 398 false 399 } 400 } 401 402 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> { 403 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) { 404 if did == self.def_id { 405 (Some(self.generic_args), self.infer_args) 406 } else { 407 // The last component of this tuple is unimportant. 408 (None, false) 409 } 410 } 411 412 fn provided_kind( 413 &mut self, 414 param: &ty::GenericParamDef, 415 arg: &GenericArg<'_>, 416 ) -> subst::GenericArg<'tcx> { 417 let tcx = self.astconv.tcx(); 418 match (¶m.kind, arg) { 419 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { 420 self.astconv.ast_region_to_region(lt, Some(param)).into() 421 } 422 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => { 423 if has_default { 424 tcx.check_optional_stability( 425 param.def_id, 426 Some(arg.id()), 427 arg.span(), 428 None, 429 |_, _| { 430 // Default generic parameters may not be marked 431 // with stability attributes, i.e. when the 432 // default parameter was defined at the same time 433 // as the rest of the type. As such, we ignore missing 434 // stability attributes. 435 }, 436 ) 437 } 438 if let (hir::TyKind::Infer, false) = 439 (&ty.kind, self.astconv.allow_ty_infer()) 440 { 441 self.inferred_params.push(ty.span); 442 tcx.ty_error().into() 443 } else { 444 self.astconv.ast_ty_to_ty(ty).into() 445 } 446 } 447 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => { 448 ty::Const::from_opt_const_arg_anon_const( 449 tcx, 450 ty::WithOptConstParam { 451 did: tcx.hir().local_def_id(ct.value.hir_id), 452 const_param_did: Some(param.def_id), 453 }, 454 ) 455 .into() 456 } 457 (&GenericParamDefKind::Const { has_default }, hir::GenericArg::Infer(inf)) => { 458 if has_default { 459 tcx.const_param_default(param.def_id).into() 460 } else if self.astconv.allow_ty_infer() { 461 // FIXME(const_generics): Actually infer parameter here? 462 todo!() 463 } else { 464 self.inferred_params.push(inf.span); 465 tcx.ty_error().into() 466 } 467 } 468 ( 469 &GenericParamDefKind::Type { has_default, .. }, 470 hir::GenericArg::Infer(inf), 471 ) => { 472 if has_default { 473 tcx.check_optional_stability( 474 param.def_id, 475 Some(arg.id()), 476 arg.span(), 477 None, 478 |_, _| { 479 // Default generic parameters may not be marked 480 // with stability attributes, i.e. when the 481 // default parameter was defined at the same time 482 // as the rest of the type. As such, we ignore missing 483 // stability attributes. 484 }, 485 ); 486 } 487 if self.astconv.allow_ty_infer() { 488 self.astconv.ast_ty_to_ty(&inf.to_ty()).into() 489 } else { 490 self.inferred_params.push(inf.span); 491 tcx.ty_error().into() 492 } 493 } 494 _ => unreachable!(), 495 } 496 } 497 498 fn inferred_kind( 499 &mut self, 500 substs: Option<&[subst::GenericArg<'tcx>]>, 501 param: &ty::GenericParamDef, 502 infer_args: bool, 503 ) -> subst::GenericArg<'tcx> { 504 let tcx = self.astconv.tcx(); 505 match param.kind { 506 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(), 507 GenericParamDefKind::Type { has_default, .. } => { 508 if !infer_args && has_default { 509 // No type parameter provided, but a default exists. 510 511 // If we are converting an object type, then the 512 // `Self` parameter is unknown. However, some of the 513 // other type parameters may reference `Self` in their 514 // defaults. This will lead to an ICE if we are not 515 // careful! 516 if self.default_needs_object_self(param) { 517 self.missing_type_params.push(param.name.to_string()); 518 tcx.ty_error().into() 519 } else { 520 // This is a default type parameter. 521 let substs = substs.unwrap(); 522 if substs.iter().any(|arg| match arg.unpack() { 523 GenericArgKind::Type(ty) => ty.references_error(), 524 _ => false, 525 }) { 526 // Avoid ICE #86756 when type error recovery goes awry. 527 return tcx.ty_error().into(); 528 } 529 self.astconv 530 .normalize_ty( 531 self.span, 532 tcx.at(self.span).type_of(param.def_id).subst_spanned( 533 tcx, 534 substs, 535 Some(self.span), 536 ), 537 ) 538 .into() 539 } 540 } else if infer_args { 541 // No type parameters were provided, we can infer all. 542 let param = if !self.default_needs_object_self(param) { 543 Some(param) 544 } else { 545 None 546 }; 547 self.astconv.ty_infer(param, self.span).into() 548 } else { 549 // We've already errored above about the mismatch. 550 tcx.ty_error().into() 551 } 552 } 553 GenericParamDefKind::Const { has_default } => { 554 let ty = tcx.at(self.span).type_of(param.def_id); 555 if !infer_args && has_default { 556 tcx.const_param_default(param.def_id) 557 .subst_spanned(tcx, substs.unwrap(), Some(self.span)) 558 .into() 559 } else { 560 if infer_args { 561 self.astconv.ct_infer(ty, Some(param), self.span).into() 562 } else { 563 // We've already errored above about the mismatch. 564 tcx.const_error(ty).into() 565 } 566 } 567 } 568 } 569 } 570 } 571 572 let mut substs_ctx = SubstsForAstPathCtxt { 573 astconv: self, 574 def_id, 575 span, 576 generic_args, 577 missing_type_params: vec![], 578 inferred_params: vec![], 579 infer_args, 580 is_object, 581 }; 582 let substs = Self::create_substs_for_generic_args( 583 tcx, 584 def_id, 585 parent_substs, 586 self_ty.is_some(), 587 self_ty, 588 &arg_count, 589 &mut substs_ctx, 590 ); 591 592 self.complain_about_missing_type_params( 593 substs_ctx.missing_type_params, 594 def_id, 595 span, 596 generic_args.args.is_empty(), 597 ); 598 599 debug!( 600 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}", 601 generics, self_ty, substs 602 ); 603 604 (substs, arg_count) 605 } 606 create_assoc_bindings_for_generic_args<'a>( &self, generic_args: &'a hir::GenericArgs<'_>, ) -> Vec<ConvertedBinding<'a, 'tcx>>607 fn create_assoc_bindings_for_generic_args<'a>( 608 &self, 609 generic_args: &'a hir::GenericArgs<'_>, 610 ) -> Vec<ConvertedBinding<'a, 'tcx>> { 611 // Convert associated-type bindings or constraints into a separate vector. 612 // Example: Given this: 613 // 614 // T: Iterator<Item = u32> 615 // 616 // The `T` is passed in as a self-type; the `Item = u32` is 617 // not a "type parameter" of the `Iterator` trait, but rather 618 // a restriction on `<T as Iterator>::Item`, so it is passed 619 // back separately. 620 let assoc_bindings = generic_args 621 .bindings 622 .iter() 623 .map(|binding| { 624 let kind = match binding.kind { 625 hir::TypeBindingKind::Equality { ty } => { 626 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty)) 627 } 628 hir::TypeBindingKind::Constraint { bounds } => { 629 ConvertedBindingKind::Constraint(bounds) 630 } 631 }; 632 ConvertedBinding { 633 hir_id: binding.hir_id, 634 item_name: binding.ident, 635 kind, 636 gen_args: binding.gen_args, 637 span: binding.span, 638 } 639 }) 640 .collect(); 641 642 assoc_bindings 643 } 644 create_substs_for_associated_item( &self, tcx: TyCtxt<'tcx>, span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'_>, parent_substs: SubstsRef<'tcx>, ) -> SubstsRef<'tcx>645 crate fn create_substs_for_associated_item( 646 &self, 647 tcx: TyCtxt<'tcx>, 648 span: Span, 649 item_def_id: DefId, 650 item_segment: &hir::PathSegment<'_>, 651 parent_substs: SubstsRef<'tcx>, 652 ) -> SubstsRef<'tcx> { 653 debug!( 654 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}", 655 span, item_def_id, item_segment 656 ); 657 if tcx.generics_of(item_def_id).params.is_empty() { 658 self.prohibit_generics(slice::from_ref(item_segment)); 659 660 parent_substs 661 } else { 662 self.create_substs_for_ast_path( 663 span, 664 item_def_id, 665 parent_substs, 666 item_segment, 667 item_segment.args(), 668 item_segment.infer_args, 669 None, 670 ) 671 .0 672 } 673 } 674 675 /// Instantiates the path for the given trait reference, assuming that it's 676 /// bound to a valid trait type. Returns the `DefId` of the defining trait. 677 /// The type _cannot_ be a type other than a trait type. 678 /// 679 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>` 680 /// are disallowed. Otherwise, they are pushed onto the vector given. instantiate_mono_trait_ref( &self, trait_ref: &hir::TraitRef<'_>, self_ty: Ty<'tcx>, ) -> ty::TraitRef<'tcx>681 pub fn instantiate_mono_trait_ref( 682 &self, 683 trait_ref: &hir::TraitRef<'_>, 684 self_ty: Ty<'tcx>, 685 ) -> ty::TraitRef<'tcx> { 686 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); 687 688 self.ast_path_to_mono_trait_ref( 689 trait_ref.path.span, 690 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()), 691 self_ty, 692 trait_ref.path.segments.last().unwrap(), 693 ) 694 } 695 instantiate_poly_trait_ref_inner( &self, hir_id: hir::HirId, span: Span, binding_span: Option<Span>, constness: ty::BoundConstness, bounds: &mut Bounds<'tcx>, speculative: bool, trait_ref_span: Span, trait_def_id: DefId, trait_segment: &hir::PathSegment<'_>, args: &GenericArgs<'_>, infer_args: bool, self_ty: Ty<'tcx>, ) -> GenericArgCountResult696 fn instantiate_poly_trait_ref_inner( 697 &self, 698 hir_id: hir::HirId, 699 span: Span, 700 binding_span: Option<Span>, 701 constness: ty::BoundConstness, 702 bounds: &mut Bounds<'tcx>, 703 speculative: bool, 704 trait_ref_span: Span, 705 trait_def_id: DefId, 706 trait_segment: &hir::PathSegment<'_>, 707 args: &GenericArgs<'_>, 708 infer_args: bool, 709 self_ty: Ty<'tcx>, 710 ) -> GenericArgCountResult { 711 let (substs, arg_count) = self.create_substs_for_ast_path( 712 trait_ref_span, 713 trait_def_id, 714 &[], 715 trait_segment, 716 args, 717 infer_args, 718 Some(self_ty), 719 ); 720 721 let tcx = self.tcx(); 722 let bound_vars = tcx.late_bound_vars(hir_id); 723 debug!(?bound_vars); 724 725 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args); 726 727 let poly_trait_ref = 728 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars); 729 730 debug!(?poly_trait_ref, ?assoc_bindings); 731 bounds.trait_bounds.push((poly_trait_ref, span, constness)); 732 733 let mut dup_bindings = FxHashMap::default(); 734 for binding in &assoc_bindings { 735 // Specify type to assert that error was already reported in `Err` case. 736 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding( 737 hir_id, 738 poly_trait_ref, 739 binding, 740 bounds, 741 speculative, 742 &mut dup_bindings, 743 binding_span.unwrap_or(binding.span), 744 ); 745 // Okay to ignore `Err` because of `ErrorReported` (see above). 746 } 747 748 arg_count 749 } 750 751 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct 752 /// a full trait reference. The resulting trait reference is returned. This may also generate 753 /// auxiliary bounds, which are added to `bounds`. 754 /// 755 /// Example: 756 /// 757 /// ``` 758 /// poly_trait_ref = Iterator<Item = u32> 759 /// self_ty = Foo 760 /// ``` 761 /// 762 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`. 763 /// 764 /// **A note on binders:** against our usual convention, there is an implied bounder around 765 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions. 766 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>` 767 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be 768 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly, 769 /// however. 770 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))] instantiate_poly_trait_ref( &self, trait_ref: &hir::TraitRef<'_>, span: Span, constness: ty::BoundConstness, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx>, speculative: bool, ) -> GenericArgCountResult771 pub(crate) fn instantiate_poly_trait_ref( 772 &self, 773 trait_ref: &hir::TraitRef<'_>, 774 span: Span, 775 constness: ty::BoundConstness, 776 self_ty: Ty<'tcx>, 777 bounds: &mut Bounds<'tcx>, 778 speculative: bool, 779 ) -> GenericArgCountResult { 780 let hir_id = trait_ref.hir_ref_id; 781 let binding_span = None; 782 let trait_ref_span = trait_ref.path.span; 783 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()); 784 let trait_segment = trait_ref.path.segments.last().unwrap(); 785 let args = trait_segment.args(); 786 let infer_args = trait_segment.infer_args; 787 788 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1); 789 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment); 790 791 self.instantiate_poly_trait_ref_inner( 792 hir_id, 793 span, 794 binding_span, 795 constness, 796 bounds, 797 speculative, 798 trait_ref_span, 799 trait_def_id, 800 trait_segment, 801 args, 802 infer_args, 803 self_ty, 804 ) 805 } 806 instantiate_lang_item_trait_ref( &self, lang_item: hir::LangItem, span: Span, hir_id: hir::HirId, args: &GenericArgs<'_>, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx>, )807 pub(crate) fn instantiate_lang_item_trait_ref( 808 &self, 809 lang_item: hir::LangItem, 810 span: Span, 811 hir_id: hir::HirId, 812 args: &GenericArgs<'_>, 813 self_ty: Ty<'tcx>, 814 bounds: &mut Bounds<'tcx>, 815 ) { 816 let binding_span = Some(span); 817 let constness = ty::BoundConstness::NotConst; 818 let speculative = false; 819 let trait_ref_span = span; 820 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span)); 821 let trait_segment = &hir::PathSegment::invalid(); 822 let infer_args = false; 823 824 self.instantiate_poly_trait_ref_inner( 825 hir_id, 826 span, 827 binding_span, 828 constness, 829 bounds, 830 speculative, 831 trait_ref_span, 832 trait_def_id, 833 trait_segment, 834 args, 835 infer_args, 836 self_ty, 837 ); 838 } 839 ast_path_to_mono_trait_ref( &self, span: Span, trait_def_id: DefId, self_ty: Ty<'tcx>, trait_segment: &hir::PathSegment<'_>, ) -> ty::TraitRef<'tcx>840 fn ast_path_to_mono_trait_ref( 841 &self, 842 span: Span, 843 trait_def_id: DefId, 844 self_ty: Ty<'tcx>, 845 trait_segment: &hir::PathSegment<'_>, 846 ) -> ty::TraitRef<'tcx> { 847 let (substs, _) = 848 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment); 849 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args()); 850 if let Some(b) = assoc_bindings.first() { 851 Self::prohibit_assoc_ty_binding(self.tcx(), b.span); 852 } 853 ty::TraitRef::new(trait_def_id, substs) 854 } 855 856 #[tracing::instrument(level = "debug", skip(self, span))] create_substs_for_ast_trait_ref<'a>( &self, span: Span, trait_def_id: DefId, self_ty: Ty<'tcx>, trait_segment: &'a hir::PathSegment<'a>, ) -> (SubstsRef<'tcx>, GenericArgCountResult)857 fn create_substs_for_ast_trait_ref<'a>( 858 &self, 859 span: Span, 860 trait_def_id: DefId, 861 self_ty: Ty<'tcx>, 862 trait_segment: &'a hir::PathSegment<'a>, 863 ) -> (SubstsRef<'tcx>, GenericArgCountResult) { 864 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment); 865 866 self.create_substs_for_ast_path( 867 span, 868 trait_def_id, 869 &[], 870 trait_segment, 871 trait_segment.args(), 872 trait_segment.infer_args, 873 Some(self_ty), 874 ) 875 } 876 trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool877 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool { 878 self.tcx() 879 .associated_items(trait_def_id) 880 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id) 881 .is_some() 882 } 883 884 // Sets `implicitly_sized` to true on `Bounds` if necessary add_implicitly_sized<'hir>( &self, bounds: &mut Bounds<'hir>, ast_bounds: &'hir [hir::GenericBound<'hir>], self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>, span: Span, )885 pub(crate) fn add_implicitly_sized<'hir>( 886 &self, 887 bounds: &mut Bounds<'hir>, 888 ast_bounds: &'hir [hir::GenericBound<'hir>], 889 self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>, 890 span: Span, 891 ) { 892 let tcx = self.tcx(); 893 894 // Try to find an unbound in bounds. 895 let mut unbound = None; 896 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| { 897 for ab in ast_bounds { 898 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab { 899 if unbound.is_none() { 900 unbound = Some(&ptr.trait_ref); 901 } else { 902 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span }); 903 } 904 } 905 } 906 }; 907 search_bounds(ast_bounds); 908 if let Some((self_ty, where_clause)) = self_ty_where_predicates { 909 let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id(); 910 for clause in where_clause { 911 if let hir::WherePredicate::BoundPredicate(pred) = clause { 912 match pred.bounded_ty.kind { 913 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => match path.res { 914 Res::Def(DefKind::TyParam, def_id) if def_id == self_ty_def_id => {} 915 _ => continue, 916 }, 917 _ => continue, 918 } 919 search_bounds(pred.bounds); 920 } 921 } 922 } 923 924 let sized_def_id = tcx.lang_items().require(LangItem::Sized); 925 match (&sized_def_id, unbound) { 926 (Ok(sized_def_id), Some(tpb)) 927 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) => 928 { 929 // There was in fact a `?Sized` bound, return without doing anything 930 return; 931 } 932 (_, Some(_)) => { 933 // There was a `?Trait` bound, but it was not `?Sized`; warn. 934 tcx.sess.span_warn( 935 span, 936 "default bound relaxed for a type parameter, but \ 937 this does nothing because the given bound is not \ 938 a default; only `?Sized` is supported", 939 ); 940 // Otherwise, add implicitly sized if `Sized` is available. 941 } 942 _ => { 943 // There was no `?Sized` bound; add implicitly sized if `Sized` is available. 944 } 945 } 946 if sized_def_id.is_err() { 947 // No lang item for `Sized`, so we can't add it as a bound. 948 return; 949 } 950 bounds.implicitly_sized = Some(span); 951 } 952 953 /// This helper takes a *converted* parameter type (`param_ty`) 954 /// and an *unconverted* list of bounds: 955 /// 956 /// ```text 957 /// fn foo<T: Debug> 958 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form 959 /// | 960 /// `param_ty`, in ty form 961 /// ``` 962 /// 963 /// It adds these `ast_bounds` into the `bounds` structure. 964 /// 965 /// **A note on binders:** there is an implied binder around 966 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref` 967 /// for more details. 968 #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))] add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>( &self, param_ty: Ty<'tcx>, ast_bounds: I, bounds: &mut Bounds<'tcx>, bound_vars: &'tcx ty::List<ty::BoundVariableKind>, )969 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>( 970 &self, 971 param_ty: Ty<'tcx>, 972 ast_bounds: I, 973 bounds: &mut Bounds<'tcx>, 974 bound_vars: &'tcx ty::List<ty::BoundVariableKind>, 975 ) { 976 for ast_bound in ast_bounds { 977 match ast_bound { 978 hir::GenericBound::Trait(poly_trait_ref, modifier) => { 979 let constness = match modifier { 980 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst, 981 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst, 982 hir::TraitBoundModifier::Maybe => continue, 983 }; 984 985 let _ = self.instantiate_poly_trait_ref( 986 &poly_trait_ref.trait_ref, 987 poly_trait_ref.span, 988 constness, 989 param_ty, 990 bounds, 991 false, 992 ); 993 } 994 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => { 995 self.instantiate_lang_item_trait_ref( 996 lang_item, span, hir_id, args, param_ty, bounds, 997 ); 998 } 999 hir::GenericBound::Outlives(lifetime) => { 1000 let region = self.ast_region_to_region(lifetime, None); 1001 bounds 1002 .region_bounds 1003 .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span)); 1004 } 1005 } 1006 } 1007 } 1008 1009 /// Translates a list of bounds from the HIR into the `Bounds` data structure. 1010 /// The self-type for the bounds is given by `param_ty`. 1011 /// 1012 /// Example: 1013 /// 1014 /// ``` 1015 /// fn foo<T: Bar + Baz>() { } 1016 /// ^ ^^^^^^^^^ ast_bounds 1017 /// param_ty 1018 /// ``` 1019 /// 1020 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be 1021 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the 1022 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`. 1023 /// 1024 /// `span` should be the declaration size of the parameter. compute_bounds( &self, param_ty: Ty<'tcx>, ast_bounds: &[hir::GenericBound<'_>], ) -> Bounds<'tcx>1025 pub(crate) fn compute_bounds( 1026 &self, 1027 param_ty: Ty<'tcx>, 1028 ast_bounds: &[hir::GenericBound<'_>], 1029 ) -> Bounds<'tcx> { 1030 self.compute_bounds_inner(param_ty, ast_bounds) 1031 } 1032 1033 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type 1034 /// named `assoc_name` into ty::Bounds. Ignore the rest. compute_bounds_that_match_assoc_type( &self, param_ty: Ty<'tcx>, ast_bounds: &[hir::GenericBound<'_>], assoc_name: Ident, ) -> Bounds<'tcx>1035 pub(crate) fn compute_bounds_that_match_assoc_type( 1036 &self, 1037 param_ty: Ty<'tcx>, 1038 ast_bounds: &[hir::GenericBound<'_>], 1039 assoc_name: Ident, 1040 ) -> Bounds<'tcx> { 1041 let mut result = Vec::new(); 1042 1043 for ast_bound in ast_bounds { 1044 if let Some(trait_ref) = ast_bound.trait_ref() { 1045 if let Some(trait_did) = trait_ref.trait_def_id() { 1046 if self.tcx().trait_may_define_assoc_type(trait_did, assoc_name) { 1047 result.push(ast_bound.clone()); 1048 } 1049 } 1050 } 1051 } 1052 1053 self.compute_bounds_inner(param_ty, &result) 1054 } 1055 compute_bounds_inner( &self, param_ty: Ty<'tcx>, ast_bounds: &[hir::GenericBound<'_>], ) -> Bounds<'tcx>1056 fn compute_bounds_inner( 1057 &self, 1058 param_ty: Ty<'tcx>, 1059 ast_bounds: &[hir::GenericBound<'_>], 1060 ) -> Bounds<'tcx> { 1061 let mut bounds = Bounds::default(); 1062 1063 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty()); 1064 1065 bounds 1066 } 1067 1068 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates 1069 /// onto `bounds`. 1070 /// 1071 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the 1072 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside* 1073 /// the binder (e.g., `&'a u32`) and hence may reference bound regions. 1074 #[tracing::instrument( 1075 level = "debug", 1076 skip(self, bounds, speculative, dup_bindings, path_span) 1077 )] add_predicates_for_ast_type_binding( &self, hir_ref_id: hir::HirId, trait_ref: ty::PolyTraitRef<'tcx>, binding: &ConvertedBinding<'_, 'tcx>, bounds: &mut Bounds<'tcx>, speculative: bool, dup_bindings: &mut FxHashMap<DefId, Span>, path_span: Span, ) -> Result<(), ErrorReported>1078 fn add_predicates_for_ast_type_binding( 1079 &self, 1080 hir_ref_id: hir::HirId, 1081 trait_ref: ty::PolyTraitRef<'tcx>, 1082 binding: &ConvertedBinding<'_, 'tcx>, 1083 bounds: &mut Bounds<'tcx>, 1084 speculative: bool, 1085 dup_bindings: &mut FxHashMap<DefId, Span>, 1086 path_span: Span, 1087 ) -> Result<(), ErrorReported> { 1088 // Given something like `U: SomeTrait<T = X>`, we want to produce a 1089 // predicate like `<U as SomeTrait>::T = X`. This is somewhat 1090 // subtle in the event that `T` is defined in a supertrait of 1091 // `SomeTrait`, because in that case we need to upcast. 1092 // 1093 // That is, consider this case: 1094 // 1095 // ``` 1096 // trait SubTrait: SuperTrait<i32> { } 1097 // trait SuperTrait<A> { type T; } 1098 // 1099 // ... B: SubTrait<T = foo> ... 1100 // ``` 1101 // 1102 // We want to produce `<B as SuperTrait<i32>>::T == foo`. 1103 1104 let tcx = self.tcx(); 1105 1106 let candidate = 1107 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) { 1108 // Simple case: X is defined in the current trait. 1109 trait_ref 1110 } else { 1111 // Otherwise, we have to walk through the supertraits to find 1112 // those that do. 1113 self.one_bound_for_assoc_type( 1114 || traits::supertraits(tcx, trait_ref), 1115 || trait_ref.print_only_trait_path().to_string(), 1116 binding.item_name, 1117 path_span, 1118 || match binding.kind { 1119 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()), 1120 _ => None, 1121 }, 1122 )? 1123 }; 1124 1125 let (assoc_ident, def_scope) = 1126 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id); 1127 1128 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead 1129 // of calling `filter_by_name_and_kind`. 1130 let assoc_ty = tcx 1131 .associated_items(candidate.def_id()) 1132 .filter_by_name_unhygienic(assoc_ident.name) 1133 .find(|i| { 1134 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident 1135 }) 1136 .expect("missing associated type"); 1137 1138 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) { 1139 tcx.sess 1140 .struct_span_err( 1141 binding.span, 1142 &format!("associated type `{}` is private", binding.item_name), 1143 ) 1144 .span_label(binding.span, "private associated type") 1145 .emit(); 1146 } 1147 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span, None); 1148 1149 if !speculative { 1150 dup_bindings 1151 .entry(assoc_ty.def_id) 1152 .and_modify(|prev_span| { 1153 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified { 1154 span: binding.span, 1155 prev_span: *prev_span, 1156 item_name: binding.item_name, 1157 def_path: tcx.def_path_str(assoc_ty.container.id()), 1158 }); 1159 }) 1160 .or_insert(binding.span); 1161 } 1162 1163 // Include substitutions for generic parameters of associated types 1164 let projection_ty = candidate.map_bound(|trait_ref| { 1165 let ident = Ident::new(assoc_ty.ident.name, binding.item_name.span); 1166 let item_segment = hir::PathSegment { 1167 ident, 1168 hir_id: Some(binding.hir_id), 1169 res: None, 1170 args: Some(binding.gen_args), 1171 infer_args: false, 1172 }; 1173 1174 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item( 1175 tcx, 1176 path_span, 1177 assoc_ty.def_id, 1178 &item_segment, 1179 trait_ref.substs, 1180 ); 1181 1182 debug!( 1183 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}", 1184 substs_trait_ref_and_assoc_item 1185 ); 1186 1187 ty::ProjectionTy { 1188 item_def_id: assoc_ty.def_id, 1189 substs: substs_trait_ref_and_assoc_item, 1190 } 1191 }); 1192 1193 if !speculative { 1194 // Find any late-bound regions declared in `ty` that are not 1195 // declared in the trait-ref or assoc_ty. These are not well-formed. 1196 // 1197 // Example: 1198 // 1199 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad 1200 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok 1201 if let ConvertedBindingKind::Equality(ty) = binding.kind { 1202 let late_bound_in_trait_ref = 1203 tcx.collect_constrained_late_bound_regions(&projection_ty); 1204 let late_bound_in_ty = 1205 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty)); 1206 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref); 1207 debug!("late_bound_in_ty = {:?}", late_bound_in_ty); 1208 1209 // FIXME: point at the type params that don't have appropriate lifetimes: 1210 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F); 1211 // ---- ---- ^^^^^^^ 1212 self.validate_late_bound_regions( 1213 late_bound_in_trait_ref, 1214 late_bound_in_ty, 1215 |br_name| { 1216 struct_span_err!( 1217 tcx.sess, 1218 binding.span, 1219 E0582, 1220 "binding for associated type `{}` references {}, \ 1221 which does not appear in the trait input types", 1222 binding.item_name, 1223 br_name 1224 ) 1225 }, 1226 ); 1227 } 1228 } 1229 1230 match binding.kind { 1231 ConvertedBindingKind::Equality(ty) => { 1232 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to 1233 // the "projection predicate" for: 1234 // 1235 // `<T as Iterator>::Item = u32` 1236 bounds.projection_bounds.push(( 1237 projection_ty.map_bound(|projection_ty| { 1238 debug!( 1239 "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}", 1240 projection_ty, projection_ty.substs 1241 ); 1242 ty::ProjectionPredicate { projection_ty, ty } 1243 }), 1244 binding.span, 1245 )); 1246 } 1247 ConvertedBindingKind::Constraint(ast_bounds) => { 1248 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to 1249 // 1250 // `<T as Iterator>::Item: Debug` 1251 // 1252 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty` 1253 // parameter to have a skipped binder. 1254 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder())); 1255 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars()); 1256 } 1257 } 1258 Ok(()) 1259 } 1260 ast_path_to_ty( &self, span: Span, did: DefId, item_segment: &hir::PathSegment<'_>, ) -> Ty<'tcx>1261 fn ast_path_to_ty( 1262 &self, 1263 span: Span, 1264 did: DefId, 1265 item_segment: &hir::PathSegment<'_>, 1266 ) -> Ty<'tcx> { 1267 let substs = self.ast_path_substs_for_ty(span, did, item_segment); 1268 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs)) 1269 } 1270 conv_object_ty_poly_trait_ref( &self, span: Span, trait_bounds: &[hir::PolyTraitRef<'_>], lifetime: &hir::Lifetime, borrowed: bool, ) -> Ty<'tcx>1271 fn conv_object_ty_poly_trait_ref( 1272 &self, 1273 span: Span, 1274 trait_bounds: &[hir::PolyTraitRef<'_>], 1275 lifetime: &hir::Lifetime, 1276 borrowed: bool, 1277 ) -> Ty<'tcx> { 1278 let tcx = self.tcx(); 1279 1280 let mut bounds = Bounds::default(); 1281 let mut potential_assoc_types = Vec::new(); 1282 let dummy_self = self.tcx().types.trait_object_dummy_self; 1283 for trait_bound in trait_bounds.iter().rev() { 1284 if let GenericArgCountResult { 1285 correct: 1286 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }), 1287 .. 1288 } = self.instantiate_poly_trait_ref( 1289 &trait_bound.trait_ref, 1290 trait_bound.span, 1291 ty::BoundConstness::NotConst, 1292 dummy_self, 1293 &mut bounds, 1294 false, 1295 ) { 1296 potential_assoc_types.extend(cur_potential_assoc_types); 1297 } 1298 } 1299 1300 // Expand trait aliases recursively and check that only one regular (non-auto) trait 1301 // is used and no 'maybe' bounds are used. 1302 let expanded_traits = 1303 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b))); 1304 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = 1305 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id())); 1306 if regular_traits.len() > 1 { 1307 let first_trait = ®ular_traits[0]; 1308 let additional_trait = ®ular_traits[1]; 1309 let mut err = struct_span_err!( 1310 tcx.sess, 1311 additional_trait.bottom().1, 1312 E0225, 1313 "only auto traits can be used as additional traits in a trait object" 1314 ); 1315 additional_trait.label_with_exp_info( 1316 &mut err, 1317 "additional non-auto trait", 1318 "additional use", 1319 ); 1320 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use"); 1321 err.help(&format!( 1322 "consider creating a new trait with all of these as supertraits and using that \ 1323 trait here instead: `trait NewTrait: {} {{}}`", 1324 regular_traits 1325 .iter() 1326 .map(|t| t.trait_ref().print_only_trait_path().to_string()) 1327 .collect::<Vec<_>>() 1328 .join(" + "), 1329 )); 1330 err.note( 1331 "auto-traits like `Send` and `Sync` are traits that have special properties; \ 1332 for more information on them, visit \ 1333 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>", 1334 ); 1335 err.emit(); 1336 } 1337 1338 if regular_traits.is_empty() && auto_traits.is_empty() { 1339 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span }); 1340 return tcx.ty_error(); 1341 } 1342 1343 // Check that there are no gross object safety violations; 1344 // most importantly, that the supertraits don't contain `Self`, 1345 // to avoid ICEs. 1346 for item in ®ular_traits { 1347 let object_safety_violations = 1348 astconv_object_safety_violations(tcx, item.trait_ref().def_id()); 1349 if !object_safety_violations.is_empty() { 1350 report_object_safety_error( 1351 tcx, 1352 span, 1353 item.trait_ref().def_id(), 1354 &object_safety_violations[..], 1355 ) 1356 .emit(); 1357 return tcx.ty_error(); 1358 } 1359 } 1360 1361 // Use a `BTreeSet` to keep output in a more consistent order. 1362 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default(); 1363 1364 let regular_traits_refs_spans = bounds 1365 .trait_bounds 1366 .into_iter() 1367 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id())); 1368 1369 for (base_trait_ref, span, constness) in regular_traits_refs_spans { 1370 assert_eq!(constness, ty::BoundConstness::NotConst); 1371 1372 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) { 1373 debug!( 1374 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", 1375 obligation.predicate 1376 ); 1377 1378 let bound_predicate = obligation.predicate.kind(); 1379 match bound_predicate.skip_binder() { 1380 ty::PredicateKind::Trait(pred) => { 1381 let pred = bound_predicate.rebind(pred); 1382 associated_types.entry(span).or_default().extend( 1383 tcx.associated_items(pred.def_id()) 1384 .in_definition_order() 1385 .filter(|item| item.kind == ty::AssocKind::Type) 1386 .map(|item| item.def_id), 1387 ); 1388 } 1389 ty::PredicateKind::Projection(pred) => { 1390 let pred = bound_predicate.rebind(pred); 1391 // A `Self` within the original bound will be substituted with a 1392 // `trait_object_dummy_self`, so check for that. 1393 let references_self = 1394 pred.skip_binder().ty.walk(tcx).any(|arg| arg == dummy_self.into()); 1395 1396 // If the projection output contains `Self`, force the user to 1397 // elaborate it explicitly to avoid a lot of complexity. 1398 // 1399 // The "classicaly useful" case is the following: 1400 // ``` 1401 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput { 1402 // type MyOutput; 1403 // } 1404 // ``` 1405 // 1406 // Here, the user could theoretically write `dyn MyTrait<Output = X>`, 1407 // but actually supporting that would "expand" to an infinitely-long type 1408 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`. 1409 // 1410 // Instead, we force the user to write 1411 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See 1412 // the discussion in #56288 for alternatives. 1413 if !references_self { 1414 // Include projections defined on supertraits. 1415 bounds.projection_bounds.push((pred, span)); 1416 } 1417 } 1418 _ => (), 1419 } 1420 } 1421 } 1422 1423 for (projection_bound, _) in &bounds.projection_bounds { 1424 for def_ids in associated_types.values_mut() { 1425 def_ids.remove(&projection_bound.projection_def_id()); 1426 } 1427 } 1428 1429 self.complain_about_missing_associated_types( 1430 associated_types, 1431 potential_assoc_types, 1432 trait_bounds, 1433 ); 1434 1435 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as 1436 // `dyn Trait + Send`. 1437 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering 1438 // the bounds 1439 let mut duplicates = FxHashSet::default(); 1440 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id())); 1441 debug!("regular_traits: {:?}", regular_traits); 1442 debug!("auto_traits: {:?}", auto_traits); 1443 1444 // Erase the `dummy_self` (`trait_object_dummy_self`) used above. 1445 let existential_trait_refs = regular_traits.iter().map(|i| { 1446 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| { 1447 if trait_ref.self_ty() != dummy_self { 1448 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`, 1449 // which picks up non-supertraits where clauses - but also, the object safety 1450 // completely ignores trait aliases, which could be object safety hazards. We 1451 // `delay_span_bug` here to avoid an ICE in stable even when the feature is 1452 // disabled. (#66420) 1453 tcx.sess.delay_span_bug( 1454 DUMMY_SP, 1455 &format!( 1456 "trait_ref_to_existential called on {:?} with non-dummy Self", 1457 trait_ref, 1458 ), 1459 ); 1460 } 1461 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref) 1462 }) 1463 }); 1464 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| { 1465 bound.map_bound(|b| { 1466 if b.projection_ty.self_ty() != dummy_self { 1467 tcx.sess.delay_span_bug( 1468 DUMMY_SP, 1469 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b), 1470 ); 1471 } 1472 ty::ExistentialProjection::erase_self_ty(tcx, b) 1473 }) 1474 }); 1475 1476 let regular_trait_predicates = existential_trait_refs 1477 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait)); 1478 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| { 1479 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id())) 1480 }); 1481 // N.b. principal, projections, auto traits 1482 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling 1483 let mut v = regular_trait_predicates 1484 .chain( 1485 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)), 1486 ) 1487 .chain(auto_trait_predicates) 1488 .collect::<SmallVec<[_; 8]>>(); 1489 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder())); 1490 v.dedup(); 1491 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter()); 1492 1493 // Use explicitly-specified region bound. 1494 let region_bound = if !lifetime.is_elided() { 1495 self.ast_region_to_region(lifetime, None) 1496 } else { 1497 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| { 1498 if tcx.named_region(lifetime.hir_id).is_some() { 1499 self.ast_region_to_region(lifetime, None) 1500 } else { 1501 self.re_infer(None, span).unwrap_or_else(|| { 1502 let mut err = struct_span_err!( 1503 tcx.sess, 1504 span, 1505 E0228, 1506 "the lifetime bound for this object type cannot be deduced \ 1507 from context; please supply an explicit bound" 1508 ); 1509 if borrowed { 1510 // We will have already emitted an error E0106 complaining about a 1511 // missing named lifetime in `&dyn Trait`, so we elide this one. 1512 err.delay_as_bug(); 1513 } else { 1514 err.emit(); 1515 } 1516 tcx.lifetimes.re_static 1517 }) 1518 } 1519 }) 1520 }; 1521 debug!("region_bound: {:?}", region_bound); 1522 1523 let ty = tcx.mk_dynamic(existential_predicates, region_bound); 1524 debug!("trait_object_type: {:?}", ty); 1525 ty 1526 } 1527 report_ambiguous_associated_type( &self, span: Span, type_str: &str, trait_str: &str, name: Symbol, )1528 fn report_ambiguous_associated_type( 1529 &self, 1530 span: Span, 1531 type_str: &str, 1532 trait_str: &str, 1533 name: Symbol, 1534 ) { 1535 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type"); 1536 if let (true, Ok(snippet)) = ( 1537 self.tcx() 1538 .resolutions(()) 1539 .confused_type_with_std_module 1540 .keys() 1541 .any(|full_span| full_span.contains(span)), 1542 self.tcx().sess.source_map().span_to_snippet(span), 1543 ) { 1544 err.span_suggestion( 1545 span, 1546 "you are looking for the module in `std`, not the primitive type", 1547 format!("std::{}", snippet), 1548 Applicability::MachineApplicable, 1549 ); 1550 } else { 1551 err.span_suggestion( 1552 span, 1553 "use fully-qualified syntax", 1554 format!("<{} as {}>::{}", type_str, trait_str, name), 1555 Applicability::HasPlaceholders, 1556 ); 1557 } 1558 err.emit(); 1559 } 1560 1561 // Search for a bound on a type parameter which includes the associated item 1562 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter 1563 // This function will fail if there are no suitable bounds or there is 1564 // any ambiguity. find_bound_for_assoc_item( &self, ty_param_def_id: LocalDefId, assoc_name: Ident, span: Span, ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>1565 fn find_bound_for_assoc_item( 1566 &self, 1567 ty_param_def_id: LocalDefId, 1568 assoc_name: Ident, 1569 span: Span, 1570 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> { 1571 let tcx = self.tcx(); 1572 1573 debug!( 1574 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})", 1575 ty_param_def_id, assoc_name, span, 1576 ); 1577 1578 let predicates = &self 1579 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name) 1580 .predicates; 1581 1582 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates); 1583 1584 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id); 1585 let param_name = tcx.hir().ty_param_name(param_hir_id); 1586 self.one_bound_for_assoc_type( 1587 || { 1588 traits::transitive_bounds_that_define_assoc_type( 1589 tcx, 1590 predicates.iter().filter_map(|(p, _)| { 1591 p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value) 1592 }), 1593 assoc_name, 1594 ) 1595 }, 1596 || param_name.to_string(), 1597 assoc_name, 1598 span, 1599 || None, 1600 ) 1601 } 1602 1603 // Checks that `bounds` contains exactly one element and reports appropriate 1604 // errors otherwise. one_bound_for_assoc_type<I>( &self, all_candidates: impl Fn() -> I, ty_param_name: impl Fn() -> String, assoc_name: Ident, span: Span, is_equality: impl Fn() -> Option<String>, ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> where I: Iterator<Item = ty::PolyTraitRef<'tcx>>,1605 fn one_bound_for_assoc_type<I>( 1606 &self, 1607 all_candidates: impl Fn() -> I, 1608 ty_param_name: impl Fn() -> String, 1609 assoc_name: Ident, 1610 span: Span, 1611 is_equality: impl Fn() -> Option<String>, 1612 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> 1613 where 1614 I: Iterator<Item = ty::PolyTraitRef<'tcx>>, 1615 { 1616 let mut matching_candidates = all_candidates() 1617 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name)); 1618 1619 let bound = match matching_candidates.next() { 1620 Some(bound) => bound, 1621 None => { 1622 self.complain_about_assoc_type_not_found( 1623 all_candidates, 1624 &ty_param_name(), 1625 assoc_name, 1626 span, 1627 ); 1628 return Err(ErrorReported); 1629 } 1630 }; 1631 1632 debug!("one_bound_for_assoc_type: bound = {:?}", bound); 1633 1634 if let Some(bound2) = matching_candidates.next() { 1635 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2); 1636 1637 let is_equality = is_equality(); 1638 let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates); 1639 let mut err = if is_equality.is_some() { 1640 // More specific Error Index entry. 1641 struct_span_err!( 1642 self.tcx().sess, 1643 span, 1644 E0222, 1645 "ambiguous associated type `{}` in bounds of `{}`", 1646 assoc_name, 1647 ty_param_name() 1648 ) 1649 } else { 1650 struct_span_err!( 1651 self.tcx().sess, 1652 span, 1653 E0221, 1654 "ambiguous associated type `{}` in bounds of `{}`", 1655 assoc_name, 1656 ty_param_name() 1657 ) 1658 }; 1659 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name)); 1660 1661 let mut where_bounds = vec![]; 1662 for bound in bounds { 1663 let bound_id = bound.def_id(); 1664 let bound_span = self 1665 .tcx() 1666 .associated_items(bound_id) 1667 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id) 1668 .and_then(|item| self.tcx().hir().span_if_local(item.def_id)); 1669 1670 if let Some(bound_span) = bound_span { 1671 err.span_label( 1672 bound_span, 1673 format!( 1674 "ambiguous `{}` from `{}`", 1675 assoc_name, 1676 bound.print_only_trait_path(), 1677 ), 1678 ); 1679 if let Some(constraint) = &is_equality { 1680 where_bounds.push(format!( 1681 " T: {trait}::{assoc} = {constraint}", 1682 trait=bound.print_only_trait_path(), 1683 assoc=assoc_name, 1684 constraint=constraint, 1685 )); 1686 } else { 1687 err.span_suggestion_verbose( 1688 span.with_hi(assoc_name.span.lo()), 1689 "use fully qualified syntax to disambiguate", 1690 format!( 1691 "<{} as {}>::", 1692 ty_param_name(), 1693 bound.print_only_trait_path(), 1694 ), 1695 Applicability::MaybeIncorrect, 1696 ); 1697 } 1698 } else { 1699 err.note(&format!( 1700 "associated type `{}` could derive from `{}`", 1701 ty_param_name(), 1702 bound.print_only_trait_path(), 1703 )); 1704 } 1705 } 1706 if !where_bounds.is_empty() { 1707 err.help(&format!( 1708 "consider introducing a new type parameter `T` and adding `where` constraints:\ 1709 \n where\n T: {},\n{}", 1710 ty_param_name(), 1711 where_bounds.join(",\n"), 1712 )); 1713 } 1714 err.emit(); 1715 if !where_bounds.is_empty() { 1716 return Err(ErrorReported); 1717 } 1718 } 1719 Ok(bound) 1720 } 1721 1722 // Create a type from a path to an associated type. 1723 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C` 1724 // and item_segment is the path segment for `D`. We return a type and a def for 1725 // the whole path. 1726 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type 1727 // parameter or `Self`. 1728 // NOTE: When this function starts resolving `Trait::AssocTy` successfully 1729 // it should also start reportint the `BARE_TRAIT_OBJECTS` lint. associated_path_to_ty( &self, hir_ref_id: hir::HirId, span: Span, qself_ty: Ty<'tcx>, qself_res: Res, assoc_segment: &hir::PathSegment<'_>, permit_variants: bool, ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported>1730 pub fn associated_path_to_ty( 1731 &self, 1732 hir_ref_id: hir::HirId, 1733 span: Span, 1734 qself_ty: Ty<'tcx>, 1735 qself_res: Res, 1736 assoc_segment: &hir::PathSegment<'_>, 1737 permit_variants: bool, 1738 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> { 1739 let tcx = self.tcx(); 1740 let assoc_ident = assoc_segment.ident; 1741 1742 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident); 1743 1744 // Check if we have an enum variant. 1745 let mut variant_resolution = None; 1746 if let ty::Adt(adt_def, _) = qself_ty.kind() { 1747 if adt_def.is_enum() { 1748 let variant_def = adt_def 1749 .variants 1750 .iter() 1751 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)); 1752 if let Some(variant_def) = variant_def { 1753 if permit_variants { 1754 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None); 1755 self.prohibit_generics(slice::from_ref(assoc_segment)); 1756 return Ok((qself_ty, DefKind::Variant, variant_def.def_id)); 1757 } else { 1758 variant_resolution = Some(variant_def.def_id); 1759 } 1760 } 1761 } 1762 } 1763 1764 // Find the type of the associated item, and the trait where the associated 1765 // item is declared. 1766 let bound = match (&qself_ty.kind(), qself_res) { 1767 (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => { 1768 // `Self` in an impl of a trait -- we have a concrete self type and a 1769 // trait reference. 1770 let trait_ref = match tcx.impl_trait_ref(impl_def_id) { 1771 Some(trait_ref) => trait_ref, 1772 None => { 1773 // A cycle error occurred, most likely. 1774 return Err(ErrorReported); 1775 } 1776 }; 1777 1778 self.one_bound_for_assoc_type( 1779 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)), 1780 || "Self".to_string(), 1781 assoc_ident, 1782 span, 1783 || None, 1784 )? 1785 } 1786 ( 1787 &ty::Param(_), 1788 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did), 1789 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?, 1790 _ => { 1791 if variant_resolution.is_some() { 1792 // Variant in type position 1793 let msg = format!("expected type, found variant `{}`", assoc_ident); 1794 tcx.sess.span_err(span, &msg); 1795 } else if qself_ty.is_enum() { 1796 let mut err = struct_span_err!( 1797 tcx.sess, 1798 assoc_ident.span, 1799 E0599, 1800 "no variant named `{}` found for enum `{}`", 1801 assoc_ident, 1802 qself_ty, 1803 ); 1804 1805 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT"); 1806 if let Some(suggested_name) = find_best_match_for_name( 1807 &adt_def 1808 .variants 1809 .iter() 1810 .map(|variant| variant.ident.name) 1811 .collect::<Vec<Symbol>>(), 1812 assoc_ident.name, 1813 None, 1814 ) { 1815 err.span_suggestion( 1816 assoc_ident.span, 1817 "there is a variant with a similar name", 1818 suggested_name.to_string(), 1819 Applicability::MaybeIncorrect, 1820 ); 1821 } else { 1822 err.span_label( 1823 assoc_ident.span, 1824 format!("variant not found in `{}`", qself_ty), 1825 ); 1826 } 1827 1828 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) { 1829 let sp = tcx.sess.source_map().guess_head_span(sp); 1830 err.span_label(sp, format!("variant `{}` not found here", assoc_ident)); 1831 } 1832 1833 err.emit(); 1834 } else if !qself_ty.references_error() { 1835 // Don't print `TyErr` to the user. 1836 self.report_ambiguous_associated_type( 1837 span, 1838 &qself_ty.to_string(), 1839 "Trait", 1840 assoc_ident.name, 1841 ); 1842 } 1843 return Err(ErrorReported); 1844 } 1845 }; 1846 1847 let trait_did = bound.def_id(); 1848 let (assoc_ident, def_scope) = 1849 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id); 1850 1851 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead 1852 // of calling `filter_by_name_and_kind`. 1853 let item = tcx 1854 .associated_items(trait_did) 1855 .in_definition_order() 1856 .find(|i| { 1857 i.kind.namespace() == Namespace::TypeNS 1858 && i.ident.normalize_to_macros_2_0() == assoc_ident 1859 }) 1860 .expect("missing associated type"); 1861 1862 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); 1863 let ty = self.normalize_ty(span, ty); 1864 1865 let kind = DefKind::AssocTy; 1866 if !item.vis.is_accessible_from(def_scope, tcx) { 1867 let kind = kind.descr(item.def_id); 1868 let msg = format!("{} `{}` is private", kind, assoc_ident); 1869 tcx.sess 1870 .struct_span_err(span, &msg) 1871 .span_label(span, &format!("private {}", kind)) 1872 .emit(); 1873 } 1874 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None); 1875 1876 if let Some(variant_def_id) = variant_resolution { 1877 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| { 1878 let mut err = lint.build("ambiguous associated item"); 1879 let mut could_refer_to = |kind: DefKind, def_id, also| { 1880 let note_msg = format!( 1881 "`{}` could{} refer to the {} defined here", 1882 assoc_ident, 1883 also, 1884 kind.descr(def_id) 1885 ); 1886 err.span_note(tcx.def_span(def_id), ¬e_msg); 1887 }; 1888 1889 could_refer_to(DefKind::Variant, variant_def_id, ""); 1890 could_refer_to(kind, item.def_id, " also"); 1891 1892 err.span_suggestion( 1893 span, 1894 "use fully-qualified syntax", 1895 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident), 1896 Applicability::MachineApplicable, 1897 ); 1898 1899 err.emit(); 1900 }); 1901 } 1902 Ok((ty, kind, item.def_id)) 1903 } 1904 qpath_to_ty( &self, span: Span, opt_self_ty: Option<Ty<'tcx>>, item_def_id: DefId, trait_segment: &hir::PathSegment<'_>, item_segment: &hir::PathSegment<'_>, ) -> Ty<'tcx>1905 fn qpath_to_ty( 1906 &self, 1907 span: Span, 1908 opt_self_ty: Option<Ty<'tcx>>, 1909 item_def_id: DefId, 1910 trait_segment: &hir::PathSegment<'_>, 1911 item_segment: &hir::PathSegment<'_>, 1912 ) -> Ty<'tcx> { 1913 let tcx = self.tcx(); 1914 1915 let trait_def_id = tcx.parent(item_def_id).unwrap(); 1916 1917 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id); 1918 1919 let Some(self_ty) = opt_self_ty else { 1920 let path_str = tcx.def_path_str(trait_def_id); 1921 1922 let def_id = self.item_def_id(); 1923 1924 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id); 1925 1926 let parent_def_id = def_id 1927 .and_then(|def_id| { 1928 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) 1929 }) 1930 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id()); 1931 1932 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id); 1933 1934 // If the trait in segment is the same as the trait defining the item, 1935 // use the `<Self as ..>` syntax in the error. 1936 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id); 1937 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id); 1938 1939 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait { 1940 "Self" 1941 } else { 1942 "Type" 1943 }; 1944 1945 self.report_ambiguous_associated_type( 1946 span, 1947 type_name, 1948 &path_str, 1949 item_segment.ident.name, 1950 ); 1951 return tcx.ty_error(); 1952 }; 1953 1954 debug!("qpath_to_ty: self_type={:?}", self_ty); 1955 1956 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment); 1957 1958 let item_substs = self.create_substs_for_associated_item( 1959 tcx, 1960 span, 1961 item_def_id, 1962 item_segment, 1963 trait_ref.substs, 1964 ); 1965 1966 debug!("qpath_to_ty: trait_ref={:?}", trait_ref); 1967 1968 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs)) 1969 } 1970 prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>( &self, segments: T, ) -> bool1971 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>( 1972 &self, 1973 segments: T, 1974 ) -> bool { 1975 let mut has_err = false; 1976 for segment in segments { 1977 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false); 1978 for arg in segment.args().args { 1979 let (span, kind) = match arg { 1980 hir::GenericArg::Lifetime(lt) => { 1981 if err_for_lt { 1982 continue; 1983 } 1984 err_for_lt = true; 1985 has_err = true; 1986 (lt.span, "lifetime") 1987 } 1988 hir::GenericArg::Type(ty) => { 1989 if err_for_ty { 1990 continue; 1991 } 1992 err_for_ty = true; 1993 has_err = true; 1994 (ty.span, "type") 1995 } 1996 hir::GenericArg::Const(ct) => { 1997 if err_for_ct { 1998 continue; 1999 } 2000 err_for_ct = true; 2001 has_err = true; 2002 (ct.span, "const") 2003 } 2004 hir::GenericArg::Infer(inf) => { 2005 if err_for_ty { 2006 continue; 2007 } 2008 has_err = true; 2009 err_for_ty = true; 2010 (inf.span, "generic") 2011 } 2012 }; 2013 let mut err = struct_span_err!( 2014 self.tcx().sess, 2015 span, 2016 E0109, 2017 "{} arguments are not allowed for this type", 2018 kind, 2019 ); 2020 err.span_label(span, format!("{} argument not allowed", kind)); 2021 err.emit(); 2022 if err_for_lt && err_for_ty && err_for_ct { 2023 break; 2024 } 2025 } 2026 2027 // Only emit the first error to avoid overloading the user with error messages. 2028 if let [binding, ..] = segment.args().bindings { 2029 has_err = true; 2030 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span); 2031 } 2032 } 2033 has_err 2034 } 2035 2036 // FIXME(eddyb, varkor) handle type paths here too, not just value ones. def_ids_for_value_path_segments( &self, segments: &[hir::PathSegment<'_>], self_ty: Option<Ty<'tcx>>, kind: DefKind, def_id: DefId, ) -> Vec<PathSeg>2037 pub fn def_ids_for_value_path_segments( 2038 &self, 2039 segments: &[hir::PathSegment<'_>], 2040 self_ty: Option<Ty<'tcx>>, 2041 kind: DefKind, 2042 def_id: DefId, 2043 ) -> Vec<PathSeg> { 2044 // We need to extract the type parameters supplied by the user in 2045 // the path `path`. Due to the current setup, this is a bit of a 2046 // tricky-process; the problem is that resolve only tells us the 2047 // end-point of the path resolution, and not the intermediate steps. 2048 // Luckily, we can (at least for now) deduce the intermediate steps 2049 // just from the end-point. 2050 // 2051 // There are basically five cases to consider: 2052 // 2053 // 1. Reference to a constructor of a struct: 2054 // 2055 // struct Foo<T>(...) 2056 // 2057 // In this case, the parameters are declared in the type space. 2058 // 2059 // 2. Reference to a constructor of an enum variant: 2060 // 2061 // enum E<T> { Foo(...) } 2062 // 2063 // In this case, the parameters are defined in the type space, 2064 // but may be specified either on the type or the variant. 2065 // 2066 // 3. Reference to a fn item or a free constant: 2067 // 2068 // fn foo<T>() { } 2069 // 2070 // In this case, the path will again always have the form 2071 // `a::b::foo::<T>` where only the final segment should have 2072 // type parameters. However, in this case, those parameters are 2073 // declared on a value, and hence are in the `FnSpace`. 2074 // 2075 // 4. Reference to a method or an associated constant: 2076 // 2077 // impl<A> SomeStruct<A> { 2078 // fn foo<B>(...) 2079 // } 2080 // 2081 // Here we can have a path like 2082 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters 2083 // may appear in two places. The penultimate segment, 2084 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the 2085 // final segment, `foo::<B>` contains parameters in fn space. 2086 // 2087 // The first step then is to categorize the segments appropriately. 2088 2089 let tcx = self.tcx(); 2090 2091 assert!(!segments.is_empty()); 2092 let last = segments.len() - 1; 2093 2094 let mut path_segs = vec![]; 2095 2096 match kind { 2097 // Case 1. Reference to a struct constructor. 2098 DefKind::Ctor(CtorOf::Struct, ..) => { 2099 // Everything but the final segment should have no 2100 // parameters at all. 2101 let generics = tcx.generics_of(def_id); 2102 // Variant and struct constructors use the 2103 // generics of their parent type definition. 2104 let generics_def_id = generics.parent.unwrap_or(def_id); 2105 path_segs.push(PathSeg(generics_def_id, last)); 2106 } 2107 2108 // Case 2. Reference to a variant constructor. 2109 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => { 2110 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap()); 2111 let (generics_def_id, index) = if let Some(adt_def) = adt_def { 2112 debug_assert!(adt_def.is_enum()); 2113 (adt_def.did, last) 2114 } else if last >= 1 && segments[last - 1].args.is_some() { 2115 // Everything but the penultimate segment should have no 2116 // parameters at all. 2117 let mut def_id = def_id; 2118 2119 // `DefKind::Ctor` -> `DefKind::Variant` 2120 if let DefKind::Ctor(..) = kind { 2121 def_id = tcx.parent(def_id).unwrap() 2122 } 2123 2124 // `DefKind::Variant` -> `DefKind::Enum` 2125 let enum_def_id = tcx.parent(def_id).unwrap(); 2126 (enum_def_id, last - 1) 2127 } else { 2128 // FIXME: lint here recommending `Enum::<...>::Variant` form 2129 // instead of `Enum::Variant::<...>` form. 2130 2131 // Everything but the final segment should have no 2132 // parameters at all. 2133 let generics = tcx.generics_of(def_id); 2134 // Variant and struct constructors use the 2135 // generics of their parent type definition. 2136 (generics.parent.unwrap_or(def_id), last) 2137 }; 2138 path_segs.push(PathSeg(generics_def_id, index)); 2139 } 2140 2141 // Case 3. Reference to a top-level value. 2142 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => { 2143 path_segs.push(PathSeg(def_id, last)); 2144 } 2145 2146 // Case 4. Reference to a method or associated const. 2147 DefKind::AssocFn | DefKind::AssocConst => { 2148 if segments.len() >= 2 { 2149 let generics = tcx.generics_of(def_id); 2150 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1)); 2151 } 2152 path_segs.push(PathSeg(def_id, last)); 2153 } 2154 2155 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), 2156 } 2157 2158 debug!("path_segs = {:?}", path_segs); 2159 2160 path_segs 2161 } 2162 2163 // Check a type `Path` and convert it to a `Ty`. res_to_ty( &self, opt_self_ty: Option<Ty<'tcx>>, path: &hir::Path<'_>, permit_variants: bool, ) -> Ty<'tcx>2164 pub fn res_to_ty( 2165 &self, 2166 opt_self_ty: Option<Ty<'tcx>>, 2167 path: &hir::Path<'_>, 2168 permit_variants: bool, 2169 ) -> Ty<'tcx> { 2170 let tcx = self.tcx(); 2171 2172 debug!( 2173 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})", 2174 path.res, opt_self_ty, path.segments 2175 ); 2176 2177 let span = path.span; 2178 match path.res { 2179 Res::Def(DefKind::OpaqueTy, did) => { 2180 // Check for desugared `impl Trait`. 2181 assert!(ty::is_impl_trait_defn(tcx, did).is_none()); 2182 let item_segment = path.segments.split_last().unwrap(); 2183 self.prohibit_generics(item_segment.1); 2184 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0); 2185 self.normalize_ty(span, tcx.mk_opaque(did, substs)) 2186 } 2187 Res::Def( 2188 DefKind::Enum 2189 | DefKind::TyAlias 2190 | DefKind::Struct 2191 | DefKind::Union 2192 | DefKind::ForeignTy, 2193 did, 2194 ) => { 2195 assert_eq!(opt_self_ty, None); 2196 self.prohibit_generics(path.segments.split_last().unwrap().1); 2197 self.ast_path_to_ty(span, did, path.segments.last().unwrap()) 2198 } 2199 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => { 2200 // Convert "variant type" as if it were a real type. 2201 // The resulting `Ty` is type of the variant's enum for now. 2202 assert_eq!(opt_self_ty, None); 2203 2204 let path_segs = 2205 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id); 2206 let generic_segs: FxHashSet<_> = 2207 path_segs.iter().map(|PathSeg(_, index)| index).collect(); 2208 self.prohibit_generics(path.segments.iter().enumerate().filter_map( 2209 |(index, seg)| { 2210 if !generic_segs.contains(&index) { Some(seg) } else { None } 2211 }, 2212 )); 2213 2214 let PathSeg(def_id, index) = path_segs.last().unwrap(); 2215 self.ast_path_to_ty(span, *def_id, &path.segments[*index]) 2216 } 2217 Res::Def(DefKind::TyParam, def_id) => { 2218 assert_eq!(opt_self_ty, None); 2219 self.prohibit_generics(path.segments); 2220 2221 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); 2222 let item_id = tcx.hir().get_parent_node(hir_id); 2223 let item_def_id = tcx.hir().local_def_id(item_id); 2224 let generics = tcx.generics_of(item_def_id); 2225 let index = generics.param_def_id_to_index[&def_id]; 2226 tcx.mk_ty_param(index, tcx.hir().name(hir_id)) 2227 } 2228 Res::SelfTy(Some(_), None) => { 2229 // `Self` in trait or type alias. 2230 assert_eq!(opt_self_ty, None); 2231 self.prohibit_generics(path.segments); 2232 tcx.types.self_param 2233 } 2234 Res::SelfTy(_, Some((def_id, forbid_generic))) => { 2235 // `Self` in impl (we know the concrete type). 2236 assert_eq!(opt_self_ty, None); 2237 self.prohibit_generics(path.segments); 2238 // Try to evaluate any array length constants. 2239 let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id)); 2240 if forbid_generic && normalized_ty.definitely_needs_subst(tcx) { 2241 let mut err = tcx.sess.struct_span_err( 2242 path.span, 2243 "generic `Self` types are currently not permitted in anonymous constants", 2244 ); 2245 if let Some(hir::Node::Item(&hir::Item { 2246 kind: hir::ItemKind::Impl(ref impl_), 2247 .. 2248 })) = tcx.hir().get_if_local(def_id) 2249 { 2250 err.span_note(impl_.self_ty.span, "not a concrete type"); 2251 } 2252 err.emit(); 2253 tcx.ty_error() 2254 } else { 2255 normalized_ty 2256 } 2257 } 2258 Res::Def(DefKind::AssocTy, def_id) => { 2259 debug_assert!(path.segments.len() >= 2); 2260 self.prohibit_generics(&path.segments[..path.segments.len() - 2]); 2261 self.qpath_to_ty( 2262 span, 2263 opt_self_ty, 2264 def_id, 2265 &path.segments[path.segments.len() - 2], 2266 path.segments.last().unwrap(), 2267 ) 2268 } 2269 Res::PrimTy(prim_ty) => { 2270 assert_eq!(opt_self_ty, None); 2271 self.prohibit_generics(path.segments); 2272 match prim_ty { 2273 hir::PrimTy::Bool => tcx.types.bool, 2274 hir::PrimTy::Char => tcx.types.char, 2275 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)), 2276 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)), 2277 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)), 2278 hir::PrimTy::Str => tcx.types.str_, 2279 } 2280 } 2281 Res::Err => { 2282 self.set_tainted_by_errors(); 2283 self.tcx().ty_error() 2284 } 2285 _ => span_bug!(span, "unexpected resolution: {:?}", path.res), 2286 } 2287 } 2288 2289 /// Parses the programmer's textual representation of a type into our 2290 /// internal notion of a type. ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx>2291 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> { 2292 self.ast_ty_to_ty_inner(ast_ty, false) 2293 } 2294 2295 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait 2296 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors. 2297 #[tracing::instrument(level = "debug", skip(self))] ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx>2298 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> { 2299 let tcx = self.tcx(); 2300 2301 let result_ty = match ast_ty.kind { 2302 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)), 2303 hir::TyKind::Ptr(ref mt) => { 2304 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl }) 2305 } 2306 hir::TyKind::Rptr(ref region, ref mt) => { 2307 let r = self.ast_region_to_region(region, None); 2308 debug!(?r); 2309 let t = self.ast_ty_to_ty_inner(mt.ty, true); 2310 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl }) 2311 } 2312 hir::TyKind::Never => tcx.types.never, 2313 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))), 2314 hir::TyKind::BareFn(bf) => { 2315 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span); 2316 2317 tcx.mk_fn_ptr(self.ty_of_fn( 2318 ast_ty.hir_id, 2319 bf.unsafety, 2320 bf.abi, 2321 bf.decl, 2322 &hir::Generics::empty(), 2323 None, 2324 Some(ast_ty), 2325 )) 2326 } 2327 hir::TyKind::TraitObject(bounds, ref lifetime, _) => { 2328 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed) 2329 } 2330 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => { 2331 debug!(?maybe_qself, ?path); 2332 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself)); 2333 self.res_to_ty(opt_self_ty, path, false) 2334 } 2335 hir::TyKind::OpaqueDef(item_id, lifetimes) => { 2336 let opaque_ty = tcx.hir().item(item_id); 2337 let def_id = item_id.def_id.to_def_id(); 2338 2339 match opaque_ty.kind { 2340 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => { 2341 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some()) 2342 } 2343 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), 2344 } 2345 } 2346 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => { 2347 debug!(?qself, ?segment); 2348 let ty = self.ast_ty_to_ty(qself); 2349 2350 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = qself.kind { 2351 path.res 2352 } else { 2353 Res::Err 2354 }; 2355 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false) 2356 .map(|(ty, _, _)| ty) 2357 .unwrap_or_else(|_| tcx.ty_error()) 2358 } 2359 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => { 2360 let def_id = tcx.require_lang_item(lang_item, Some(span)); 2361 let (substs, _) = self.create_substs_for_ast_path( 2362 span, 2363 def_id, 2364 &[], 2365 &hir::PathSegment::invalid(), 2366 &GenericArgs::none(), 2367 true, 2368 None, 2369 ); 2370 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs)) 2371 } 2372 hir::TyKind::Array(ref ty, ref length) => { 2373 let length_def_id = tcx.hir().local_def_id(length.hir_id); 2374 let length = ty::Const::from_anon_const(tcx, length_def_id); 2375 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length)); 2376 self.normalize_ty(ast_ty.span, array_ty) 2377 } 2378 hir::TyKind::Typeof(ref e) => { 2379 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span }); 2380 tcx.type_of(tcx.hir().local_def_id(e.hir_id)) 2381 } 2382 hir::TyKind::Infer => { 2383 // Infer also appears as the type of arguments or return 2384 // values in an ExprKind::Closure, or as 2385 // the type of local variables. Both of these cases are 2386 // handled specially and will not descend into this routine. 2387 self.ty_infer(None, ast_ty.span) 2388 } 2389 hir::TyKind::Err => tcx.ty_error(), 2390 }; 2391 2392 debug!(?result_ty); 2393 2394 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span); 2395 result_ty 2396 } 2397 impl_trait_ty_to_ty( &self, def_id: DefId, lifetimes: &[hir::GenericArg<'_>], replace_parent_lifetimes: bool, ) -> Ty<'tcx>2398 fn impl_trait_ty_to_ty( 2399 &self, 2400 def_id: DefId, 2401 lifetimes: &[hir::GenericArg<'_>], 2402 replace_parent_lifetimes: bool, 2403 ) -> Ty<'tcx> { 2404 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes); 2405 let tcx = self.tcx(); 2406 2407 let generics = tcx.generics_of(def_id); 2408 2409 debug!("impl_trait_ty_to_ty: generics={:?}", generics); 2410 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| { 2411 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) { 2412 // Our own parameters are the resolved lifetimes. 2413 if let GenericParamDefKind::Lifetime = param.kind { 2414 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] { 2415 self.ast_region_to_region(lifetime, None).into() 2416 } else { 2417 bug!() 2418 } 2419 } else { 2420 bug!() 2421 } 2422 } else { 2423 match param.kind { 2424 // For RPIT (return position impl trait), only lifetimes 2425 // mentioned in the impl Trait predicate are captured by 2426 // the opaque type, so the lifetime parameters from the 2427 // parent item need to be replaced with `'static`. 2428 // 2429 // For `impl Trait` in the types of statics, constants, 2430 // locals and type aliases. These capture all parent 2431 // lifetimes, so they can use their identity subst. 2432 GenericParamDefKind::Lifetime if replace_parent_lifetimes => { 2433 tcx.lifetimes.re_static.into() 2434 } 2435 _ => tcx.mk_param_from_def(param), 2436 } 2437 } 2438 }); 2439 debug!("impl_trait_ty_to_ty: substs={:?}", substs); 2440 2441 let ty = tcx.mk_opaque(def_id, substs); 2442 debug!("impl_trait_ty_to_ty: {}", ty); 2443 ty 2444 } 2445 ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx>2446 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> { 2447 match ty.kind { 2448 hir::TyKind::Infer if expected_ty.is_some() => { 2449 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span); 2450 expected_ty.unwrap() 2451 } 2452 _ => self.ast_ty_to_ty(ty), 2453 } 2454 } 2455 ty_of_fn( &self, hir_id: hir::HirId, unsafety: hir::Unsafety, abi: abi::Abi, decl: &hir::FnDecl<'_>, generics: &hir::Generics<'_>, ident_span: Option<Span>, hir_ty: Option<&hir::Ty<'_>>, ) -> ty::PolyFnSig<'tcx>2456 pub fn ty_of_fn( 2457 &self, 2458 hir_id: hir::HirId, 2459 unsafety: hir::Unsafety, 2460 abi: abi::Abi, 2461 decl: &hir::FnDecl<'_>, 2462 generics: &hir::Generics<'_>, 2463 ident_span: Option<Span>, 2464 hir_ty: Option<&hir::Ty<'_>>, 2465 ) -> ty::PolyFnSig<'tcx> { 2466 debug!("ty_of_fn"); 2467 2468 let tcx = self.tcx(); 2469 let bound_vars = tcx.late_bound_vars(hir_id); 2470 debug!(?bound_vars); 2471 2472 // We proactively collect all the inferred type params to emit a single error per fn def. 2473 let mut visitor = PlaceholderHirTyCollector::default(); 2474 for ty in decl.inputs { 2475 visitor.visit_ty(ty); 2476 } 2477 walk_generics(&mut visitor, generics); 2478 2479 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None)); 2480 let output_ty = match decl.output { 2481 hir::FnRetTy::Return(output) => { 2482 visitor.visit_ty(output); 2483 self.ast_ty_to_ty(output) 2484 } 2485 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(), 2486 }; 2487 2488 debug!("ty_of_fn: output_ty={:?}", output_ty); 2489 2490 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi); 2491 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars); 2492 2493 if !self.allow_ty_infer() { 2494 // We always collect the spans for placeholder types when evaluating `fn`s, but we 2495 // only want to emit an error complaining about them if infer types (`_`) are not 2496 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of 2497 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`. 2498 2499 crate::collect::placeholder_type_error( 2500 tcx, 2501 ident_span.map(|sp| sp.shrink_to_hi()), 2502 generics.params, 2503 visitor.0, 2504 true, 2505 hir_ty, 2506 "function", 2507 ); 2508 } 2509 2510 // Find any late-bound regions declared in return type that do 2511 // not appear in the arguments. These are not well-formed. 2512 // 2513 // Example: 2514 // for<'a> fn() -> &'a str <-- 'a is bad 2515 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok 2516 let inputs = bare_fn_ty.inputs(); 2517 let late_bound_in_args = 2518 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned())); 2519 let output = bare_fn_ty.output(); 2520 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output); 2521 2522 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| { 2523 struct_span_err!( 2524 tcx.sess, 2525 decl.output.span(), 2526 E0581, 2527 "return type references {}, which is not constrained by the fn input types", 2528 br_name 2529 ) 2530 }); 2531 2532 bare_fn_ty 2533 } 2534 validate_late_bound_regions( &self, constrained_regions: FxHashSet<ty::BoundRegionKind>, referenced_regions: FxHashSet<ty::BoundRegionKind>, generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>, )2535 fn validate_late_bound_regions( 2536 &self, 2537 constrained_regions: FxHashSet<ty::BoundRegionKind>, 2538 referenced_regions: FxHashSet<ty::BoundRegionKind>, 2539 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>, 2540 ) { 2541 for br in referenced_regions.difference(&constrained_regions) { 2542 let br_name = match *br { 2543 ty::BrNamed(_, name) => format!("lifetime `{}`", name), 2544 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(), 2545 }; 2546 2547 let mut err = generate_err(&br_name); 2548 2549 if let ty::BrAnon(_) = *br { 2550 // The only way for an anonymous lifetime to wind up 2551 // in the return type but **also** be unconstrained is 2552 // if it only appears in "associated types" in the 2553 // input. See #47511 and #62200 for examples. In this case, 2554 // though we can easily give a hint that ought to be 2555 // relevant. 2556 err.note( 2557 "lifetimes appearing in an associated type are not considered constrained", 2558 ); 2559 } 2560 2561 err.emit(); 2562 } 2563 } 2564 2565 /// Given the bounds on an object, determines what single region bound (if any) we can 2566 /// use to summarize this type. The basic idea is that we will use the bound the user 2567 /// provided, if they provided one, and otherwise search the supertypes of trait bounds 2568 /// for region bounds. It may be that we can derive no bound at all, in which case 2569 /// we return `None`. compute_object_lifetime_bound( &self, span: Span, existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, ) -> Option<ty::Region<'tcx>>2570 fn compute_object_lifetime_bound( 2571 &self, 2572 span: Span, 2573 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>, 2574 ) -> Option<ty::Region<'tcx>> // if None, use the default 2575 { 2576 let tcx = self.tcx(); 2577 2578 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates); 2579 2580 // No explicit region bound specified. Therefore, examine trait 2581 // bounds and see if we can derive region bounds from those. 2582 let derived_region_bounds = object_region_bounds(tcx, existential_predicates); 2583 2584 // If there are no derived region bounds, then report back that we 2585 // can find no region bound. The caller will use the default. 2586 if derived_region_bounds.is_empty() { 2587 return None; 2588 } 2589 2590 // If any of the derived region bounds are 'static, that is always 2591 // the best choice. 2592 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) { 2593 return Some(tcx.lifetimes.re_static); 2594 } 2595 2596 // Determine whether there is exactly one unique region in the set 2597 // of derived region bounds. If so, use that. Otherwise, report an 2598 // error. 2599 let r = derived_region_bounds[0]; 2600 if derived_region_bounds[1..].iter().any(|r1| r != *r1) { 2601 tcx.sess.emit_err(AmbiguousLifetimeBound { span }); 2602 } 2603 Some(r) 2604 } 2605 } 2606