1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works. 2 //! 3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html 4 5 pub mod query; 6 pub mod select; 7 pub mod solve; 8 pub mod specialization_graph; 9 mod structural_impls; 10 pub mod util; 11 12 use crate::infer::canonical::Canonical; 13 use crate::mir::ConstraintCategory; 14 use crate::ty::abstract_const::NotConstEvaluatable; 15 use crate::ty::subst::SubstsRef; 16 use crate::ty::{self, AdtKind, Ty, TyCtxt}; 17 18 use rustc_data_structures::sync::Lrc; 19 use rustc_errors::{Applicability, Diagnostic}; 20 use rustc_hir as hir; 21 use rustc_hir::def_id::DefId; 22 use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; 23 use rustc_span::symbol::Symbol; 24 use rustc_span::{Span, DUMMY_SP}; 25 use smallvec::SmallVec; 26 27 use std::borrow::Cow; 28 use std::hash::{Hash, Hasher}; 29 30 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; 31 32 pub use self::ObligationCauseCode::*; 33 34 /// Depending on the stage of compilation, we want projection to be 35 /// more or less conservative. 36 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)] 37 pub enum Reveal { 38 /// At type-checking time, we refuse to project any associated 39 /// type that is marked `default`. Non-`default` ("final") types 40 /// are always projected. This is necessary in general for 41 /// soundness of specialization. However, we *could* allow 42 /// projections in fully-monomorphic cases. We choose not to, 43 /// because we prefer for `default type` to force the type 44 /// definition to be treated abstractly by any consumers of the 45 /// impl. Concretely, that means that the following example will 46 /// fail to compile: 47 /// 48 /// ```compile_fail,E0308 49 /// #![feature(specialization)] 50 /// trait Assoc { 51 /// type Output; 52 /// } 53 /// 54 /// impl<T> Assoc for T { 55 /// default type Output = bool; 56 /// } 57 /// 58 /// fn main() { 59 /// let x: <() as Assoc>::Output = true; 60 /// } 61 /// ``` 62 /// 63 /// We also do not reveal the hidden type of opaque types during 64 /// type-checking. 65 UserFacing, 66 67 /// At codegen time, all monomorphic projections will succeed. 68 /// Also, `impl Trait` is normalized to the concrete type, 69 /// which has to be already collected by type-checking. 70 /// 71 /// NOTE: as `impl Trait`'s concrete type should *never* 72 /// be observable directly by the user, `Reveal::All` 73 /// should not be used by checks which may expose 74 /// type equality or type contents to the user. 75 /// There are some exceptions, e.g., around auto traits and 76 /// transmute-checking, which expose some details, but 77 /// not the whole concrete type of the `impl Trait`. 78 All, 79 } 80 81 /// The reason why we incurred this obligation; used for error reporting. 82 /// 83 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the 84 /// best trade-off between keeping the type small (which makes copies cheaper) 85 /// while not doing too many heap allocations. 86 /// 87 /// We do not want to intern this as there are a lot of obligation causes which 88 /// only live for a short period of time. 89 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 90 #[derive(TypeVisitable, TypeFoldable)] 91 pub struct ObligationCause<'tcx> { 92 pub span: Span, 93 94 /// The ID of the fn body that triggered this obligation. This is 95 /// used for region obligations to determine the precise 96 /// environment in which the region obligation should be evaluated 97 /// (in particular, closures can add new assumptions). See the 98 /// field `region_obligations` of the `FulfillmentContext` for more 99 /// information. 100 pub body_id: LocalDefId, 101 102 code: InternedObligationCauseCode<'tcx>, 103 } 104 105 // This custom hash function speeds up hashing for `Obligation` deduplication 106 // greatly by skipping the `code` field, which can be large and complex. That 107 // shouldn't affect hash quality much since there are several other fields in 108 // `Obligation` which should be unique enough, especially the predicate itself 109 // which is hashed as an interned pointer. See #90996. 110 impl Hash for ObligationCause<'_> { hash<H: Hasher>(&self, state: &mut H)111 fn hash<H: Hasher>(&self, state: &mut H) { 112 self.body_id.hash(state); 113 self.span.hash(state); 114 } 115 } 116 117 impl<'tcx> ObligationCause<'tcx> { 118 #[inline] new( span: Span, body_id: LocalDefId, code: ObligationCauseCode<'tcx>, ) -> ObligationCause<'tcx>119 pub fn new( 120 span: Span, 121 body_id: LocalDefId, 122 code: ObligationCauseCode<'tcx>, 123 ) -> ObligationCause<'tcx> { 124 ObligationCause { span, body_id, code: code.into() } 125 } 126 misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx>127 pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> { 128 ObligationCause::new(span, body_id, MiscObligation) 129 } 130 131 #[inline(always)] dummy() -> ObligationCause<'tcx>132 pub fn dummy() -> ObligationCause<'tcx> { 133 ObligationCause::dummy_with_span(DUMMY_SP) 134 } 135 136 #[inline(always)] dummy_with_span(span: Span) -> ObligationCause<'tcx>137 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> { 138 ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() } 139 } 140 span(&self) -> Span141 pub fn span(&self) -> Span { 142 match *self.code() { 143 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { 144 arm_span, 145 .. 146 }) => arm_span, 147 _ => self.span, 148 } 149 } 150 151 #[inline] code(&self) -> &ObligationCauseCode<'tcx>152 pub fn code(&self) -> &ObligationCauseCode<'tcx> { 153 &self.code 154 } 155 map_code( &mut self, f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>, )156 pub fn map_code( 157 &mut self, 158 f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>, 159 ) { 160 self.code = f(std::mem::take(&mut self.code)).into(); 161 } 162 derived_cause( mut self, parent_trait_pred: ty::PolyTraitPredicate<'tcx>, variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>, ) -> ObligationCause<'tcx>163 pub fn derived_cause( 164 mut self, 165 parent_trait_pred: ty::PolyTraitPredicate<'tcx>, 166 variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>, 167 ) -> ObligationCause<'tcx> { 168 /*! 169 * Creates a cause for obligations that are derived from 170 * `obligation` by a recursive search (e.g., for a builtin 171 * bound, or eventually a `auto trait Foo`). If `obligation` 172 * is itself a derived obligation, this is just a clone, but 173 * otherwise we create a "derived obligation" cause so as to 174 * keep track of the original root obligation for error 175 * reporting. 176 */ 177 178 // NOTE(flaper87): As of now, it keeps track of the whole error 179 // chain. Ideally, we should have a way to configure this either 180 // by using -Z verbose or just a CLI argument. 181 self.code = 182 variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into(); 183 self 184 } 185 to_constraint_category(&self) -> ConstraintCategory<'tcx>186 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> { 187 match self.code() { 188 MatchImpl(cause, _) => cause.to_constraint_category(), 189 AscribeUserTypeProvePredicate(predicate_span) => { 190 ConstraintCategory::Predicate(*predicate_span) 191 } 192 _ => ConstraintCategory::BoringNoLocation, 193 } 194 } 195 } 196 197 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 198 #[derive(TypeVisitable, TypeFoldable)] 199 pub struct UnifyReceiverContext<'tcx> { 200 pub assoc_item: ty::AssocItem, 201 pub param_env: ty::ParamEnv<'tcx>, 202 pub substs: SubstsRef<'tcx>, 203 } 204 205 #[derive(Clone, PartialEq, Eq, Lift, Default, HashStable)] 206 #[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)] 207 pub struct InternedObligationCauseCode<'tcx> { 208 /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of 209 /// the time). `Some` otherwise. 210 code: Option<Lrc<ObligationCauseCode<'tcx>>>, 211 } 212 213 impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> { fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 215 let cause: &ObligationCauseCode<'_> = self; 216 cause.fmt(f) 217 } 218 } 219 220 impl<'tcx> ObligationCauseCode<'tcx> { 221 #[inline(always)] into(self) -> InternedObligationCauseCode<'tcx>222 fn into(self) -> InternedObligationCauseCode<'tcx> { 223 InternedObligationCauseCode { 224 code: if let ObligationCauseCode::MiscObligation = self { 225 None 226 } else { 227 Some(Lrc::new(self)) 228 }, 229 } 230 } 231 } 232 233 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> { 234 type Target = ObligationCauseCode<'tcx>; 235 deref(&self) -> &Self::Target236 fn deref(&self) -> &Self::Target { 237 self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation) 238 } 239 } 240 241 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 242 #[derive(TypeVisitable, TypeFoldable)] 243 pub enum ObligationCauseCode<'tcx> { 244 /// Not well classified or should be obvious from the span. 245 MiscObligation, 246 247 /// A slice or array is WF only if `T: Sized`. 248 SliceOrArrayElem, 249 250 /// A tuple is WF only if its middle elements are `Sized`. 251 TupleElem, 252 253 /// This is the trait reference from the given projection. 254 ProjectionWf(ty::AliasTy<'tcx>), 255 256 /// Must satisfy all of the where-clause predicates of the 257 /// given item. 258 ItemObligation(DefId), 259 260 /// Like `ItemObligation`, but carries the span of the 261 /// predicate when it can be identified. 262 BindingObligation(DefId, Span), 263 264 /// Like `ItemObligation`, but carries the `HirId` of the 265 /// expression that caused the obligation, and the `usize` 266 /// indicates exactly which predicate it is in the list of 267 /// instantiated predicates. 268 ExprItemObligation(DefId, rustc_hir::HirId, usize), 269 270 /// Combines `ExprItemObligation` and `BindingObligation`. 271 ExprBindingObligation(DefId, Span, rustc_hir::HirId, usize), 272 273 /// A type like `&'a T` is WF only if `T: 'a`. 274 ReferenceOutlivesReferent(Ty<'tcx>), 275 276 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`. 277 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>), 278 279 /// Obligation incurred due to a coercion. 280 Coercion { 281 source: Ty<'tcx>, 282 target: Ty<'tcx>, 283 }, 284 285 /// Various cases where expressions must be `Sized` / `Copy` / etc. 286 /// `L = X` implies that `L` is `Sized`. 287 AssignmentLhsSized, 288 /// `(x1, .., xn)` must be `Sized`. 289 TupleInitializerSized, 290 /// `S { ... }` must be `Sized`. 291 StructInitializerSized, 292 /// Type of each variable must be `Sized`. 293 VariableType(hir::HirId), 294 /// Argument type must be `Sized`. 295 SizedArgumentType(Option<Span>), 296 /// Return type must be `Sized`. 297 SizedReturnType, 298 /// Yield type must be `Sized`. 299 SizedYieldType, 300 /// Inline asm operand type must be `Sized`. 301 InlineAsmSized, 302 /// `[expr; N]` requires `type_of(expr): Copy`. 303 RepeatElementCopy { 304 /// If element is a `const fn` we display a help message suggesting to move the 305 /// function call to a new `const` item while saying that `T` doesn't implement `Copy`. 306 is_const_fn: bool, 307 }, 308 309 /// Types of fields (other than the last, except for packed structs) in a struct must be sized. 310 FieldSized { 311 adt_kind: AdtKind, 312 span: Span, 313 last: bool, 314 }, 315 316 /// Constant expressions must be sized. 317 ConstSized, 318 319 /// `static` items must have `Sync` type. 320 SharedStatic, 321 322 BuiltinDerivedObligation(DerivedObligationCause<'tcx>), 323 324 ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>), 325 326 DerivedObligation(DerivedObligationCause<'tcx>), 327 328 FunctionArgumentObligation { 329 /// The node of the relevant argument in the function call. 330 arg_hir_id: hir::HirId, 331 /// The node of the function call. 332 call_hir_id: hir::HirId, 333 /// The obligation introduced by this argument. 334 parent_code: InternedObligationCauseCode<'tcx>, 335 }, 336 337 /// Error derived when matching traits/impls; see ObligationCause for more details 338 CompareImplItemObligation { 339 impl_item_def_id: LocalDefId, 340 trait_item_def_id: DefId, 341 kind: ty::AssocKind, 342 }, 343 344 /// Checking that the bounds of a trait's associated type hold for a given impl 345 CheckAssociatedTypeBounds { 346 impl_item_def_id: LocalDefId, 347 trait_item_def_id: DefId, 348 }, 349 350 /// Checking that this expression can be assigned to its target. 351 ExprAssignable, 352 353 /// Computing common supertype in the arms of a match expression 354 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>), 355 356 /// Type error arising from type checking a pattern against an expected type. 357 Pattern { 358 /// The span of the scrutinee or type expression which caused the `root_ty` type. 359 span: Option<Span>, 360 /// The root expected type induced by a scrutinee or type expression. 361 root_ty: Ty<'tcx>, 362 /// Whether the `Span` came from an expression or a type expression. 363 origin_expr: bool, 364 }, 365 366 /// Constants in patterns must have `Structural` type. 367 ConstPatternStructural, 368 369 /// Computing common supertype in an if expression 370 IfExpression(Box<IfExpressionCause<'tcx>>), 371 372 /// Computing common supertype of an if expression with no else counter-part 373 IfExpressionWithNoElse, 374 375 /// `main` has wrong type 376 MainFunctionType, 377 378 /// `start` has wrong type 379 StartFunctionType, 380 381 /// Intrinsic has wrong type 382 IntrinsicType, 383 384 /// A let else block does not diverge 385 LetElse, 386 387 /// Method receiver 388 MethodReceiver, 389 390 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>), 391 392 /// `return` with no expression 393 ReturnNoExpression, 394 395 /// `return` with an expression 396 ReturnValue(hir::HirId), 397 398 /// Return type of this function 399 ReturnType, 400 401 /// Opaque return type of this function 402 OpaqueReturnType(Option<(Ty<'tcx>, Span)>), 403 404 /// Block implicit return 405 BlockTailExpression(hir::HirId), 406 407 /// #[feature(trivial_bounds)] is not enabled 408 TrivialBound, 409 410 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y` 411 OpaqueType, 412 413 AwaitableExpr(Option<hir::HirId>), 414 415 ForLoopIterator, 416 417 QuestionMark, 418 419 /// Well-formed checking. If a `WellFormedLoc` is provided, 420 /// then it will be used to perform HIR-based wf checking 421 /// after an error occurs, in order to generate a more precise error span. 422 /// This is purely for diagnostic purposes - it is always 423 /// correct to use `MiscObligation` instead, or to specify 424 /// `WellFormed(None)` 425 WellFormed(Option<WellFormedLoc>), 426 427 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against. 428 MatchImpl(ObligationCause<'tcx>, DefId), 429 430 BinOp { 431 rhs_span: Option<Span>, 432 is_lit: bool, 433 output_ty: Option<Ty<'tcx>>, 434 }, 435 436 AscribeUserTypeProvePredicate(Span), 437 438 RustCall, 439 440 /// Obligations to prove that a `std::ops::Drop` impl is not stronger than 441 /// the ADT it's being implemented for. 442 DropImpl, 443 444 /// Requirement for a `const N: Ty` to implement `Ty: ConstParamTy` 445 ConstParam(Ty<'tcx>), 446 447 /// Obligations emitted during the normalization of a weak type alias. 448 TypeAlias(InternedObligationCauseCode<'tcx>, Span, DefId), 449 } 450 451 /// The 'location' at which we try to perform HIR-based wf checking. 452 /// This information is used to obtain an `hir::Ty`, which 453 /// we can walk in order to obtain precise spans for any 454 /// 'nested' types (e.g. `Foo` in `Option<Foo>`). 455 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)] 456 #[derive(TypeVisitable, TypeFoldable)] 457 pub enum WellFormedLoc { 458 /// Use the type of the provided definition. 459 Ty(LocalDefId), 460 /// Use the type of the parameter of the provided function. 461 /// We cannot use `hir::Param`, since the function may 462 /// not have a body (e.g. a trait method definition) 463 Param { 464 /// The function to lookup the parameter in 465 function: LocalDefId, 466 /// The index of the parameter to use. 467 /// Parameters are indexed from 0, with the return type 468 /// being the last 'parameter' 469 param_idx: u16, 470 }, 471 } 472 473 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 474 #[derive(TypeVisitable, TypeFoldable)] 475 pub struct ImplDerivedObligationCause<'tcx> { 476 pub derived: DerivedObligationCause<'tcx>, 477 /// The `DefId` of the `impl` that gave rise to the `derived` obligation. 478 /// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic impl, 479 /// then this will be the `DefId` of that trait alias. Care should therefore be taken to handle 480 /// that exceptional case where appropriate. 481 pub impl_or_alias_def_id: DefId, 482 /// The index of the derived predicate in the parent impl's predicates. 483 pub impl_def_predicate_index: Option<usize>, 484 pub span: Span, 485 } 486 487 impl<'tcx> ObligationCauseCode<'tcx> { 488 /// Returns the base obligation, ignoring derived obligations. peel_derives(&self) -> &Self489 pub fn peel_derives(&self) -> &Self { 490 let mut base_cause = self; 491 while let Some((parent_code, _)) = base_cause.parent() { 492 base_cause = parent_code; 493 } 494 base_cause 495 } 496 parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)>497 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> { 498 match self { 499 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)), 500 BuiltinDerivedObligation(derived) 501 | DerivedObligation(derived) 502 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => { 503 Some((&derived.parent_code, Some(derived.parent_trait_pred))) 504 } 505 _ => None, 506 } 507 } 508 peel_match_impls(&self) -> &Self509 pub fn peel_match_impls(&self) -> &Self { 510 match self { 511 MatchImpl(cause, _) => cause.code(), 512 _ => self, 513 } 514 } 515 } 516 517 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger. 518 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] 519 static_assert_size!(ObligationCauseCode<'_>, 48); 520 521 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] 522 pub enum StatementAsExpression { 523 CorrectType, 524 NeedsBoxing, 525 } 526 527 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression { 528 type Lifted = StatementAsExpression; lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression>529 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> { 530 Some(self) 531 } 532 } 533 534 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 535 #[derive(TypeVisitable, TypeFoldable)] 536 pub struct MatchExpressionArmCause<'tcx> { 537 pub arm_block_id: Option<hir::HirId>, 538 pub arm_ty: Ty<'tcx>, 539 pub arm_span: Span, 540 pub prior_arm_block_id: Option<hir::HirId>, 541 pub prior_arm_ty: Ty<'tcx>, 542 pub prior_arm_span: Span, 543 pub scrut_span: Span, 544 pub source: hir::MatchSource, 545 pub prior_arms: Vec<Span>, 546 pub scrut_hir_id: hir::HirId, 547 pub opt_suggest_box_span: Option<Span>, 548 } 549 550 #[derive(Copy, Clone, Debug, PartialEq, Eq)] 551 #[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)] 552 pub struct IfExpressionCause<'tcx> { 553 pub then_id: hir::HirId, 554 pub else_id: hir::HirId, 555 pub then_ty: Ty<'tcx>, 556 pub else_ty: Ty<'tcx>, 557 pub outer_span: Option<Span>, 558 pub opt_suggest_box_span: Option<Span>, 559 } 560 561 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)] 562 #[derive(TypeVisitable, TypeFoldable)] 563 pub struct DerivedObligationCause<'tcx> { 564 /// The trait predicate of the parent obligation that led to the 565 /// current obligation. Note that only trait obligations lead to 566 /// derived obligations, so we just store the trait predicate here 567 /// directly. 568 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>, 569 570 /// The parent trait had this cause. 571 pub parent_code: InternedObligationCauseCode<'tcx>, 572 } 573 574 #[derive(Clone, Debug, TypeVisitable, Lift)] 575 pub enum SelectionError<'tcx> { 576 /// The trait is not implemented. 577 Unimplemented, 578 /// After a closure impl has selected, its "outputs" were evaluated 579 /// (which for closures includes the "input" type params) and they 580 /// didn't resolve. See `confirm_poly_trait_refs` for more. 581 OutputTypeParameterMismatch(Box<SelectionOutputTypeParameterMismatch<'tcx>>), 582 /// The trait pointed by `DefId` is not object safe. 583 TraitNotObjectSafe(DefId), 584 /// A given constant couldn't be evaluated. 585 NotConstEvaluatable(NotConstEvaluatable), 586 /// Exceeded the recursion depth during type projection. 587 Overflow(OverflowError), 588 /// Signaling that an error has already been emitted, to avoid 589 /// multiple errors being shown. 590 ErrorReporting, 591 /// Computing an opaque type's hidden type caused an error (e.g. a cycle error). 592 /// We can thus not know whether the hidden type implements an auto trait, so 593 /// we should not presume anything about it. 594 OpaqueTypeAutoTraitLeakageUnknown(DefId), 595 } 596 597 #[derive(Clone, Debug, TypeVisitable, Lift)] 598 pub struct SelectionOutputTypeParameterMismatch<'tcx> { 599 pub found_trait_ref: ty::PolyTraitRef<'tcx>, 600 pub expected_trait_ref: ty::PolyTraitRef<'tcx>, 601 pub terr: ty::error::TypeError<'tcx>, 602 } 603 604 /// When performing resolution, it is typically the case that there 605 /// can be one of three outcomes: 606 /// 607 /// - `Ok(Some(r))`: success occurred with result `r` 608 /// - `Ok(None)`: could not definitely determine anything, usually due 609 /// to inconclusive type inference. 610 /// - `Err(e)`: error `e` occurred 611 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>; 612 613 /// Given the successful resolution of an obligation, the `ImplSource` 614 /// indicates where the impl comes from. 615 /// 616 /// For example, the obligation may be satisfied by a specific impl (case A), 617 /// or it may be relative to some bound that is in scope (case B). 618 /// 619 /// ```ignore (illustrative) 620 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1 621 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2 622 /// impl Clone for i32 { ... } // Impl_3 623 /// 624 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) { 625 /// // Case A: ImplSource points at a specific impl. Only possible when 626 /// // type is concretely known. If the impl itself has bounded 627 /// // type parameters, ImplSource will carry resolutions for those as well: 628 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])]) 629 /// 630 /// // Case B: ImplSource must be provided by caller. This applies when 631 /// // type is a type parameter. 632 /// param.clone(); // ImplSource::Param 633 /// 634 /// // Case C: A mix of cases A and B. 635 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param]) 636 /// } 637 /// ``` 638 /// 639 /// ### The type parameter `N` 640 /// 641 /// See explanation on `ImplSourceUserDefinedData`. 642 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)] 643 #[derive(TypeFoldable, TypeVisitable)] 644 pub enum ImplSource<'tcx, N> { 645 /// ImplSource identifying a particular impl. 646 UserDefined(ImplSourceUserDefinedData<'tcx, N>), 647 648 /// Successful resolution to an obligation provided by the caller 649 /// for some type parameter. The `Vec<N>` represents the 650 /// obligations incurred from normalizing the where-clause (if 651 /// any). 652 Param(Vec<N>, ty::BoundConstness), 653 654 /// Virtual calls through an object. 655 Object(ImplSourceObjectData<N>), 656 657 /// Successful resolution for a builtin trait. 658 Builtin(Vec<N>), 659 660 /// ImplSource for trait upcasting coercion 661 TraitUpcasting(ImplSourceTraitUpcastingData<N>), 662 } 663 664 impl<'tcx, N> ImplSource<'tcx, N> { nested_obligations(self) -> Vec<N>665 pub fn nested_obligations(self) -> Vec<N> { 666 match self { 667 ImplSource::UserDefined(i) => i.nested, 668 ImplSource::Param(n, _) | ImplSource::Builtin(n) => n, 669 ImplSource::Object(d) => d.nested, 670 ImplSource::TraitUpcasting(d) => d.nested, 671 } 672 } 673 borrow_nested_obligations(&self) -> &[N]674 pub fn borrow_nested_obligations(&self) -> &[N] { 675 match self { 676 ImplSource::UserDefined(i) => &i.nested, 677 ImplSource::Param(n, _) | ImplSource::Builtin(n) => &n, 678 ImplSource::Object(d) => &d.nested, 679 ImplSource::TraitUpcasting(d) => &d.nested, 680 } 681 } 682 borrow_nested_obligations_mut(&mut self) -> &mut [N]683 pub fn borrow_nested_obligations_mut(&mut self) -> &mut [N] { 684 match self { 685 ImplSource::UserDefined(i) => &mut i.nested, 686 ImplSource::Param(n, _) | ImplSource::Builtin(n) => n, 687 ImplSource::Object(d) => &mut d.nested, 688 ImplSource::TraitUpcasting(d) => &mut d.nested, 689 } 690 } 691 map<M, F>(self, f: F) -> ImplSource<'tcx, M> where F: FnMut(N) -> M,692 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M> 693 where 694 F: FnMut(N) -> M, 695 { 696 match self { 697 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData { 698 impl_def_id: i.impl_def_id, 699 substs: i.substs, 700 nested: i.nested.into_iter().map(f).collect(), 701 }), 702 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct), 703 ImplSource::Builtin(n) => ImplSource::Builtin(n.into_iter().map(f).collect()), 704 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData { 705 vtable_base: o.vtable_base, 706 nested: o.nested.into_iter().map(f).collect(), 707 }), 708 ImplSource::TraitUpcasting(d) => { 709 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData { 710 vtable_vptr_slot: d.vtable_vptr_slot, 711 nested: d.nested.into_iter().map(f).collect(), 712 }) 713 } 714 } 715 } 716 } 717 718 /// Identifies a particular impl in the source, along with a set of 719 /// substitutions from the impl's type/lifetime parameters. The 720 /// `nested` vector corresponds to the nested obligations attached to 721 /// the impl's type parameters. 722 /// 723 /// The type parameter `N` indicates the type used for "nested 724 /// obligations" that are required by the impl. During type-check, this 725 /// is `Obligation`, as one might expect. During codegen, however, this 726 /// is `()`, because codegen only requires a shallow resolution of an 727 /// impl, and nested obligations are satisfied later. 728 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)] 729 #[derive(TypeFoldable, TypeVisitable)] 730 pub struct ImplSourceUserDefinedData<'tcx, N> { 731 pub impl_def_id: DefId, 732 pub substs: SubstsRef<'tcx>, 733 pub nested: Vec<N>, 734 } 735 736 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)] 737 #[derive(TypeFoldable, TypeVisitable)] 738 pub struct ImplSourceTraitUpcastingData<N> { 739 /// The vtable is formed by concatenating together the method lists of 740 /// the base object trait and all supertraits, pointers to supertrait vtable will 741 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable 742 /// within that vtable. 743 pub vtable_vptr_slot: Option<usize>, 744 745 pub nested: Vec<N>, 746 } 747 748 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)] 749 #[derive(TypeFoldable, TypeVisitable)] 750 pub struct ImplSourceObjectData<N> { 751 /// The vtable is formed by concatenating together the method lists of 752 /// the base object trait and all supertraits, pointers to supertrait vtable will 753 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods 754 /// in that vtable. 755 pub vtable_base: usize, 756 757 pub nested: Vec<N>, 758 } 759 760 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)] 761 pub enum ObjectSafetyViolation { 762 /// `Self: Sized` declared on the trait. 763 SizedSelf(SmallVec<[Span; 1]>), 764 765 /// Supertrait reference references `Self` an in illegal location 766 /// (e.g., `trait Foo : Bar<Self>`). 767 SupertraitSelf(SmallVec<[Span; 1]>), 768 769 // Supertrait has a non-lifetime `for<T>` binder. 770 SupertraitNonLifetimeBinder(SmallVec<[Span; 1]>), 771 772 /// Method has something illegal. 773 Method(Symbol, MethodViolationCode, Span), 774 775 /// Associated const. 776 AssocConst(Symbol, Span), 777 778 /// GAT 779 GAT(Symbol, Span), 780 } 781 782 impl ObjectSafetyViolation { error_msg(&self) -> Cow<'static, str>783 pub fn error_msg(&self) -> Cow<'static, str> { 784 match self { 785 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(), 786 ObjectSafetyViolation::SupertraitSelf(ref spans) => { 787 if spans.iter().any(|sp| *sp != DUMMY_SP) { 788 "it uses `Self` as a type parameter".into() 789 } else { 790 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause" 791 .into() 792 } 793 } 794 ObjectSafetyViolation::SupertraitNonLifetimeBinder(_) => { 795 "where clause cannot reference non-lifetime `for<...>` variables".into() 796 } 797 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => { 798 format!("associated function `{}` has no `self` parameter", name).into() 799 } 800 ObjectSafetyViolation::Method( 801 name, 802 MethodViolationCode::ReferencesSelfInput(_), 803 DUMMY_SP, 804 ) => format!("method `{}` references the `Self` type in its parameters", name).into(), 805 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => { 806 format!("method `{}` references the `Self` type in this parameter", name).into() 807 } 808 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => { 809 format!("method `{}` references the `Self` type in its return type", name).into() 810 } 811 ObjectSafetyViolation::Method( 812 name, 813 MethodViolationCode::ReferencesImplTraitInTrait(_), 814 _, 815 ) => format!("method `{}` references an `impl Trait` type in its return type", name) 816 .into(), 817 ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => { 818 format!("method `{}` is `async`", name).into() 819 } 820 ObjectSafetyViolation::Method( 821 name, 822 MethodViolationCode::WhereClauseReferencesSelf, 823 _, 824 ) => { 825 format!("method `{}` references the `Self` type in its `where` clause", name).into() 826 } 827 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => { 828 format!("method `{}` has generic type parameters", name).into() 829 } 830 ObjectSafetyViolation::Method( 831 name, 832 MethodViolationCode::UndispatchableReceiver(_), 833 _, 834 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(), 835 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => { 836 format!("it contains associated `const` `{}`", name).into() 837 } 838 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(), 839 ObjectSafetyViolation::GAT(name, _) => { 840 format!("it contains the generic associated type `{}`", name).into() 841 } 842 } 843 } 844 solution(&self, err: &mut Diagnostic)845 pub fn solution(&self, err: &mut Diagnostic) { 846 match self { 847 ObjectSafetyViolation::SizedSelf(_) 848 | ObjectSafetyViolation::SupertraitSelf(_) 849 | ObjectSafetyViolation::SupertraitNonLifetimeBinder(..) => {} 850 ObjectSafetyViolation::Method( 851 name, 852 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))), 853 _, 854 ) => { 855 err.span_suggestion( 856 add_self_sugg.1, 857 format!( 858 "consider turning `{}` into a method by giving it a `&self` argument", 859 name 860 ), 861 add_self_sugg.0.to_string(), 862 Applicability::MaybeIncorrect, 863 ); 864 err.span_suggestion( 865 make_sized_sugg.1, 866 format!( 867 "alternatively, consider constraining `{}` so it does not apply to \ 868 trait objects", 869 name 870 ), 871 make_sized_sugg.0.to_string(), 872 Applicability::MaybeIncorrect, 873 ); 874 } 875 ObjectSafetyViolation::Method( 876 name, 877 MethodViolationCode::UndispatchableReceiver(Some(span)), 878 _, 879 ) => { 880 err.span_suggestion( 881 *span, 882 format!("consider changing method `{}`'s `self` parameter to be `&self`", name), 883 "&Self", 884 Applicability::MachineApplicable, 885 ); 886 } 887 ObjectSafetyViolation::AssocConst(name, _) 888 | ObjectSafetyViolation::GAT(name, _) 889 | ObjectSafetyViolation::Method(name, ..) => { 890 err.help(format!("consider moving `{}` to another trait", name)); 891 } 892 } 893 } 894 spans(&self) -> SmallVec<[Span; 1]>895 pub fn spans(&self) -> SmallVec<[Span; 1]> { 896 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so 897 // diagnostics use a `note` instead of a `span_label`. 898 match self { 899 ObjectSafetyViolation::SupertraitSelf(spans) 900 | ObjectSafetyViolation::SizedSelf(spans) 901 | ObjectSafetyViolation::SupertraitNonLifetimeBinder(spans) => spans.clone(), 902 ObjectSafetyViolation::AssocConst(_, span) 903 | ObjectSafetyViolation::GAT(_, span) 904 | ObjectSafetyViolation::Method(_, _, span) 905 if *span != DUMMY_SP => 906 { 907 smallvec![*span] 908 } 909 _ => smallvec![], 910 } 911 } 912 } 913 914 /// Reasons a method might not be object-safe. 915 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)] 916 pub enum MethodViolationCode { 917 /// e.g., `fn foo()` 918 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>), 919 920 /// e.g., `fn foo(&self, x: Self)` 921 ReferencesSelfInput(Option<Span>), 922 923 /// e.g., `fn foo(&self) -> Self` 924 ReferencesSelfOutput, 925 926 /// e.g., `fn foo(&self) -> impl Sized` 927 ReferencesImplTraitInTrait(Span), 928 929 /// e.g., `async fn foo(&self)` 930 AsyncFn, 931 932 /// e.g., `fn foo(&self) where Self: Clone` 933 WhereClauseReferencesSelf, 934 935 /// e.g., `fn foo<A>()` 936 Generic, 937 938 /// the method's receiver (`self` argument) can't be dispatched on 939 UndispatchableReceiver(Option<Span>), 940 } 941 942 /// These are the error cases for `codegen_select_candidate`. 943 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)] 944 pub enum CodegenObligationError { 945 /// Ambiguity can happen when monomorphizing during trans 946 /// expands to some humongous type that never occurred 947 /// statically -- this humongous type can then overflow, 948 /// leading to an ambiguous result. So report this as an 949 /// overflow bug, since I believe this is the only case 950 /// where ambiguity can result. 951 Ambiguity, 952 /// This can trigger when we probe for the source of a `'static` lifetime requirement 953 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound. 954 /// This can also trigger when we have a global bound that is not actually satisfied, 955 /// but was included during typeck due to the trivial_bounds feature. 956 Unimplemented, 957 FulfillmentError, 958 } 959 960 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, HashStable, TypeFoldable, TypeVisitable)] 961 pub enum DefiningAnchor { 962 /// `DefId` of the item. 963 Bind(LocalDefId), 964 /// When opaque types are not resolved, we `Bubble` up, meaning 965 /// return the opaque/hidden type pair from query, for caller of query to handle it. 966 Bubble, 967 /// Used to catch type mismatch errors when handling opaque types. 968 Error, 969 } 970