]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_typeck/src/check/writeback.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / compiler / rustc_typeck / src / check / writeback.rs
CommitLineData
1a4d82fc
JJ
1// Type resolution: the phase that finds all the types in the AST with
2// unresolved type variables and replaces "ty_var" types with their
3// substitutions.
1a4d82fc 4
9fa01778 5use crate::check::FnCtxt;
60c5eb7d 6
6a06907d 7use rustc_data_structures::stable_map::FxHashMap;
ba9703b0 8use rustc_errors::ErrorReported;
dfeec247 9use rustc_hir as hir;
6a06907d 10use rustc_hir::def_id::DefId;
dfeec247 11use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
74b04a01
XL
12use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
13use rustc_infer::infer::InferCtxt;
6a06907d
XL
14use rustc_middle::hir::place::Place as HirPlace;
15use rustc_middle::mir::FakeReadCause;
ba9703b0
XL
16use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast};
17use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
18use rustc_middle::ty::{self, Ty, TyCtxt};
dfeec247
XL
19use rustc_span::symbol::sym;
20use rustc_span::Span;
ba9703b0 21use rustc_trait_selection::opaque_types::InferCtxtExt;
1a4d82fc 22
60c5eb7d
XL
23use std::mem;
24
1a4d82fc 25///////////////////////////////////////////////////////////////////////////
32a655c1 26// Entry point
1a4d82fc 27
0731742a
XL
28// During type inference, partially inferred types are
29// represented using Type variables (ty::Infer). These don't appear in
3dfed10e
XL
30// the final TypeckResults since all of the types should have been
31// inferred once typeck is done.
0731742a 32// When type inference is running however, having to update the typeck
3dfed10e 33// typeck results every time a new type is inferred would be unreasonably slow,
0731742a
XL
34// so instead all of the replacement happens at the end in
35// resolve_type_vars_in_body, which creates a new TypeTables which
36// doesn't contain any inference types.
dc9dc135 37impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
dfeec247
XL
38 pub fn resolve_type_vars_in_body(
39 &self,
40 body: &'tcx hir::Body<'tcx>,
3dfed10e 41 ) -> &'tcx ty::TypeckResults<'tcx> {
0731742a 42 let item_id = self.tcx.hir().body_owner(body.id());
416331ca 43 let item_def_id = self.tcx.hir().local_def_id(item_id);
32a655c1 44
b7449926 45 // This attribute causes us to dump some writeback information
ba9703b0 46 // in the form of errors, which is uSymbol for unit tests.
f9f354fc
XL
47 let rustc_dump_user_substs =
48 self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs);
b7449926
XL
49
50 let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
dfeec247 51 for param in body.params {
e1599b0c 52 wbcx.visit_node_id(param.pat.span, param.hir_id);
1a4d82fc 53 }
48663c56
XL
54 // Type only exists for constants and statics, not functions.
55 match self.tcx.hir().body_owner_kind(item_id) {
56 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => {
dc9dc135 57 wbcx.visit_node_id(body.value.span, item_id);
48663c56
XL
58 }
59 hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (),
60 }
32a655c1 61 wbcx.visit_body(body);
fc512014 62 wbcx.visit_min_capture_map();
6a06907d 63 wbcx.visit_fake_reads_map();
a7813a04
XL
64 wbcx.visit_closures();
65 wbcx.visit_liberated_fn_sigs();
66 wbcx.visit_fru_field_types();
b7449926 67 wbcx.visit_opaque_types(body.value.span);
532ac7d7 68 wbcx.visit_coercion_casts();
0531ce1d 69 wbcx.visit_user_provided_tys();
0bf4aa26 70 wbcx.visit_user_provided_sigs();
e1599b0c 71 wbcx.visit_generator_interior_types();
8bb4bdeb 72
3dfed10e
XL
73 let used_trait_imports =
74 mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
dfeec247 75 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
3dfed10e 76 wbcx.typeck_results.used_trait_imports = used_trait_imports;
32a655c1 77
29967ef6
XL
78 wbcx.typeck_results.treat_byte_string_as_slice =
79 mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice);
80
ba9703b0
XL
81 if self.is_tainted_by_errors() {
82 // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted.
3dfed10e 83 wbcx.typeck_results.tainted_by_errors = Some(ErrorReported);
ba9703b0 84 }
8bb4bdeb 85
3dfed10e 86 debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
ff7c6d11 87
3dfed10e 88 self.tcx.arena.alloc(wbcx.typeck_results)
1a4d82fc 89 }
1a4d82fc
JJ
90}
91
92///////////////////////////////////////////////////////////////////////////
fc512014 93// The Writeback context. This visitor walks the HIR, checking the
3dfed10e 94// fn-specific typeck results to find references to types or regions. It
1a4d82fc 95// resolves those regions to remove inference variables and writes the
3dfed10e 96// final result back into the master typeck results in the tcx. Here and
1a4d82fc
JJ
97// there, it applies a few ad-hoc checks that were not convenient to
98// do elsewhere.
99
dc9dc135
XL
100struct WritebackCx<'cx, 'tcx> {
101 fcx: &'cx FnCtxt<'cx, 'tcx>,
5bcae85e 102
3dfed10e 103 typeck_results: ty::TypeckResults<'tcx>,
32a655c1 104
dfeec247 105 body: &'tcx hir::Body<'tcx>,
b7449926
XL
106
107 rustc_dump_user_substs: bool,
1a4d82fc
JJ
108}
109
dc9dc135 110impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
ff7c6d11 111 fn new(
dc9dc135 112 fcx: &'cx FnCtxt<'cx, 'tcx>,
dfeec247 113 body: &'tcx hir::Body<'tcx>,
b7449926 114 rustc_dump_user_substs: bool,
dc9dc135 115 ) -> WritebackCx<'cx, 'tcx> {
ba9703b0 116 let owner = body.id().hir_id.owner;
3b2f2976 117
3dfed10e
XL
118 WritebackCx {
119 fcx,
120 typeck_results: ty::TypeckResults::new(owner),
121 body,
122 rustc_dump_user_substs,
123 }
1a4d82fc
JJ
124 }
125
dc9dc135 126 fn tcx(&self) -> TyCtxt<'tcx> {
a7813a04 127 self.fcx.tcx
1a4d82fc 128 }
d9579d0f 129
3dfed10e
XL
130 fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) {
131 debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty);
ba9703b0 132 assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions());
3dfed10e 133 self.typeck_results.node_types_mut().insert(hir_id, ty);
476ff2be
SL
134 }
135
d9579d0f
AL
136 // Hacky hack: During type-checking, we treat *all* operators
137 // as potentially overloaded. But then, during writeback, if
138 // we observe that something like `a+b` is (known to be)
139 // operating on scalars, we clear the overload.
dfeec247 140 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
e74abb32 141 match e.kind {
6a06907d 142 hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, ref inner) => {
3b2f2976 143 let inner_ty = self.fcx.node_ty(inner.hir_id);
fc512014 144 let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty);
32a655c1
SL
145
146 if inner_ty.is_scalar() {
3dfed10e
XL
147 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
148 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
149 typeck_results.node_substs_mut().remove(e.hir_id);
32a655c1
SL
150 }
151 }
8faf50e0
XL
152 hir::ExprKind::Binary(ref op, ref lhs, ref rhs)
153 | hir::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
3b2f2976 154 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
fc512014 155 let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty);
b039eaaf 156
3b2f2976 157 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
fc512014 158 let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty);
b039eaaf
SL
159
160 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
3dfed10e
XL
161 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
162 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
163 typeck_results.node_substs_mut().remove(e.hir_id);
b039eaaf 164
e74abb32 165 match e.kind {
8faf50e0 166 hir::ExprKind::Binary(..) => {
54a0048b 167 if !op.node.is_by_value() {
3dfed10e 168 let mut adjustments = typeck_results.adjustments_mut();
f9f354fc
XL
169 if let Some(a) = adjustments.get_mut(lhs.hir_id) {
170 a.pop();
171 }
172 if let Some(a) = adjustments.get_mut(rhs.hir_id) {
173 a.pop();
174 }
b039eaaf 175 }
ff7c6d11 176 }
8faf50e0 177 hir::ExprKind::AssignOp(..) => {
3dfed10e 178 if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) {
f9f354fc
XL
179 a.pop();
180 }
ff7c6d11
XL
181 }
182 _ => {}
b039eaaf 183 }
d9579d0f
AL
184 }
185 }
ff7c6d11 186 _ => {}
d9579d0f
AL
187 }
188 }
2c00a5a8
XL
189
190 // Similar to operators, indexing is always assumed to be overloaded
191 // Here, correct cases where an indexing expression can be simplified
192 // to use builtin indexing because the index type is known to be
193 // usize-ish
dfeec247 194 fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
e74abb32 195 if let hir::ExprKind::Index(ref base, ref index) = e.kind {
3dfed10e 196 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
2c00a5a8 197
e74abb32 198 // All valid indexing looks like this; might encounter non-valid indexes at this point.
fc512014
XL
199 let base_ty = typeck_results
200 .expr_ty_adjusted_opt(&base)
201 .map(|t| self.fcx.resolve_vars_if_possible(t).kind());
e74abb32
XL
202 if base_ty.is_none() {
203 // When encountering `return [0][0]` outside of a `fn` body we can encounter a base
204 // that isn't in the type table. We assume more relevant errors have already been
205 // emitted, so we delay an ICE if none have. (#64638)
206 self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base));
207 }
208 if let Some(ty::Ref(_, base_ty, _)) = base_ty {
3dfed10e 209 let index_ty = typeck_results.expr_ty_adjusted_opt(&index).unwrap_or_else(|| {
e74abb32
XL
210 // When encountering `return [0][0]` outside of a `fn` body we would attempt
211 // to access an unexistend index. We assume that more relevant errors will
212 // already have been emitted, so we only gate on this with an ICE if no
213 // error has been emitted. (#64638)
f035d41b 214 self.fcx.tcx.ty_error_with_message(
e74abb32
XL
215 e.span,
216 &format!("bad index {:?} for base: `{:?}`", index, base),
f035d41b 217 )
e74abb32 218 });
fc512014 219 let index_ty = self.fcx.resolve_vars_if_possible(index_ty);
0bf4aa26
XL
220
221 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
222 // Remove the method call record
3dfed10e
XL
223 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
224 typeck_results.node_substs_mut().remove(e.hir_id);
0bf4aa26 225
3dfed10e 226 if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) {
0bf4aa26 227 // Discard the need for a mutable borrow
ba9703b0
XL
228
229 // Extra adjustment made when indexing causes a drop
230 // of size information - we need to get rid of it
231 // Since this is "after" the other adjustment to be
232 // discarded, we do an extra `pop()`
233 if let Some(Adjustment {
234 kind: Adjust::Pointer(PointerCast::Unsize), ..
235 }) = a.pop()
236 {
237 // So the borrow discard actually happens here
238 a.pop();
0bf4aa26 239 }
f9f354fc 240 }
b7449926 241 }
2c00a5a8
XL
242 }
243 }
244 }
1a4d82fc
JJ
245}
246
247///////////////////////////////////////////////////////////////////////////
248// Impl of Visitor for Resolver
249//
250// This is the master code which walks the AST. It delegates most of
251// the heavy lifting to the generic visit and resolve functions
252// below. In general, a function is made into a `visitor` if it must
3dfed10e 253// traffic in node-ids or update typeck results in the type context etc.
1a4d82fc 254
dc9dc135 255impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
ba9703b0 256 type Map = intravisit::ErasedMap<'tcx>;
dfeec247 257
ba9703b0 258 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
32a655c1 259 NestedVisitorMap::None
476ff2be
SL
260 }
261
dfeec247 262 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
32a655c1 263 self.fix_scalar_builtin_expr(e);
2c00a5a8 264 self.fix_index_builtin_expr(e);
c34b1796 265
3b2f2976 266 self.visit_node_id(e.span, e.hir_id);
1a4d82fc 267
e74abb32 268 match e.kind {
8faf50e0 269 hir::ExprKind::Closure(_, _, body, _, _) => {
0731742a 270 let body = self.fcx.tcx.hir().body(body);
dfeec247 271 for param in body.params {
e1599b0c 272 self.visit_node_id(e.span, param.hir_id);
83c7162d 273 }
32a655c1 274
83c7162d
XL
275 self.visit_body(body);
276 }
dfeec247 277 hir::ExprKind::Struct(_, fields, _) => {
83c7162d 278 for field in fields {
532ac7d7 279 self.visit_field_id(field.hir_id);
83c7162d
XL
280 }
281 }
8faf50e0 282 hir::ExprKind::Field(..) => {
532ac7d7 283 self.visit_field_id(e.hir_id);
83c7162d
XL
284 }
285 _ => {}
1a4d82fc
JJ
286 }
287
92a42be0 288 intravisit::walk_expr(self, e);
1a4d82fc
JJ
289 }
290
dfeec247 291 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
3b2f2976 292 self.visit_node_id(b.span, b.hir_id);
92a42be0 293 intravisit::walk_block(self, b);
1a4d82fc
JJ
294 }
295
dfeec247 296 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
e74abb32 297 match p.kind {
3b2f2976 298 hir::PatKind::Binding(..) => {
3dfed10e
XL
299 let typeck_results = self.fcx.typeck_results.borrow();
300 if let Some(bm) =
301 typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span)
302 {
303 self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm);
8faf50e0 304 }
3b2f2976 305 }
dfeec247 306 hir::PatKind::Struct(_, fields, _) => {
83c7162d 307 for field in fields {
e1599b0c 308 self.visit_field_id(field.hir_id);
83c7162d
XL
309 }
310 }
3b2f2976
XL
311 _ => {}
312 };
313
ea8adc8c
XL
314 self.visit_pat_adjustments(p.span, p.hir_id);
315
3b2f2976 316 self.visit_node_id(p.span, p.hir_id);
92a42be0 317 intravisit::walk_pat(self, p);
1a4d82fc
JJ
318 }
319
dfeec247 320 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
cc61c64b 321 intravisit::walk_local(self, l);
532ac7d7 322 let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
fc512014 323 let var_ty = self.resolve(var_ty, &l.span);
3dfed10e 324 self.write_ty_to_typeck_results(l.hir_id, var_ty);
1a4d82fc 325 }
ea8adc8c 326
dfeec247 327 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
ea8adc8c
XL
328 intravisit::walk_ty(self, hir_ty);
329 let ty = self.fcx.node_ty(hir_ty.hir_id);
fc512014 330 let ty = self.resolve(ty, &hir_ty.span);
3dfed10e 331 self.write_ty_to_typeck_results(hir_ty.hir_id, ty);
ea8adc8c 332 }
1a4d82fc
JJ
333}
334
dc9dc135 335impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
fc512014
XL
336 fn visit_min_capture_map(&mut self) {
337 let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher(
338 self.fcx.typeck_results.borrow().closure_min_captures.len(),
339 Default::default(),
340 );
341 for (closure_def_id, root_min_captures) in
342 self.fcx.typeck_results.borrow().closure_min_captures.iter()
343 {
344 let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher(
345 root_min_captures.len(),
346 Default::default(),
347 );
348 for (var_hir_id, min_list) in root_min_captures.iter() {
349 let min_list_wb = min_list
350 .iter()
351 .map(|captured_place| {
6a06907d
XL
352 let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| {
353 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local())
354 });
fc512014
XL
355
356 self.resolve(captured_place.clone(), &locatable)
357 })
358 .collect();
359 root_var_map_wb.insert(*var_hir_id, min_list_wb);
360 }
361 min_captures_wb.insert(*closure_def_id, root_var_map_wb);
362 }
363
364 self.typeck_results.closure_min_captures = min_captures_wb;
365 }
366
6a06907d
XL
367 fn visit_fake_reads_map(&mut self) {
368 let mut resolved_closure_fake_reads: FxHashMap<
369 DefId,
370 Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>,
371 > = Default::default();
372 for (closure_def_id, fake_reads) in
373 self.fcx.typeck_results.borrow().closure_fake_reads.iter()
374 {
375 let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new();
376 for (place, cause, hir_id) in fake_reads.iter() {
377 let locatable =
378 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
379
380 let resolved_fake_read = self.resolve(place.clone(), &locatable);
381 resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id));
382 }
383 resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads);
1a4d82fc 384 }
6a06907d 385 self.typeck_results.closure_fake_reads = resolved_closure_fake_reads;
1a4d82fc
JJ
386 }
387
8bb4bdeb 388 fn visit_closures(&mut self) {
3dfed10e
XL
389 let fcx_typeck_results = self.fcx.typeck_results.borrow();
390 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
391 let common_hir_owner = fcx_typeck_results.hir_owner;
3b2f2976 392
5869c6ff
XL
393 for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() {
394 let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id };
395 let place_span = origin.0;
396 let place = self.resolve(origin.1.clone(), &place_span);
397 self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place));
1a4d82fc
JJ
398 }
399 }
400
532ac7d7 401 fn visit_coercion_casts(&mut self) {
3dfed10e
XL
402 let fcx_typeck_results = self.fcx.typeck_results.borrow();
403 let fcx_coercion_casts = fcx_typeck_results.coercion_casts();
404 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
3b2f2976 405
532ac7d7 406 for local_id in fcx_coercion_casts {
3dfed10e 407 self.typeck_results.set_coercion_cast(*local_id);
3b2f2976 408 }
8bb4bdeb
XL
409 }
410
0531ce1d 411 fn visit_user_provided_tys(&mut self) {
3dfed10e
XL
412 let fcx_typeck_results = self.fcx.typeck_results.borrow();
413 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
414 let common_hir_owner = fcx_typeck_results.hir_owner;
0531ce1d 415
0731742a 416 let mut errors_buffer = Vec::new();
3dfed10e 417 for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() {
ba9703b0 418 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
0531ce1d 419
ba9703b0
XL
420 if cfg!(debug_assertions) && c_ty.needs_infer() {
421 span_bug!(
422 hir_id.to_span(self.fcx.tcx),
423 "writeback: `{:?}` has inference variables",
424 c_ty
425 );
0531ce1d
XL
426 };
427
3dfed10e 428 self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty);
0731742a 429
9fa01778 430 if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
0731742a
XL
431 if self.rustc_dump_user_substs {
432 // This is a unit-testing mechanism.
dc9dc135 433 let span = self.tcx().hir().span(hir_id);
0731742a
XL
434 // We need to buffer the errors in order to guarantee a consistent
435 // order when emitting them.
dfeec247
XL
436 let err = self
437 .tcx()
438 .sess
439 .struct_span_err(span, &format!("user substs: {:?}", user_substs));
0731742a
XL
440 err.buffer(&mut errors_buffer);
441 }
442 }
443 }
444
445 if !errors_buffer.is_empty() {
446 errors_buffer.sort_by_key(|diag| diag.span.primary_span());
447 for diag in errors_buffer.drain(..) {
e1599b0c 448 self.tcx().sess.diagnostic().emit_diagnostic(&diag);
0731742a 449 }
0531ce1d
XL
450 }
451 }
452
0bf4aa26 453 fn visit_user_provided_sigs(&mut self) {
3dfed10e
XL
454 let fcx_typeck_results = self.fcx.typeck_results.borrow();
455 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
0bf4aa26 456
3dfed10e 457 for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() {
ba9703b0 458 if cfg!(debug_assertions) && c_sig.needs_infer() {
0bf4aa26 459 span_bug!(
0731742a 460 self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
ba9703b0 461 "writeback: `{:?}` has inference variables",
0bf4aa26
XL
462 c_sig
463 );
464 };
465
3dfed10e 466 self.typeck_results.user_provided_sigs.insert(def_id, *c_sig);
0bf4aa26
XL
467 }
468 }
469
e1599b0c 470 fn visit_generator_interior_types(&mut self) {
3dfed10e
XL
471 let fcx_typeck_results = self.fcx.typeck_results.borrow();
472 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
473 self.typeck_results.generator_interior_types =
474 fcx_typeck_results.generator_interior_types.clone();
e1599b0c
XL
475 }
476
b7449926
XL
477 fn visit_opaque_types(&mut self, span: Span) {
478 for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
3dfed10e 479 let hir_id = self.tcx().hir().local_def_id_to_hir_id(def_id.expect_local());
fc512014 480 let instantiated_ty = self.resolve(opaque_defn.concrete_ty, &hir_id);
8faf50e0 481
48663c56
XL
482 debug_assert!(!instantiated_ty.has_escaping_bound_vars());
483
416331ca
XL
484 // Prevent:
485 // * `fn foo<T>() -> Foo<T>`
486 // * `fn foo<T: Bound + Other>() -> Foo<T>`
487 // from being defining.
8faf50e0 488
416331ca
XL
489 // Also replace all generic params with the ones from the opaque type
490 // definition so that
491 // ```rust
492 // type Foo<T> = impl Baz + 'static;
493 // fn foo<U>() -> Foo<U> { .. }
494 // ```
495 // figures out the concrete type with `U`, but the stored type is with `T`.
496 let definition_ty = self.fcx.infer_opaque_definition_from_instantiation(
dfeec247 497 def_id,
74b04a01 498 opaque_defn.substs,
dfeec247
XL
499 instantiated_ty,
500 span,
501 );
416331ca
XL
502
503 let mut skip_add = false;
8faf50e0 504
1b1a35ee 505 if let ty::Opaque(defin_ty_def_id, _substs) = *definition_ty.kind() {
6a06907d
XL
506 if let hir::OpaqueTyOrigin::Misc | hir::OpaqueTyOrigin::TyAlias = opaque_defn.origin
507 {
e74abb32 508 if def_id == defin_ty_def_id {
60c5eb7d
XL
509 debug!(
510 "skipping adding concrete definition for opaque type {:?} {:?}",
511 opaque_defn, defin_ty_def_id
512 );
e74abb32
XL
513 skip_add = true;
514 }
b7449926
XL
515 }
516 }
517
ba9703b0 518 if !opaque_defn.substs.needs_infer() {
416331ca
XL
519 // We only want to add an entry into `concrete_opaque_types`
520 // if we actually found a defining usage of this opaque type.
521 // Otherwise, we do nothing - we'll either find a defining usage
522 // in some other location, or we'll end up emitting an error due
523 // to the lack of defining usage
524 if !skip_add {
525 let new = ty::ResolvedOpaqueTy {
526 concrete_type: definition_ty,
527 substs: opaque_defn.substs,
528 };
529
3dfed10e 530 let old = self.typeck_results.concrete_opaque_types.insert(def_id, new);
416331ca
XL
531 if let Some(old) = old {
532 if old.concrete_type != definition_ty || old.substs != opaque_defn.substs {
533 span_bug!(
534 span,
60c5eb7d
XL
535 "`visit_opaque_types` tried to write different types for the same \
536 opaque type: {:?}, {:?}, {:?}, {:?}",
416331ca
XL
537 def_id,
538 definition_ty,
539 opaque_defn,
540 old,
541 );
542 }
48663c56 543 }
94b46f34 544 }
48663c56 545 } else {
ba9703b0 546 self.tcx().sess.delay_span_bug(span, "`opaque_defn` has inference variables");
94b46f34 547 }
5bcae85e
SL
548 }
549 }
550
532ac7d7 551 fn visit_field_id(&mut self, hir_id: hir::HirId) {
3dfed10e
XL
552 if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
553 {
554 self.typeck_results.field_indices_mut().insert(hir_id, index);
83c7162d
XL
555 }
556 }
557
3b2f2976 558 fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
b7449926 559 // Export associated path extensions and method resolutions.
3dfed10e
XL
560 if let Some(def) =
561 self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
562 {
563 self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
476ff2be
SL
564 }
565
cc61c64b 566 // Resolve any borrowings for the node with id `node_id`
3b2f2976 567 self.visit_adjustments(span, hir_id);
1a4d82fc 568
cc61c64b 569 // Resolve the type of the node with id `node_id`
3b2f2976 570 let n_ty = self.fcx.node_ty(hir_id);
fc512014 571 let n_ty = self.resolve(n_ty, &span);
3dfed10e 572 self.write_ty_to_typeck_results(hir_id, n_ty);
416331ca 573 debug!("node {:?} has type {:?}", hir_id, n_ty);
1a4d82fc
JJ
574
575 // Resolve any substitutions
3dfed10e 576 if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) {
fc512014 577 let substs = self.resolve(substs, &span);
3b2f2976 578 debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
a1dfa0c6 579 assert!(!substs.needs_infer() && !substs.has_placeholders());
3dfed10e 580 self.typeck_results.node_substs_mut().insert(hir_id, substs);
7cac9316 581 }
1a4d82fc
JJ
582 }
583
3b2f2976 584 fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
3dfed10e 585 let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
7cac9316 586 match adjustment {
1a4d82fc 587 None => {
416331ca 588 debug!("no adjustments for node {:?}", hir_id);
1a4d82fc
JJ
589 }
590
591 Some(adjustment) => {
fc512014 592 let resolved_adjustment = self.resolve(adjustment, &span);
dfeec247 593 debug!("adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
3dfed10e 594 self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
1a4d82fc
JJ
595 }
596 }
597 }
598
ea8adc8c 599 fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
3dfed10e 600 let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
ea8adc8c
XL
601 match adjustment {
602 None => {
416331ca 603 debug!("no pat_adjustments for node {:?}", hir_id);
ea8adc8c
XL
604 }
605
606 Some(adjustment) => {
fc512014 607 let resolved_adjustment = self.resolve(adjustment, &span);
dfeec247 608 debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment);
3dfed10e 609 self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
ea8adc8c
XL
610 }
611 }
612 }
613
32a655c1 614 fn visit_liberated_fn_sigs(&mut self) {
3dfed10e
XL
615 let fcx_typeck_results = self.fcx.typeck_results.borrow();
616 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
617 let common_hir_owner = fcx_typeck_results.hir_owner;
3b2f2976 618
fc512014 619 for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() {
ba9703b0 620 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
3b2f2976 621 let fn_sig = self.resolve(fn_sig, &hir_id);
3dfed10e 622 self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
92a42be0
SL
623 }
624 }
625
32a655c1 626 fn visit_fru_field_types(&mut self) {
3dfed10e
XL
627 let fcx_typeck_results = self.fcx.typeck_results.borrow();
628 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
629 let common_hir_owner = fcx_typeck_results.hir_owner;
3b2f2976 630
3dfed10e 631 for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() {
ba9703b0 632 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
fc512014 633 let ftys = self.resolve(ftys.clone(), &hir_id);
3dfed10e 634 self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
7453a54e
SL
635 }
636 }
637
fc512014 638 fn resolve<T>(&mut self, x: T, span: &dyn Locatable) -> T
ff7c6d11 639 where
dc9dc135 640 T: TypeFoldable<'tcx>,
a7813a04 641 {
ba9703b0
XL
642 let mut resolver = Resolver::new(self.fcx, span, self.body);
643 let x = x.fold_with(&mut resolver);
644 if cfg!(debug_assertions) && x.needs_infer() {
645 span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x);
646 }
647
648 // We may have introduced e.g. `ty::Error`, if inference failed, make sure
3dfed10e
XL
649 // to mark the `TypeckResults` as tainted in that case, so that downstream
650 // users of the typeck results don't produce extra errors, or worse, ICEs.
ba9703b0
XL
651 if resolver.replaced_with_error {
652 // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted.
3dfed10e 653 self.typeck_results.tainted_by_errors = Some(ErrorReported);
a7813a04 654 }
ba9703b0 655
dc9dc135 656 x
1a4d82fc
JJ
657 }
658}
659
5869c6ff 660crate trait Locatable {
dc9dc135 661 fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
1a4d82fc
JJ
662}
663
cc61c64b 664impl Locatable for Span {
dc9dc135 665 fn to_span(&self, _: TyCtxt<'_>) -> Span {
ff7c6d11
XL
666 *self
667 }
cc61c64b
XL
668}
669
3b2f2976 670impl Locatable for hir::HirId {
dc9dc135
XL
671 fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
672 tcx.hir().span(*self)
3b2f2976
XL
673 }
674}
675
ba9703b0
XL
676/// The Resolver. This is the type folding engine that detects
677/// unresolved types and so forth.
5869c6ff 678crate struct Resolver<'cx, 'tcx> {
dc9dc135
XL
679 tcx: TyCtxt<'tcx>,
680 infcx: &'cx InferCtxt<'cx, 'tcx>,
8faf50e0 681 span: &'cx dyn Locatable,
dfeec247 682 body: &'tcx hir::Body<'tcx>,
ba9703b0
XL
683
684 /// Set to `true` if any `Ty` or `ty::Const` had to be replaced with an `Error`.
685 replaced_with_error: bool,
1a4d82fc
JJ
686}
687
dc9dc135 688impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
5869c6ff 689 crate fn new(
dc9dc135 690 fcx: &'cx FnCtxt<'cx, 'tcx>,
8faf50e0 691 span: &'cx dyn Locatable,
dfeec247 692 body: &'tcx hir::Body<'tcx>,
dc9dc135 693 ) -> Resolver<'cx, 'tcx> {
ba9703b0 694 Resolver { tcx: fcx.tcx, infcx: fcx, span, body, replaced_with_error: false }
1a4d82fc
JJ
695 }
696
f9f354fc 697 fn report_type_error(&self, t: Ty<'tcx>) {
1a4d82fc 698 if !self.tcx.sess.has_errors() {
ff7c6d11 699 self.infcx
1b1a35ee
XL
700 .emit_inference_failure_err(
701 Some(self.body.id()),
702 self.span.to_span(self.tcx),
703 t.into(),
5869c6ff 704 vec![],
1b1a35ee
XL
705 E0282,
706 )
b7449926 707 .emit();
1a4d82fc
JJ
708 }
709 }
f9f354fc
XL
710
711 fn report_const_error(&self, c: &'tcx ty::Const<'tcx>) {
712 if !self.tcx.sess.has_errors() {
713 self.infcx
1b1a35ee 714 .emit_inference_failure_err(
f9f354fc
XL
715 Some(self.body.id()),
716 self.span.to_span(self.tcx),
1b1a35ee 717 c.into(),
5869c6ff 718 vec![],
f9f354fc
XL
719 E0282,
720 )
721 .emit();
722 }
723 }
1a4d82fc
JJ
724}
725
dc9dc135
XL
726impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
727 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
1a4d82fc
JJ
728 self.tcx
729 }
730
731 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
fc512014
XL
732 match self.infcx.fully_resolve(t) {
733 Ok(t) => self.infcx.tcx.erase_regions(t),
cc61c64b 734 Err(_) => {
dfeec247 735 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t);
f9f354fc 736 self.report_type_error(t);
ba9703b0 737 self.replaced_with_error = true;
f035d41b 738 self.tcx().ty_error()
1a4d82fc
JJ
739 }
740 }
741 }
742
7cac9316 743 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
ba9703b0
XL
744 debug_assert!(!r.is_late_bound(), "Should not be resolving bound region.");
745 self.tcx.lifetimes.re_erased
48663c56
XL
746 }
747
748 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
fc512014
XL
749 match self.infcx.fully_resolve(ct) {
750 Ok(ct) => self.infcx.tcx.erase_regions(ct),
48663c56 751 Err(_) => {
dfeec247 752 debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct);
f9f354fc 753 self.report_const_error(ct);
ba9703b0 754 self.replaced_with_error = true;
f035d41b 755 self.tcx().const_error(ct.ty)
48663c56
XL
756 }
757 }
1a4d82fc
JJ
758 }
759}
760
761///////////////////////////////////////////////////////////////////////////
762// During type check, we store promises with the result of trait
763// lookup rather than the actual results (because the results are not
764// necessarily available immediately). These routines unwind the
765// promises. It is expected that we will have already reported any
766// errors that may be encountered, so if the promises store an error,
767// a dummy result is returned.