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