1 use crate::callee::{self, DeferredCallResolution}; 2 use crate::errors::CtorIsPrivate; 3 use crate::method::{self, MethodCallee, SelfSource}; 4 use crate::rvalue_scopes; 5 use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, RawTy}; 6 use rustc_data_structures::captures::Captures; 7 use rustc_data_structures::fx::FxHashSet; 8 use rustc_errors::{Applicability, Diagnostic, ErrorGuaranteed, MultiSpan, StashKey}; 9 use rustc_hir as hir; 10 use rustc_hir::def::{CtorOf, DefKind, Res}; 11 use rustc_hir::def_id::DefId; 12 use rustc_hir::lang_items::LangItem; 13 use rustc_hir::{ExprKind, GenericArg, Node, QPath}; 14 use rustc_hir_analysis::astconv::generics::{ 15 check_generic_arg_count_for_call, create_substs_for_generic_args, 16 }; 17 use rustc_hir_analysis::astconv::{ 18 AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, 19 GenericArgCountResult, IsMethodCall, PathSeg, 20 }; 21 use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; 22 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; 23 use rustc_infer::infer::{DefineOpaqueTypes, InferResult}; 24 use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability}; 25 use rustc_middle::ty::error::TypeError; 26 use rustc_middle::ty::fold::TypeFoldable; 27 use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; 28 use rustc_middle::ty::{ 29 self, AdtKind, CanonicalUserType, GenericParamDefKind, Ty, TyCtxt, UserType, 30 }; 31 use rustc_middle::ty::{GenericArgKind, SubstsRef, UserSelfTy, UserSubsts}; 32 use rustc_session::lint; 33 use rustc_span::def_id::LocalDefId; 34 use rustc_span::hygiene::DesugaringKind; 35 use rustc_span::symbol::{kw, sym, Ident}; 36 use rustc_span::Span; 37 use rustc_target::abi::FieldIdx; 38 use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; 39 use rustc_trait_selection::traits::{ 40 self, NormalizeExt, ObligationCauseCode, ObligationCtxt, StructurallyNormalizeExt, 41 }; 42 43 use std::collections::hash_map::Entry; 44 use std::slice; 45 46 impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 47 /// Produces warning on the given node, if the current point in the 48 /// function is unreachable, and there hasn't been another warning. warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str)49 pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) { 50 // FIXME: Combine these two 'if' expressions into one once 51 // let chains are implemented 52 if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() { 53 // If span arose from a desugaring of `if` or `while`, then it is the condition itself, 54 // which diverges, that we are about to lint on. This gives suboptimal diagnostics. 55 // Instead, stop here so that the `if`- or `while`-expression's block is linted instead. 56 if !span.is_desugaring(DesugaringKind::CondTemporary) 57 && !span.is_desugaring(DesugaringKind::Async) 58 && !orig_span.is_desugaring(DesugaringKind::Await) 59 { 60 self.diverges.set(Diverges::WarnedAlways); 61 62 debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); 63 64 let msg = format!("unreachable {}", kind); 65 self.tcx().struct_span_lint_hir( 66 lint::builtin::UNREACHABLE_CODE, 67 id, 68 span, 69 msg.clone(), 70 |lint| { 71 lint.span_label(span, msg).span_label( 72 orig_span, 73 custom_note 74 .unwrap_or("any code following this expression is unreachable"), 75 ) 76 }, 77 ) 78 } 79 } 80 } 81 82 /// Resolves type and const variables in `ty` if possible. Unlike the infcx 83 /// version (resolve_vars_if_possible), this version will 84 /// also select obligations if it seems useful, in an effort 85 /// to get more type information. 86 // FIXME(-Ztrait-solver=next): A lot of the calls to this method should 87 // probably be `try_structurally_resolve_type` or `structurally_resolve_type` instead. resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx>88 pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> { 89 self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {}) 90 } 91 92 #[instrument(skip(self, mutate_fulfillment_errors), level = "debug", ret)] resolve_vars_with_obligations_and_mutate_fulfillment( &self, mut ty: Ty<'tcx>, mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>), ) -> Ty<'tcx>93 pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment( 94 &self, 95 mut ty: Ty<'tcx>, 96 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>), 97 ) -> Ty<'tcx> { 98 // No Infer()? Nothing needs doing. 99 if !ty.has_non_region_infer() { 100 debug!("no inference var, nothing needs doing"); 101 return ty; 102 } 103 104 // If `ty` is a type variable, see whether we already know what it is. 105 ty = self.resolve_vars_if_possible(ty); 106 if !ty.has_non_region_infer() { 107 debug!(?ty); 108 return ty; 109 } 110 111 // If not, try resolving pending obligations as much as 112 // possible. This can help substantially when there are 113 // indirect dependencies that don't seem worth tracking 114 // precisely. 115 self.select_obligations_where_possible(mutate_fulfillment_errors); 116 self.resolve_vars_if_possible(ty) 117 } 118 record_deferred_call_resolution( &self, closure_def_id: LocalDefId, r: DeferredCallResolution<'tcx>, )119 pub(in super::super) fn record_deferred_call_resolution( 120 &self, 121 closure_def_id: LocalDefId, 122 r: DeferredCallResolution<'tcx>, 123 ) { 124 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); 125 deferred_call_resolutions.entry(closure_def_id).or_default().push(r); 126 } 127 remove_deferred_call_resolutions( &self, closure_def_id: LocalDefId, ) -> Vec<DeferredCallResolution<'tcx>>128 pub(in super::super) fn remove_deferred_call_resolutions( 129 &self, 130 closure_def_id: LocalDefId, 131 ) -> Vec<DeferredCallResolution<'tcx>> { 132 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); 133 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default() 134 } 135 tag(&self) -> String136 pub fn tag(&self) -> String { 137 format!("{:p}", self) 138 } 139 local_ty(&self, span: Span, nid: hir::HirId) -> Ty<'tcx>140 pub fn local_ty(&self, span: Span, nid: hir::HirId) -> Ty<'tcx> { 141 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| { 142 span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid)) 143 }) 144 } 145 146 #[inline] write_ty(&self, id: hir::HirId, ty: Ty<'tcx>)147 pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) { 148 debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag()); 149 self.typeck_results.borrow_mut().node_types_mut().insert(id, ty); 150 151 if let Err(e) = ty.error_reported() { 152 self.set_tainted_by_errors(e); 153 } 154 } 155 write_field_index(&self, hir_id: hir::HirId, index: FieldIdx)156 pub fn write_field_index(&self, hir_id: hir::HirId, index: FieldIdx) { 157 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index); 158 } 159 160 #[instrument(level = "debug", skip(self))] write_resolution( &self, hir_id: hir::HirId, r: Result<(DefKind, DefId), ErrorGuaranteed>, )161 pub(in super::super) fn write_resolution( 162 &self, 163 hir_id: hir::HirId, 164 r: Result<(DefKind, DefId), ErrorGuaranteed>, 165 ) { 166 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r); 167 } 168 169 #[instrument(level = "debug", skip(self))] write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>)170 pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { 171 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id))); 172 self.write_substs(hir_id, method.substs); 173 } 174 write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>)175 pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) { 176 if !substs.is_empty() { 177 debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); 178 179 self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs); 180 } 181 } 182 183 /// Given the substs that we just converted from the HIR, try to 184 /// canonicalize them and store them as user-given substitutions 185 /// (i.e., substitutions that must be respected by the NLL check). 186 /// 187 /// This should be invoked **before any unifications have 188 /// occurred**, so that annotations like `Vec<_>` are preserved 189 /// properly. 190 #[instrument(skip(self), level = "debug")] write_user_type_annotation_from_substs( &self, hir_id: hir::HirId, def_id: DefId, substs: SubstsRef<'tcx>, user_self_ty: Option<UserSelfTy<'tcx>>, )191 pub fn write_user_type_annotation_from_substs( 192 &self, 193 hir_id: hir::HirId, 194 def_id: DefId, 195 substs: SubstsRef<'tcx>, 196 user_self_ty: Option<UserSelfTy<'tcx>>, 197 ) { 198 debug!("fcx {}", self.tag()); 199 200 if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) { 201 let canonicalized = self.canonicalize_user_type_annotation(UserType::TypeOf( 202 def_id, 203 UserSubsts { substs, user_self_ty }, 204 )); 205 debug!(?canonicalized); 206 self.write_user_type_annotation(hir_id, canonicalized); 207 } 208 } 209 210 #[instrument(skip(self), level = "debug")] write_user_type_annotation( &self, hir_id: hir::HirId, canonical_user_type_annotation: CanonicalUserType<'tcx>, )211 pub fn write_user_type_annotation( 212 &self, 213 hir_id: hir::HirId, 214 canonical_user_type_annotation: CanonicalUserType<'tcx>, 215 ) { 216 debug!("fcx {}", self.tag()); 217 218 if !canonical_user_type_annotation.is_identity() { 219 self.typeck_results 220 .borrow_mut() 221 .user_provided_types_mut() 222 .insert(hir_id, canonical_user_type_annotation); 223 } else { 224 debug!("skipping identity substs"); 225 } 226 } 227 228 #[instrument(skip(self, expr), level = "debug")] apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>)229 pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) { 230 debug!("expr = {:#?}", expr); 231 232 if adj.is_empty() { 233 return; 234 } 235 236 for a in &adj { 237 if let Adjust::NeverToAny = a.kind { 238 if a.target.is_ty_var() { 239 self.diverging_type_vars.borrow_mut().insert(a.target); 240 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target); 241 } 242 } 243 } 244 245 let autoborrow_mut = adj.iter().any(|adj| { 246 matches!( 247 adj, 248 &Adjustment { 249 kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })), 250 .. 251 } 252 ) 253 }); 254 255 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) { 256 Entry::Vacant(entry) => { 257 entry.insert(adj); 258 } 259 Entry::Occupied(mut entry) => { 260 debug!(" - composing on top of {:?}", entry.get()); 261 match (&entry.get()[..], &adj[..]) { 262 // Applying any adjustment on top of a NeverToAny 263 // is a valid NeverToAny adjustment, because it can't 264 // be reached. 265 (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return, 266 ( 267 &[ 268 Adjustment { kind: Adjust::Deref(_), .. }, 269 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. }, 270 ], 271 &[ 272 Adjustment { kind: Adjust::Deref(_), .. }, 273 .., // Any following adjustments are allowed. 274 ], 275 ) => { 276 // A reborrow has no effect before a dereference. 277 } 278 // FIXME: currently we never try to compose autoderefs 279 // and ReifyFnPointer/UnsafeFnPointer, but we could. 280 _ => { 281 self.tcx.sess.delay_span_bug( 282 expr.span, 283 format!( 284 "while adjusting {:?}, can't compose {:?} and {:?}", 285 expr, 286 entry.get(), 287 adj 288 ), 289 ); 290 } 291 } 292 *entry.get_mut() = adj; 293 } 294 } 295 296 // If there is an mutable auto-borrow, it is equivalent to `&mut <expr>`. 297 // In this case implicit use of `Deref` and `Index` within `<expr>` should 298 // instead be `DerefMut` and `IndexMut`, so fix those up. 299 if autoborrow_mut { 300 self.convert_place_derefs_to_mutable(expr); 301 } 302 } 303 304 /// Instantiates and normalizes the bounds for a given item instantiate_bounds( &self, span: Span, def_id: DefId, substs: SubstsRef<'tcx>, ) -> ty::InstantiatedPredicates<'tcx>305 pub(in super::super) fn instantiate_bounds( 306 &self, 307 span: Span, 308 def_id: DefId, 309 substs: SubstsRef<'tcx>, 310 ) -> ty::InstantiatedPredicates<'tcx> { 311 let bounds = self.tcx.predicates_of(def_id); 312 let result = bounds.instantiate(self.tcx, substs); 313 let result = self.normalize(span, result); 314 debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}", bounds, substs, result); 315 result 316 } 317 normalize<T>(&self, span: Span, value: T) -> T where T: TypeFoldable<TyCtxt<'tcx>>,318 pub(in super::super) fn normalize<T>(&self, span: Span, value: T) -> T 319 where 320 T: TypeFoldable<TyCtxt<'tcx>>, 321 { 322 self.register_infer_ok_obligations( 323 self.at(&self.misc(span), self.param_env).normalize(value), 324 ) 325 } 326 require_type_meets( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, def_id: DefId, )327 pub fn require_type_meets( 328 &self, 329 ty: Ty<'tcx>, 330 span: Span, 331 code: traits::ObligationCauseCode<'tcx>, 332 def_id: DefId, 333 ) { 334 self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code)); 335 } 336 require_type_is_sized( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, )337 pub fn require_type_is_sized( 338 &self, 339 ty: Ty<'tcx>, 340 span: Span, 341 code: traits::ObligationCauseCode<'tcx>, 342 ) { 343 if !ty.references_error() { 344 let lang_item = self.tcx.require_lang_item(LangItem::Sized, None); 345 self.require_type_meets(ty, span, code, lang_item); 346 } 347 } 348 require_type_is_sized_deferred( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, )349 pub fn require_type_is_sized_deferred( 350 &self, 351 ty: Ty<'tcx>, 352 span: Span, 353 code: traits::ObligationCauseCode<'tcx>, 354 ) { 355 if !ty.references_error() { 356 self.deferred_sized_obligations.borrow_mut().push((ty, span, code)); 357 } 358 } 359 register_bound( &self, ty: Ty<'tcx>, def_id: DefId, cause: traits::ObligationCause<'tcx>, )360 pub fn register_bound( 361 &self, 362 ty: Ty<'tcx>, 363 def_id: DefId, 364 cause: traits::ObligationCause<'tcx>, 365 ) { 366 if !ty.references_error() { 367 self.fulfillment_cx.borrow_mut().register_bound( 368 self, 369 self.param_env, 370 ty, 371 def_id, 372 cause, 373 ); 374 } 375 } 376 handle_raw_ty(&self, span: Span, ty: Ty<'tcx>) -> RawTy<'tcx>377 pub fn handle_raw_ty(&self, span: Span, ty: Ty<'tcx>) -> RawTy<'tcx> { 378 RawTy { raw: ty, normalized: self.normalize(span, ty) } 379 } 380 to_ty(&self, ast_t: &hir::Ty<'_>) -> RawTy<'tcx>381 pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> RawTy<'tcx> { 382 let t = self.astconv().ast_ty_to_ty(ast_t); 383 self.register_wf_obligation(t.into(), ast_t.span, traits::WellFormed(None)); 384 self.handle_raw_ty(ast_t.span, t) 385 } 386 to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx>387 pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> { 388 let ty = self.to_ty(ast_ty); 389 debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); 390 391 if Self::can_contain_user_lifetime_bounds(ty.raw) { 392 let c_ty = self.canonicalize_response(UserType::Ty(ty.raw)); 393 debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); 394 self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); 395 } 396 397 ty.normalized 398 } 399 user_substs_for_adt(ty: RawTy<'tcx>) -> UserSubsts<'tcx>400 pub(super) fn user_substs_for_adt(ty: RawTy<'tcx>) -> UserSubsts<'tcx> { 401 match (ty.raw.kind(), ty.normalized.kind()) { 402 (ty::Adt(_, substs), _) => UserSubsts { substs, user_self_ty: None }, 403 (_, ty::Adt(adt, substs)) => UserSubsts { 404 substs, 405 user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }), 406 }, 407 _ => bug!("non-adt type {:?}", ty), 408 } 409 } 410 array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx>411 pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> { 412 match length { 413 &hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span), 414 hir::ArrayLen::Body(anon_const) => { 415 let span = self.tcx.def_span(anon_const.def_id); 416 let c = ty::Const::from_anon_const(self.tcx, anon_const.def_id); 417 self.register_wf_obligation(c.into(), span, ObligationCauseCode::WellFormed(None)); 418 self.normalize(span, c) 419 } 420 } 421 } 422 const_arg_to_const( &self, ast_c: &hir::AnonConst, param_def_id: DefId, ) -> ty::Const<'tcx>423 pub fn const_arg_to_const( 424 &self, 425 ast_c: &hir::AnonConst, 426 param_def_id: DefId, 427 ) -> ty::Const<'tcx> { 428 let did = ast_c.def_id; 429 self.tcx.feed_anon_const_type(did, self.tcx.type_of(param_def_id)); 430 let c = ty::Const::from_anon_const(self.tcx, did); 431 self.register_wf_obligation( 432 c.into(), 433 self.tcx.hir().span(ast_c.hir_id), 434 ObligationCauseCode::WellFormed(None), 435 ); 436 c 437 } 438 439 // If the type given by the user has free regions, save it for later, since 440 // NLL would like to enforce those. Also pass in types that involve 441 // projections, since those can resolve to `'static` bounds (modulo #54940, 442 // which hopefully will be fixed by the time you see this comment, dear 443 // reader, although I have my doubts). Also pass in types with inference 444 // types, because they may be repeated. Other sorts of things are already 445 // sufficiently enforced with erased regions. =) can_contain_user_lifetime_bounds<T>(t: T) -> bool where T: TypeVisitable<TyCtxt<'tcx>>,446 fn can_contain_user_lifetime_bounds<T>(t: T) -> bool 447 where 448 T: TypeVisitable<TyCtxt<'tcx>>, 449 { 450 t.has_free_regions() || t.has_projections() || t.has_infer_types() 451 } 452 node_ty(&self, id: hir::HirId) -> Ty<'tcx>453 pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { 454 match self.typeck_results.borrow().node_types().get(id) { 455 Some(&t) => t, 456 None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx,e), 457 None => { 458 bug!( 459 "no type for node {} in fcx {}", 460 self.tcx.hir().node_to_string(id), 461 self.tag() 462 ); 463 } 464 } 465 } 466 node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>>467 pub fn node_ty_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> { 468 match self.typeck_results.borrow().node_types().get(id) { 469 Some(&t) => Some(t), 470 None if let Some(e) = self.tainted_by_errors() => Some(Ty::new_error(self.tcx,e)), 471 None => None, 472 } 473 } 474 475 /// Registers an obligation for checking later, during regionck, that `arg` is well-formed. register_wf_obligation( &self, arg: ty::GenericArg<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, )476 pub fn register_wf_obligation( 477 &self, 478 arg: ty::GenericArg<'tcx>, 479 span: Span, 480 code: traits::ObligationCauseCode<'tcx>, 481 ) { 482 // WF obligations never themselves fail, so no real need to give a detailed cause: 483 let cause = traits::ObligationCause::new(span, self.body_id, code); 484 self.register_predicate(traits::Obligation::new( 485 self.tcx, 486 cause, 487 self.param_env, 488 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg))), 489 )); 490 } 491 492 /// Registers obligations that all `substs` are well-formed. add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>)493 pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) { 494 for arg in substs.iter().filter(|arg| { 495 matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) 496 }) { 497 self.register_wf_obligation(arg, expr.span, traits::WellFormed(None)); 498 } 499 } 500 501 // FIXME(arielb1): use this instead of field.ty everywhere 502 // Only for fields! Returns <none> for methods> 503 // Indifferent to privacy flags field_ty( &self, span: Span, field: &'tcx ty::FieldDef, substs: SubstsRef<'tcx>, ) -> Ty<'tcx>504 pub fn field_ty( 505 &self, 506 span: Span, 507 field: &'tcx ty::FieldDef, 508 substs: SubstsRef<'tcx>, 509 ) -> Ty<'tcx> { 510 self.normalize(span, field.ty(self.tcx, substs)) 511 } 512 resolve_rvalue_scopes(&self, def_id: DefId)513 pub(in super::super) fn resolve_rvalue_scopes(&self, def_id: DefId) { 514 let scope_tree = self.tcx.region_scope_tree(def_id); 515 let rvalue_scopes = { rvalue_scopes::resolve_rvalue_scopes(self, &scope_tree, def_id) }; 516 let mut typeck_results = self.inh.typeck_results.borrow_mut(); 517 typeck_results.rvalue_scopes = rvalue_scopes; 518 } 519 resolve_generator_interiors(&self, def_id: DefId)520 pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) { 521 if self.tcx.sess.opts.unstable_opts.drop_tracking_mir { 522 self.save_generator_interior_predicates(def_id); 523 return; 524 } 525 526 self.select_obligations_where_possible(|_| {}); 527 528 let mut generators = self.deferred_generator_interiors.borrow_mut(); 529 for (_, body_id, interior, kind) in generators.drain(..) { 530 crate::generator_interior::resolve_interior(self, def_id, body_id, interior, kind); 531 self.select_obligations_where_possible(|_| {}); 532 } 533 } 534 535 /// Unify the inference variables corresponding to generator witnesses, and save all the 536 /// predicates that were stalled on those inference variables. 537 /// 538 /// This process allows to conservatively save all predicates that do depend on the generator 539 /// interior types, for later processing by `check_generator_obligations`. 540 /// 541 /// We must not attempt to select obligations after this method has run, or risk query cycle 542 /// ICE. 543 #[instrument(level = "debug", skip(self))] save_generator_interior_predicates(&self, def_id: DefId)544 fn save_generator_interior_predicates(&self, def_id: DefId) { 545 // Try selecting all obligations that are not blocked on inference variables. 546 // Once we start unifying generator witnesses, trying to select obligations on them will 547 // trigger query cycle ICEs, as doing so requires MIR. 548 self.select_obligations_where_possible(|_| {}); 549 550 let generators = std::mem::take(&mut *self.deferred_generator_interiors.borrow_mut()); 551 debug!(?generators); 552 553 for &(expr_def_id, body_id, interior, _) in generators.iter() { 554 debug!(?expr_def_id); 555 556 // Create the `GeneratorWitness` type that we will unify with `interior`. 557 let substs = ty::InternalSubsts::identity_for_item( 558 self.tcx, 559 self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), 560 ); 561 let witness = Ty::new_generator_witness_mir(self.tcx, expr_def_id.to_def_id(), substs); 562 563 // Unify `interior` with `witness` and collect all the resulting obligations. 564 let span = self.tcx.hir().body(body_id).value.span; 565 let ok = self 566 .at(&self.misc(span), self.param_env) 567 .eq(DefineOpaqueTypes::No, interior, witness) 568 .expect("Failed to unify generator interior type"); 569 let mut obligations = ok.obligations; 570 571 // Also collect the obligations that were unstalled by this unification. 572 obligations 573 .extend(self.fulfillment_cx.borrow_mut().drain_unstalled_obligations(&self.infcx)); 574 575 let obligations = obligations.into_iter().map(|o| (o.predicate, o.cause)).collect(); 576 debug!(?obligations); 577 self.typeck_results 578 .borrow_mut() 579 .generator_interior_predicates 580 .insert(expr_def_id, obligations); 581 } 582 } 583 584 #[instrument(skip(self), level = "debug")] report_ambiguity_errors(&self)585 pub(in super::super) fn report_ambiguity_errors(&self) { 586 let mut errors = self.fulfillment_cx.borrow_mut().collect_remaining_errors(self); 587 588 if !errors.is_empty() { 589 self.adjust_fulfillment_errors_for_expr_obligation(&mut errors); 590 self.err_ctxt().report_fulfillment_errors(&errors); 591 } 592 } 593 594 /// Select as many obligations as we can at present. select_obligations_where_possible( &self, mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>), )595 pub(in super::super) fn select_obligations_where_possible( 596 &self, 597 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>), 598 ) { 599 let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self); 600 if !result.is_empty() { 601 mutate_fulfillment_errors(&mut result); 602 self.adjust_fulfillment_errors_for_expr_obligation(&mut result); 603 self.err_ctxt().report_fulfillment_errors(&result); 604 } 605 } 606 607 /// For the overloaded place expressions (`*x`, `x[3]`), the trait 608 /// returns a type of `&T`, but the actual type we assign to the 609 /// *expression* is `T`. So this function just peels off the return 610 /// type by one layer to yield `T`. make_overloaded_place_return_type( &self, method: MethodCallee<'tcx>, ) -> ty::TypeAndMut<'tcx>611 pub(in super::super) fn make_overloaded_place_return_type( 612 &self, 613 method: MethodCallee<'tcx>, 614 ) -> ty::TypeAndMut<'tcx> { 615 // extract method return type, which will be &T; 616 let ret_ty = method.sig.output(); 617 618 // method returns &T, but the type as visible to user is T, so deref 619 ret_ty.builtin_deref(true).unwrap() 620 } 621 622 #[instrument(skip(self), level = "debug")] self_type_matches_expected_vid(&self, self_ty: Ty<'tcx>, expected_vid: ty::TyVid) -> bool623 fn self_type_matches_expected_vid(&self, self_ty: Ty<'tcx>, expected_vid: ty::TyVid) -> bool { 624 let self_ty = self.shallow_resolve(self_ty); 625 debug!(?self_ty); 626 627 match *self_ty.kind() { 628 ty::Infer(ty::TyVar(found_vid)) => { 629 // FIXME: consider using `sub_root_var` here so we 630 // can see through subtyping. 631 let found_vid = self.root_var(found_vid); 632 debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid); 633 expected_vid == found_vid 634 } 635 _ => false, 636 } 637 } 638 639 #[instrument(skip(self), level = "debug")] obligations_for_self_ty<'b>( &'b self, self_ty: ty::TyVid, ) -> impl DoubleEndedIterator<Item = traits::PredicateObligation<'tcx>> + Captures<'tcx> + 'b640 pub(in super::super) fn obligations_for_self_ty<'b>( 641 &'b self, 642 self_ty: ty::TyVid, 643 ) -> impl DoubleEndedIterator<Item = traits::PredicateObligation<'tcx>> + Captures<'tcx> + 'b 644 { 645 // FIXME: consider using `sub_root_var` here so we 646 // can see through subtyping. 647 let ty_var_root = self.root_var(self_ty); 648 trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations()); 649 650 self.fulfillment_cx.borrow().pending_obligations().into_iter().filter_map( 651 move |obligation| match &obligation.predicate.kind().skip_binder() { 652 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) 653 if self.self_type_matches_expected_vid( 654 data.projection_ty.self_ty(), 655 ty_var_root, 656 ) => 657 { 658 Some(obligation) 659 } 660 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) 661 if self.self_type_matches_expected_vid(data.self_ty(), ty_var_root) => 662 { 663 Some(obligation) 664 } 665 666 ty::PredicateKind::Clause(ty::ClauseKind::Trait(..)) 667 | ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) 668 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(..)) 669 | ty::PredicateKind::Subtype(..) 670 | ty::PredicateKind::Coerce(..) 671 | ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..)) 672 | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) 673 | ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(..)) 674 | ty::PredicateKind::ObjectSafe(..) 675 | ty::PredicateKind::AliasRelate(..) 676 | ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..)) 677 | ty::PredicateKind::ConstEquate(..) 678 // N.B., this predicate is created by breaking down a 679 // `ClosureType: FnFoo()` predicate, where 680 // `ClosureType` represents some `Closure`. It can't 681 // possibly be referring to the current closure, 682 // because we haven't produced the `Closure` for 683 // this closure yet; this is exactly why the other 684 // code is looking for a self type of an unresolved 685 // inference variable. 686 | ty::PredicateKind::ClosureKind(..) 687 | ty::PredicateKind::Ambiguous 688 => None, 689 }, 690 ) 691 } 692 type_var_is_sized(&self, self_ty: ty::TyVid) -> bool693 pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool { 694 let sized_did = self.tcx.lang_items().sized_trait(); 695 self.obligations_for_self_ty(self_ty).any(|obligation| { 696 match obligation.predicate.kind().skip_binder() { 697 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => { 698 Some(data.def_id()) == sized_did 699 } 700 _ => false, 701 } 702 }) 703 } 704 err_args(&self, len: usize) -> Vec<Ty<'tcx>>705 pub(in super::super) fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> { 706 let ty_error = Ty::new_misc_error(self.tcx); 707 vec![ty_error; len] 708 } 709 710 /// Unifies the output type with the expected type early, for more coercions 711 /// and forward type information on the input expressions. 712 #[instrument(skip(self, call_span), level = "debug")] expected_inputs_for_expected_output( &self, call_span: Span, expected_ret: Expectation<'tcx>, formal_ret: Ty<'tcx>, formal_args: &[Ty<'tcx>], ) -> Option<Vec<Ty<'tcx>>>713 pub(in super::super) fn expected_inputs_for_expected_output( 714 &self, 715 call_span: Span, 716 expected_ret: Expectation<'tcx>, 717 formal_ret: Ty<'tcx>, 718 formal_args: &[Ty<'tcx>], 719 ) -> Option<Vec<Ty<'tcx>>> { 720 let formal_ret = self.resolve_vars_with_obligations(formal_ret); 721 let ret_ty = expected_ret.only_has_type(self)?; 722 723 // HACK(oli-obk): This is a hack to keep RPIT and TAIT in sync wrt their behaviour. 724 // Without it, the inference 725 // variable will get instantiated with the opaque type. The inference variable often 726 // has various helpful obligations registered for it that help closures figure out their 727 // signature. If we infer the inference var to the opaque type, the closure won't be able 728 // to find those obligations anymore, and it can't necessarily find them from the opaque 729 // type itself. We could be more powerful with inference if we *combined* the obligations 730 // so that we got both the obligations from the opaque type and the ones from the inference 731 // variable. That will accept more code than we do right now, so we need to carefully consider 732 // the implications. 733 // Note: this check is pessimistic, as the inference type could be matched with something other 734 // than the opaque type, but then we need a new `TypeRelation` just for this specific case and 735 // can't re-use `sup` below. 736 // See tests/ui/impl-trait/hidden-type-is-opaque.rs and 737 // tests/ui/impl-trait/hidden-type-is-opaque-2.rs for examples that hit this path. 738 if formal_ret.has_infer_types() { 739 for ty in ret_ty.walk() { 740 if let ty::subst::GenericArgKind::Type(ty) = ty.unpack() 741 && let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *ty.kind() 742 && let Some(def_id) = def_id.as_local() 743 && self.opaque_type_origin(def_id).is_some() { 744 return None; 745 } 746 } 747 } 748 749 let expect_args = self 750 .fudge_inference_if_ok(|| { 751 let ocx = ObligationCtxt::new(self); 752 753 // Attempt to apply a subtyping relationship between the formal 754 // return type (likely containing type variables if the function 755 // is polymorphic) and the expected return type. 756 // No argument expectations are produced if unification fails. 757 let origin = self.misc(call_span); 758 ocx.sup(&origin, self.param_env, ret_ty, formal_ret)?; 759 if !ocx.select_where_possible().is_empty() { 760 return Err(TypeError::Mismatch); 761 } 762 763 // Record all the argument types, with the substitutions 764 // produced from the above subtyping unification. 765 Ok(Some(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect())) 766 }) 767 .unwrap_or_default(); 768 debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret); 769 expect_args 770 } 771 resolve_lang_item_path( &self, lang_item: hir::LangItem, span: Span, hir_id: hir::HirId, expr_hir_id: Option<hir::HirId>, ) -> (Res, Ty<'tcx>)772 pub(in super::super) fn resolve_lang_item_path( 773 &self, 774 lang_item: hir::LangItem, 775 span: Span, 776 hir_id: hir::HirId, 777 expr_hir_id: Option<hir::HirId>, 778 ) -> (Res, Ty<'tcx>) { 779 let def_id = self.tcx.require_lang_item(lang_item, Some(span)); 780 let def_kind = self.tcx.def_kind(def_id); 781 782 let item_ty = if let DefKind::Variant = def_kind { 783 self.tcx.type_of(self.tcx.parent(def_id)) 784 } else { 785 self.tcx.type_of(def_id) 786 }; 787 let substs = self.fresh_substs_for_item(span, def_id); 788 let ty = item_ty.subst(self.tcx, substs); 789 790 self.write_resolution(hir_id, Ok((def_kind, def_id))); 791 792 let code = match lang_item { 793 hir::LangItem::IntoFutureIntoFuture => { 794 Some(ObligationCauseCode::AwaitableExpr(expr_hir_id)) 795 } 796 hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => { 797 Some(ObligationCauseCode::ForLoopIterator) 798 } 799 hir::LangItem::TryTraitFromOutput 800 | hir::LangItem::TryTraitFromResidual 801 | hir::LangItem::TryTraitBranch => Some(ObligationCauseCode::QuestionMark), 802 _ => None, 803 }; 804 if let Some(code) = code { 805 self.add_required_obligations_with_code(span, def_id, substs, move |_, _| code.clone()); 806 } else { 807 self.add_required_obligations_for_hir(span, def_id, substs, hir_id); 808 } 809 810 (Res::Def(def_kind, def_id), ty) 811 } 812 813 /// Resolves an associated value path into a base type and associated constant, or method 814 /// resolution. The newly resolved definition is written into `type_dependent_defs`. resolve_ty_and_res_fully_qualified_call( &self, qpath: &'tcx QPath<'tcx>, hir_id: hir::HirId, span: Span, ) -> (Res, Option<RawTy<'tcx>>, &'tcx [hir::PathSegment<'tcx>])815 pub fn resolve_ty_and_res_fully_qualified_call( 816 &self, 817 qpath: &'tcx QPath<'tcx>, 818 hir_id: hir::HirId, 819 span: Span, 820 ) -> (Res, Option<RawTy<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) { 821 debug!( 822 "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}", 823 qpath, hir_id, span 824 ); 825 let (ty, qself, item_segment) = match *qpath { 826 QPath::Resolved(ref opt_qself, ref path) => { 827 return ( 828 path.res, 829 opt_qself.as_ref().map(|qself| self.to_ty(qself)), 830 path.segments, 831 ); 832 } 833 QPath::TypeRelative(ref qself, ref segment) => { 834 // Don't use `self.to_ty`, since this will register a WF obligation. 835 // If we're trying to call a nonexistent method on a trait 836 // (e.g. `MyTrait::missing_method`), then resolution will 837 // give us a `QPath::TypeRelative` with a trait object as 838 // `qself`. In that case, we want to avoid registering a WF obligation 839 // for `dyn MyTrait`, since we don't actually need the trait 840 // to be object-safe. 841 // We manually call `register_wf_obligation` in the success path 842 // below. 843 let ty = self.astconv().ast_ty_to_ty_in_path(qself); 844 (self.handle_raw_ty(span, ty), qself, segment) 845 } 846 QPath::LangItem(..) => { 847 bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`") 848 } 849 }; 850 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id) 851 { 852 self.register_wf_obligation(ty.raw.into(), qself.span, traits::WellFormed(None)); 853 // Return directly on cache hit. This is useful to avoid doubly reporting 854 // errors with default match binding modes. See #44614. 855 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)); 856 return (def, Some(ty), slice::from_ref(&**item_segment)); 857 } 858 let item_name = item_segment.ident; 859 let result = self 860 .resolve_fully_qualified_call(span, item_name, ty.normalized, qself.span, hir_id) 861 .and_then(|r| { 862 // lint bare trait if the method is found in the trait 863 if span.edition().rust_2021() && let Some(mut diag) = self.tcx.sess.diagnostic().steal_diagnostic(qself.span, StashKey::TraitMissingMethod) { 864 diag.emit(); 865 } 866 Ok(r) 867 }) 868 .or_else(|error| { 869 let guar = self 870 .tcx 871 .sess 872 .delay_span_bug(span, "method resolution should've emitted an error"); 873 let result = match error { 874 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)), 875 _ => Err(guar), 876 }; 877 878 let trait_missing_method = 879 matches!(error, method::MethodError::NoMatch(_)) && ty.normalized.is_trait(); 880 // If we have a path like `MyTrait::missing_method`, then don't register 881 // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise, 882 // register a WF obligation so that we can detect any additional 883 // errors in the self type. 884 if !trait_missing_method { 885 self.register_wf_obligation( 886 ty.raw.into(), 887 qself.span, 888 traits::WellFormed(None), 889 ); 890 } 891 892 // emit or cancel the diagnostic for bare traits 893 if span.edition().rust_2021() && let Some(mut diag) = self.tcx.sess.diagnostic().steal_diagnostic(qself.span, StashKey::TraitMissingMethod) { 894 if trait_missing_method { 895 // cancel the diag for bare traits when meeting `MyTrait::missing_method` 896 diag.cancel(); 897 } else { 898 diag.emit(); 899 } 900 } 901 902 if item_name.name != kw::Empty { 903 if let Some(mut e) = self.report_method_error( 904 span, 905 ty.normalized, 906 item_name, 907 SelfSource::QPath(qself), 908 error, 909 None, 910 Expectation::NoExpectation, 911 trait_missing_method && span.edition().rust_2021(), // emits missing method for trait only after edition 2021 912 ) { 913 e.emit(); 914 } 915 } 916 917 result 918 }); 919 920 if result.is_ok() { 921 self.register_wf_obligation(ty.raw.into(), qself.span, traits::WellFormed(None)); 922 } 923 924 // Write back the new resolution. 925 self.write_resolution(hir_id, result); 926 ( 927 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), 928 Some(ty), 929 slice::from_ref(&**item_segment), 930 ) 931 } 932 933 /// Given a function `Node`, return its `HirId` and `FnDecl` if it exists. Given a closure 934 /// that is the child of a function, return that function's `HirId` and `FnDecl` instead. 935 /// This may seem confusing at first, but this is used in diagnostics for `async fn`, 936 /// for example, where most of the type checking actually happens within a nested closure, 937 /// but we often want access to the parent function's signature. 938 /// 939 /// Otherwise, return false. get_node_fn_decl( &self, node: Node<'tcx>, ) -> Option<(hir::HirId, &'tcx hir::FnDecl<'tcx>, Ident, bool)>940 pub(in super::super) fn get_node_fn_decl( 941 &self, 942 node: Node<'tcx>, 943 ) -> Option<(hir::HirId, &'tcx hir::FnDecl<'tcx>, Ident, bool)> { 944 match node { 945 Node::Item(&hir::Item { 946 ident, 947 kind: hir::ItemKind::Fn(ref sig, ..), 948 owner_id, 949 .. 950 }) => { 951 // This is less than ideal, it will not suggest a return type span on any 952 // method called `main`, regardless of whether it is actually the entry point, 953 // but it will still present it as the reason for the expected type. 954 Some(( 955 hir::HirId::make_owner(owner_id.def_id), 956 &sig.decl, 957 ident, 958 ident.name != sym::main, 959 )) 960 } 961 Node::TraitItem(&hir::TraitItem { 962 ident, 963 kind: hir::TraitItemKind::Fn(ref sig, ..), 964 owner_id, 965 .. 966 }) => Some((hir::HirId::make_owner(owner_id.def_id), &sig.decl, ident, true)), 967 Node::ImplItem(&hir::ImplItem { 968 ident, 969 kind: hir::ImplItemKind::Fn(ref sig, ..), 970 owner_id, 971 .. 972 }) => Some((hir::HirId::make_owner(owner_id.def_id), &sig.decl, ident, false)), 973 Node::Expr(&hir::Expr { hir_id, kind: hir::ExprKind::Closure(..), .. }) 974 if let Some(Node::Item(&hir::Item { 975 ident, 976 kind: hir::ItemKind::Fn(ref sig, ..), 977 owner_id, 978 .. 979 })) = self.tcx.hir().find_parent(hir_id) => Some(( 980 hir::HirId::make_owner(owner_id.def_id), 981 &sig.decl, 982 ident, 983 ident.name != sym::main, 984 )), 985 _ => None, 986 } 987 } 988 989 /// Given a `HirId`, return the `HirId` of the enclosing function, its `FnDecl`, and whether a 990 /// suggestion can be made, `None` otherwise. get_fn_decl( &self, blk_id: hir::HirId, ) -> Option<(hir::HirId, &'tcx hir::FnDecl<'tcx>, bool)>991 pub fn get_fn_decl( 992 &self, 993 blk_id: hir::HirId, 994 ) -> Option<(hir::HirId, &'tcx hir::FnDecl<'tcx>, bool)> { 995 // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or 996 // `while` before reaching it, as block tail returns are not available in them. 997 self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { 998 let parent = self.tcx.hir().get(blk_id); 999 self.get_node_fn_decl(parent) 1000 .map(|(fn_id, fn_decl, _, is_main)| (fn_id, fn_decl, is_main)) 1001 }) 1002 } 1003 note_internal_mutation_in_method( &self, err: &mut Diagnostic, expr: &hir::Expr<'_>, expected: Option<Ty<'tcx>>, found: Ty<'tcx>, )1004 pub(in super::super) fn note_internal_mutation_in_method( 1005 &self, 1006 err: &mut Diagnostic, 1007 expr: &hir::Expr<'_>, 1008 expected: Option<Ty<'tcx>>, 1009 found: Ty<'tcx>, 1010 ) { 1011 if found != self.tcx.types.unit { 1012 return; 1013 } 1014 1015 let ExprKind::MethodCall(path_segment, rcvr, ..) = expr.kind else { 1016 return; 1017 }; 1018 1019 let rcvr_has_the_expected_type = self 1020 .typeck_results 1021 .borrow() 1022 .expr_ty_adjusted_opt(rcvr) 1023 .zip(expected) 1024 .is_some_and(|(ty, expected_ty)| expected_ty.peel_refs() == ty.peel_refs()); 1025 1026 let prev_call_mutates_and_returns_unit = || { 1027 self.typeck_results 1028 .borrow() 1029 .type_dependent_def_id(expr.hir_id) 1030 .map(|def_id| self.tcx.fn_sig(def_id).skip_binder().skip_binder()) 1031 .and_then(|sig| sig.inputs_and_output.split_last()) 1032 .is_some_and(|(output, inputs)| { 1033 output.is_unit() 1034 && inputs 1035 .get(0) 1036 .and_then(|self_ty| self_ty.ref_mutability()) 1037 .is_some_and(rustc_ast::Mutability::is_mut) 1038 }) 1039 }; 1040 1041 if !(rcvr_has_the_expected_type || prev_call_mutates_and_returns_unit()) { 1042 return; 1043 } 1044 1045 let mut sp = MultiSpan::from_span(path_segment.ident.span); 1046 sp.push_span_label( 1047 path_segment.ident.span, 1048 format!( 1049 "this call modifies {} in-place", 1050 match rcvr.kind { 1051 ExprKind::Path(QPath::Resolved( 1052 None, 1053 hir::Path { segments: [segment], .. }, 1054 )) => format!("`{}`", segment.ident), 1055 _ => "its receiver".to_string(), 1056 } 1057 ), 1058 ); 1059 1060 let modifies_rcvr_note = 1061 format!("method `{}` modifies its receiver in-place", path_segment.ident); 1062 if rcvr_has_the_expected_type { 1063 sp.push_span_label( 1064 rcvr.span, 1065 "you probably want to use this value after calling the method...", 1066 ); 1067 err.span_note(sp, modifies_rcvr_note); 1068 err.note(format!("...instead of the `()` output of method `{}`", path_segment.ident)); 1069 } else if let ExprKind::MethodCall(..) = rcvr.kind { 1070 err.span_note( 1071 sp, 1072 modifies_rcvr_note.clone() + ", it is not meant to be used in method chains.", 1073 ); 1074 } else { 1075 err.span_note(sp, modifies_rcvr_note); 1076 } 1077 } 1078 1079 // Instantiates the given path, which must refer to an item with the given 1080 // number of type parameters and type. 1081 #[instrument(skip(self, span), level = "debug")] instantiate_value_path( &self, segments: &[hir::PathSegment<'_>], self_ty: Option<RawTy<'tcx>>, res: Res, span: Span, hir_id: hir::HirId, ) -> (Ty<'tcx>, Res)1082 pub fn instantiate_value_path( 1083 &self, 1084 segments: &[hir::PathSegment<'_>], 1085 self_ty: Option<RawTy<'tcx>>, 1086 res: Res, 1087 span: Span, 1088 hir_id: hir::HirId, 1089 ) -> (Ty<'tcx>, Res) { 1090 let tcx = self.tcx; 1091 1092 let path_segs = match res { 1093 Res::Local(_) | Res::SelfCtor(_) => vec![], 1094 Res::Def(kind, def_id) => self.astconv().def_ids_for_value_path_segments( 1095 segments, 1096 self_ty.map(|ty| ty.raw), 1097 kind, 1098 def_id, 1099 span, 1100 ), 1101 _ => bug!("instantiate_value_path on {:?}", res), 1102 }; 1103 1104 let mut user_self_ty = None; 1105 let mut is_alias_variant_ctor = false; 1106 match res { 1107 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) 1108 if let Some(self_ty) = self_ty => 1109 { 1110 let adt_def = self_ty.normalized.ty_adt_def().unwrap(); 1111 user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty: self_ty.raw }); 1112 is_alias_variant_ctor = true; 1113 } 1114 Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => { 1115 let assoc_item = tcx.associated_item(def_id); 1116 let container = assoc_item.container; 1117 let container_id = assoc_item.container_id(tcx); 1118 debug!(?def_id, ?container, ?container_id); 1119 match container { 1120 ty::TraitContainer => { 1121 callee::check_legal_trait_for_method_call(tcx, span, None, span, container_id) 1122 } 1123 ty::ImplContainer => { 1124 if segments.len() == 1 { 1125 // `<T>::assoc` will end up here, and so 1126 // can `T::assoc`. It this came from an 1127 // inherent impl, we need to record the 1128 // `T` for posterity (see `UserSelfTy` for 1129 // details). 1130 let self_ty = self_ty.expect("UFCS sugared assoc missing Self").raw; 1131 user_self_ty = Some(UserSelfTy { impl_def_id: container_id, self_ty }); 1132 } 1133 } 1134 } 1135 } 1136 _ => {} 1137 } 1138 1139 // Now that we have categorized what space the parameters for each 1140 // segment belong to, let's sort out the parameters that the user 1141 // provided (if any) into their appropriate spaces. We'll also report 1142 // errors if type parameters are provided in an inappropriate place. 1143 1144 let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect(); 1145 let generics_has_err = self.astconv().prohibit_generics( 1146 segments.iter().enumerate().filter_map(|(index, seg)| { 1147 if !generic_segs.contains(&index) || is_alias_variant_ctor { 1148 Some(seg) 1149 } else { 1150 None 1151 } 1152 }), 1153 |_| {}, 1154 ); 1155 1156 if let Res::Local(hid) = res { 1157 let ty = self.local_ty(span, hid); 1158 let ty = self.normalize(span, ty); 1159 self.write_ty(hir_id, ty); 1160 return (ty, res); 1161 } 1162 1163 if generics_has_err { 1164 // Don't try to infer type parameters when prohibited generic arguments were given. 1165 user_self_ty = None; 1166 } 1167 1168 // Now we have to compare the types that the user *actually* 1169 // provided against the types that were *expected*. If the user 1170 // did not provide any types, then we want to substitute inference 1171 // variables. If the user provided some types, we may still need 1172 // to add defaults. If the user provided *too many* types, that's 1173 // a problem. 1174 1175 let mut infer_args_for_err = FxHashSet::default(); 1176 1177 let mut explicit_late_bound = ExplicitLateBound::No; 1178 for &PathSeg(def_id, index) in &path_segs { 1179 let seg = &segments[index]; 1180 let generics = tcx.generics_of(def_id); 1181 1182 // Argument-position `impl Trait` is treated as a normal generic 1183 // parameter internally, but we don't allow users to specify the 1184 // parameter's value explicitly, so we have to do some error- 1185 // checking here. 1186 let arg_count = check_generic_arg_count_for_call( 1187 tcx, 1188 span, 1189 def_id, 1190 &generics, 1191 seg, 1192 IsMethodCall::No, 1193 ); 1194 1195 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound { 1196 explicit_late_bound = ExplicitLateBound::Yes; 1197 } 1198 1199 if let Err(GenericArgCountMismatch { reported: Some(e), .. }) = arg_count.correct { 1200 infer_args_for_err.insert(index); 1201 self.set_tainted_by_errors(e); // See issue #53251. 1202 } 1203 } 1204 1205 let has_self = 1206 path_segs.last().is_some_and(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self); 1207 1208 let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { 1209 let ty = self.handle_raw_ty(span, tcx.at(span).type_of(impl_def_id).subst_identity()); 1210 match ty.normalized.ty_adt_def() { 1211 Some(adt_def) if adt_def.has_ctor() => { 1212 let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap(); 1213 // Check the visibility of the ctor. 1214 let vis = tcx.visibility(ctor_def_id); 1215 if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) { 1216 tcx.sess 1217 .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) }); 1218 } 1219 let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); 1220 let user_substs = Self::user_substs_for_adt(ty); 1221 user_self_ty = user_substs.user_self_ty; 1222 (new_res, Some(user_substs.substs)) 1223 } 1224 _ => { 1225 let mut err = tcx.sess.struct_span_err( 1226 span, 1227 "the `Self` constructor can only be used with tuple or unit structs", 1228 ); 1229 if let Some(adt_def) = ty.normalized.ty_adt_def() { 1230 match adt_def.adt_kind() { 1231 AdtKind::Enum => { 1232 err.help("did you mean to use one of the enum's variants?"); 1233 } 1234 AdtKind::Struct | AdtKind::Union => { 1235 err.span_suggestion( 1236 span, 1237 "use curly brackets", 1238 "Self { /* fields */ }", 1239 Applicability::HasPlaceholders, 1240 ); 1241 } 1242 } 1243 } 1244 let reported = err.emit(); 1245 return (Ty::new_error(tcx, reported), res); 1246 } 1247 } 1248 } else { 1249 (res, None) 1250 }; 1251 let def_id = res.def_id(); 1252 1253 let arg_count = GenericArgCountResult { 1254 explicit_late_bound, 1255 correct: if infer_args_for_err.is_empty() { 1256 Ok(()) 1257 } else { 1258 Err(GenericArgCountMismatch::default()) 1259 }, 1260 }; 1261 1262 struct CreateCtorSubstsContext<'a, 'tcx> { 1263 fcx: &'a FnCtxt<'a, 'tcx>, 1264 span: Span, 1265 path_segs: &'a [PathSeg], 1266 infer_args_for_err: &'a FxHashSet<usize>, 1267 segments: &'a [hir::PathSegment<'a>], 1268 } 1269 impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> { 1270 fn args_for_def_id( 1271 &mut self, 1272 def_id: DefId, 1273 ) -> (Option<&'a hir::GenericArgs<'a>>, bool) { 1274 if let Some(&PathSeg(_, index)) = 1275 self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id) 1276 { 1277 // If we've encountered an `impl Trait`-related error, we're just 1278 // going to infer the arguments for better error messages. 1279 if !self.infer_args_for_err.contains(&index) { 1280 // Check whether the user has provided generic arguments. 1281 if let Some(ref data) = self.segments[index].args { 1282 return (Some(data), self.segments[index].infer_args); 1283 } 1284 } 1285 return (None, self.segments[index].infer_args); 1286 } 1287 1288 (None, true) 1289 } 1290 1291 fn provided_kind( 1292 &mut self, 1293 param: &ty::GenericParamDef, 1294 arg: &GenericArg<'_>, 1295 ) -> ty::GenericArg<'tcx> { 1296 match (¶m.kind, arg) { 1297 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { 1298 self.fcx.astconv().ast_region_to_region(lt, Some(param)).into() 1299 } 1300 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { 1301 self.fcx.to_ty(ty).raw.into() 1302 } 1303 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => { 1304 self.fcx.const_arg_to_const(&ct.value, param.def_id).into() 1305 } 1306 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => { 1307 self.fcx.ty_infer(Some(param), inf.span).into() 1308 } 1309 (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => { 1310 let tcx = self.fcx.tcx(); 1311 self.fcx 1312 .ct_infer( 1313 tcx.type_of(param.def_id) 1314 .no_bound_vars() 1315 .expect("const parameter types cannot be generic"), 1316 Some(param), 1317 inf.span, 1318 ) 1319 .into() 1320 } 1321 _ => unreachable!(), 1322 } 1323 } 1324 1325 fn inferred_kind( 1326 &mut self, 1327 substs: Option<&[ty::GenericArg<'tcx>]>, 1328 param: &ty::GenericParamDef, 1329 infer_args: bool, 1330 ) -> ty::GenericArg<'tcx> { 1331 let tcx = self.fcx.tcx(); 1332 match param.kind { 1333 GenericParamDefKind::Lifetime => { 1334 self.fcx.re_infer(Some(param), self.span).unwrap().into() 1335 } 1336 GenericParamDefKind::Type { has_default, .. } => { 1337 if !infer_args && has_default { 1338 // If we have a default, then we it doesn't matter that we're not 1339 // inferring the type arguments: we provide the default where any 1340 // is missing. 1341 tcx.type_of(param.def_id).subst(tcx, substs.unwrap()).into() 1342 } else { 1343 // If no type arguments were provided, we have to infer them. 1344 // This case also occurs as a result of some malformed input, e.g. 1345 // a lifetime argument being given instead of a type parameter. 1346 // Using inference instead of `Error` gives better error messages. 1347 self.fcx.var_for_def(self.span, param) 1348 } 1349 } 1350 GenericParamDefKind::Const { has_default } => { 1351 if !infer_args && has_default { 1352 tcx.const_param_default(param.def_id).subst(tcx, substs.unwrap()).into() 1353 } else { 1354 self.fcx.var_for_def(self.span, param) 1355 } 1356 } 1357 } 1358 } 1359 } 1360 1361 let substs_raw = self_ctor_substs.unwrap_or_else(|| { 1362 create_substs_for_generic_args( 1363 tcx, 1364 def_id, 1365 &[], 1366 has_self, 1367 self_ty.map(|s| s.raw), 1368 &arg_count, 1369 &mut CreateCtorSubstsContext { 1370 fcx: self, 1371 span, 1372 path_segs: &path_segs, 1373 infer_args_for_err: &infer_args_for_err, 1374 segments, 1375 }, 1376 ) 1377 }); 1378 1379 // First, store the "user substs" for later. 1380 self.write_user_type_annotation_from_substs(hir_id, def_id, substs_raw, user_self_ty); 1381 1382 // Normalize only after registering type annotations. 1383 let substs = self.normalize(span, substs_raw); 1384 1385 self.add_required_obligations_for_hir(span, def_id, &substs, hir_id); 1386 1387 // Substitute the values for the type parameters into the type of 1388 // the referenced item. 1389 let ty = tcx.type_of(def_id); 1390 assert!(!substs.has_escaping_bound_vars()); 1391 assert!(!ty.skip_binder().has_escaping_bound_vars()); 1392 let ty_substituted = self.normalize(span, ty.subst(tcx, substs)); 1393 1394 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { 1395 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method` 1396 // is inherent, there is no `Self` parameter; instead, the impl needs 1397 // type parameters, which we can infer by unifying the provided `Self` 1398 // with the substituted impl type. 1399 // This also occurs for an enum variant on a type alias. 1400 let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).subst(tcx, substs)); 1401 let self_ty = self.normalize(span, self_ty); 1402 match self.at(&self.misc(span), self.param_env).eq( 1403 DefineOpaqueTypes::No, 1404 impl_ty, 1405 self_ty, 1406 ) { 1407 Ok(ok) => self.register_infer_ok_obligations(ok), 1408 Err(_) => { 1409 self.tcx.sess.delay_span_bug( 1410 span, 1411 format!( 1412 "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", 1413 self_ty, 1414 impl_ty, 1415 ), 1416 ); 1417 } 1418 } 1419 } 1420 1421 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted); 1422 self.write_substs(hir_id, substs); 1423 1424 (ty_substituted, res) 1425 } 1426 1427 /// Add all the obligations that are required, substituting and normalized appropriately. add_required_obligations_for_hir( &self, span: Span, def_id: DefId, substs: SubstsRef<'tcx>, hir_id: hir::HirId, )1428 pub(crate) fn add_required_obligations_for_hir( 1429 &self, 1430 span: Span, 1431 def_id: DefId, 1432 substs: SubstsRef<'tcx>, 1433 hir_id: hir::HirId, 1434 ) { 1435 self.add_required_obligations_with_code(span, def_id, substs, |idx, span| { 1436 if span.is_dummy() { 1437 ObligationCauseCode::ExprItemObligation(def_id, hir_id, idx) 1438 } else { 1439 ObligationCauseCode::ExprBindingObligation(def_id, span, hir_id, idx) 1440 } 1441 }) 1442 } 1443 1444 #[instrument(level = "debug", skip(self, code, span, substs))] add_required_obligations_with_code( &self, span: Span, def_id: DefId, substs: SubstsRef<'tcx>, code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>, )1445 fn add_required_obligations_with_code( 1446 &self, 1447 span: Span, 1448 def_id: DefId, 1449 substs: SubstsRef<'tcx>, 1450 code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>, 1451 ) { 1452 let param_env = self.param_env; 1453 1454 let bounds = self.instantiate_bounds(span, def_id, &substs); 1455 1456 for obligation in traits::predicates_for_generics( 1457 |idx, predicate_span| { 1458 traits::ObligationCause::new(span, self.body_id, code(idx, predicate_span)) 1459 }, 1460 param_env, 1461 bounds, 1462 ) { 1463 // N.B. We are remapping all predicates to non-const since we don't know if we just 1464 // want them as function pointers or we are calling them from a const-context. The 1465 // actual checking will occur in `rustc_const_eval::transform::check_consts`. 1466 self.register_predicate(obligation.without_const(self.tcx)); 1467 } 1468 } 1469 1470 /// Try to resolve `ty` to a structural type, normalizing aliases. 1471 /// 1472 /// In case there is still ambiguity, the returned type may be an inference 1473 /// variable. This is different from `structurally_resolve_type` which errors 1474 /// in this case. try_structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx>1475 pub fn try_structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { 1476 let ty = self.resolve_vars_with_obligations(ty); 1477 1478 if self.next_trait_solver() 1479 && let ty::Alias(ty::Projection, _) = ty.kind() 1480 { 1481 match self 1482 .at(&self.misc(sp), self.param_env) 1483 .structurally_normalize(ty, &mut **self.fulfillment_cx.borrow_mut()) 1484 { 1485 Ok(normalized_ty) => normalized_ty, 1486 Err(errors) => { 1487 let guar = self.err_ctxt().report_fulfillment_errors(&errors); 1488 return Ty::new_error(self.tcx,guar); 1489 } 1490 } 1491 } else { 1492 ty 1493 } 1494 } 1495 1496 /// Resolves `ty` by a single level if `ty` is a type variable. 1497 /// 1498 /// When the new solver is enabled, this will also attempt to normalize 1499 /// the type if it's a projection (note that it will not deeply normalize 1500 /// projections within the type, just the outermost layer of the type). 1501 /// 1502 /// If no resolution is possible, then an error is reported. 1503 /// Numeric inference variables may be left unresolved. structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx>1504 pub fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { 1505 let ty = self.try_structurally_resolve_type(sp, ty); 1506 1507 if !ty.is_ty_var() { 1508 ty 1509 } else { 1510 let e = self.tainted_by_errors().unwrap_or_else(|| { 1511 self.err_ctxt() 1512 .emit_inference_failure_err(self.body_id, sp, ty.into(), E0282, true) 1513 .emit() 1514 }); 1515 let err = Ty::new_error(self.tcx, e); 1516 self.demand_suptype(sp, err, ty); 1517 err 1518 } 1519 } 1520 with_breakable_ctxt<F: FnOnce() -> R, R>( &self, id: hir::HirId, ctxt: BreakableCtxt<'tcx>, f: F, ) -> (BreakableCtxt<'tcx>, R)1521 pub(in super::super) fn with_breakable_ctxt<F: FnOnce() -> R, R>( 1522 &self, 1523 id: hir::HirId, 1524 ctxt: BreakableCtxt<'tcx>, 1525 f: F, 1526 ) -> (BreakableCtxt<'tcx>, R) { 1527 let index; 1528 { 1529 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); 1530 index = enclosing_breakables.stack.len(); 1531 enclosing_breakables.by_id.insert(id, index); 1532 enclosing_breakables.stack.push(ctxt); 1533 } 1534 let result = f(); 1535 let ctxt = { 1536 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); 1537 debug_assert!(enclosing_breakables.stack.len() == index + 1); 1538 enclosing_breakables.by_id.remove(&id).expect("missing breakable context"); 1539 enclosing_breakables.stack.pop().expect("missing breakable context") 1540 }; 1541 (ctxt, result) 1542 } 1543 1544 /// Instantiate a QueryResponse in a probe context, without a 1545 /// good ObligationCause. probe_instantiate_query_response( &self, span: Span, original_values: &OriginalQueryValues<'tcx>, query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, ) -> InferResult<'tcx, Ty<'tcx>>1546 pub(in super::super) fn probe_instantiate_query_response( 1547 &self, 1548 span: Span, 1549 original_values: &OriginalQueryValues<'tcx>, 1550 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, 1551 ) -> InferResult<'tcx, Ty<'tcx>> { 1552 self.instantiate_query_response_and_region_obligations( 1553 &traits::ObligationCause::misc(span, self.body_id), 1554 self.param_env, 1555 original_values, 1556 query_result, 1557 ) 1558 } 1559 1560 /// Returns `true` if an expression is contained inside the LHS of an assignment expression. expr_in_place(&self, mut expr_id: hir::HirId) -> bool1561 pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool { 1562 let mut contained_in_place = false; 1563 1564 while let hir::Node::Expr(parent_expr) = self.tcx.hir().get_parent(expr_id) { 1565 match &parent_expr.kind { 1566 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => { 1567 if lhs.hir_id == expr_id { 1568 contained_in_place = true; 1569 break; 1570 } 1571 } 1572 _ => (), 1573 } 1574 expr_id = parent_expr.hir_id; 1575 } 1576 1577 contained_in_place 1578 } 1579 } 1580