]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
Rollup merge of #60354 - Centril:cleanup-declare-features-accepted, r=oli-obk
[rust.git] / src / librustc_typeck / check / writeback.rs
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.
4
5 use crate::check::FnCtxt;
6 use errors::DiagnosticBuilder;
7 use rustc::hir;
8 use rustc::hir::def_id::{DefId, DefIndex};
9 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
10 use rustc::infer::InferCtxt;
11 use rustc::ty::adjustment::{Adjust, Adjustment, PointerCast};
12 use rustc::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder};
13 use rustc::ty::subst::UnpackedKind;
14 use rustc::ty::{self, Ty, TyCtxt};
15 use rustc::util::nodemap::DefIdSet;
16 use rustc_data_structures::sync::Lrc;
17 use std::mem;
18 use syntax_pos::Span;
19
20 ///////////////////////////////////////////////////////////////////////////
21 // Entry point
22
23 // During type inference, partially inferred types are
24 // represented using Type variables (ty::Infer). These don't appear in
25 // the final TypeckTables since all of the types should have been
26 // inferred once typeck_tables_of is done.
27 // When type inference is running however, having to update the typeck
28 // tables every time a new type is inferred would be unreasonably slow,
29 // so instead all of the replacement happens at the end in
30 // resolve_type_vars_in_body, which creates a new TypeTables which
31 // doesn't contain any inference types.
32 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
33     pub fn resolve_type_vars_in_body(&self, body: &'gcx hir::Body) -> &'gcx ty::TypeckTables<'gcx> {
34         let item_id = self.tcx.hir().body_owner(body.id());
35         let item_def_id = self.tcx.hir().local_def_id(item_id);
36
37         // This attribute causes us to dump some writeback information
38         // in the form of errors, which is used for unit tests.
39         let rustc_dump_user_substs = self.tcx.has_attr(item_def_id, "rustc_dump_user_substs");
40
41         let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
42         for arg in &body.arguments {
43             wbcx.visit_node_id(arg.pat.span, arg.hir_id);
44         }
45         // Type only exists for constants and statics, not functions.
46         match self.tcx.hir().body_owner_kind(item_id) {
47             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => {
48                 let item_hir_id = self.tcx.hir().node_to_hir_id(item_id);
49                 wbcx.visit_node_id(body.value.span, item_hir_id);
50             }
51             hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (),
52         }
53         wbcx.visit_body(body);
54         wbcx.visit_upvar_capture_map();
55         wbcx.visit_upvar_list_map();
56         wbcx.visit_closures();
57         wbcx.visit_liberated_fn_sigs();
58         wbcx.visit_fru_field_types();
59         wbcx.visit_opaque_types(body.value.span);
60         wbcx.visit_coercion_casts();
61         wbcx.visit_free_region_map();
62         wbcx.visit_user_provided_tys();
63         wbcx.visit_user_provided_sigs();
64
65         let used_trait_imports = mem::replace(
66             &mut self.tables.borrow_mut().used_trait_imports,
67             Lrc::new(DefIdSet::default()),
68         );
69         debug!(
70             "used_trait_imports({:?}) = {:?}",
71             item_def_id, used_trait_imports
72         );
73         wbcx.tables.used_trait_imports = used_trait_imports;
74
75         wbcx.tables.tainted_by_errors = self.is_tainted_by_errors();
76
77         debug!(
78             "writeback: tables for {:?} are {:#?}",
79             item_def_id, wbcx.tables
80         );
81
82         self.tcx.alloc_tables(wbcx.tables)
83     }
84 }
85
86 ///////////////////////////////////////////////////////////////////////////
87 // The Writeback context. This visitor walks the AST, checking the
88 // fn-specific tables to find references to types or regions. It
89 // resolves those regions to remove inference variables and writes the
90 // final result back into the master tables in the tcx. Here and
91 // there, it applies a few ad-hoc checks that were not convenient to
92 // do elsewhere.
93
94 struct WritebackCx<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
95     fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
96
97     tables: ty::TypeckTables<'gcx>,
98
99     body: &'gcx hir::Body,
100
101     rustc_dump_user_substs: bool,
102 }
103
104 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
105     fn new(
106         fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
107         body: &'gcx hir::Body,
108         rustc_dump_user_substs: bool,
109     ) -> WritebackCx<'cx, 'gcx, 'tcx> {
110         let owner = body.id().hir_id;
111
112         WritebackCx {
113             fcx,
114             tables: ty::TypeckTables::empty(Some(DefId::local(owner.owner))),
115             body,
116             rustc_dump_user_substs,
117         }
118     }
119
120     fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
121         self.fcx.tcx
122     }
123
124     fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'gcx>) {
125         debug!("write_ty_to_tables({:?}, {:?})", hir_id, ty);
126         assert!(!ty.needs_infer() && !ty.has_placeholders());
127         self.tables.node_types_mut().insert(hir_id, ty);
128     }
129
130     // Hacky hack: During type-checking, we treat *all* operators
131     // as potentially overloaded. But then, during writeback, if
132     // we observe that something like `a+b` is (known to be)
133     // operating on scalars, we clear the overload.
134     fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr) {
135         match e.node {
136             hir::ExprKind::Unary(hir::UnNeg, ref inner)
137             | hir::ExprKind::Unary(hir::UnNot, ref inner) => {
138                 let inner_ty = self.fcx.node_ty(inner.hir_id);
139                 let inner_ty = self.fcx.resolve_type_vars_if_possible(&inner_ty);
140
141                 if inner_ty.is_scalar() {
142                     let mut tables = self.fcx.tables.borrow_mut();
143                     tables.type_dependent_defs_mut().remove(e.hir_id);
144                     tables.node_substs_mut().remove(e.hir_id);
145                 }
146             }
147             hir::ExprKind::Binary(ref op, ref lhs, ref rhs)
148             | hir::ExprKind::AssignOp(ref op, ref lhs, ref rhs) => {
149                 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
150                 let lhs_ty = self.fcx.resolve_type_vars_if_possible(&lhs_ty);
151
152                 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
153                 let rhs_ty = self.fcx.resolve_type_vars_if_possible(&rhs_ty);
154
155                 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
156                     let mut tables = self.fcx.tables.borrow_mut();
157                     tables.type_dependent_defs_mut().remove(e.hir_id);
158                     tables.node_substs_mut().remove(e.hir_id);
159
160                     match e.node {
161                         hir::ExprKind::Binary(..) => {
162                             if !op.node.is_by_value() {
163                                 let mut adjustments = tables.adjustments_mut();
164                                 adjustments.get_mut(lhs.hir_id).map(|a| a.pop());
165                                 adjustments.get_mut(rhs.hir_id).map(|a| a.pop());
166                             }
167                         }
168                         hir::ExprKind::AssignOp(..) => {
169                             tables
170                                 .adjustments_mut()
171                                 .get_mut(lhs.hir_id)
172                                 .map(|a| a.pop());
173                         }
174                         _ => {}
175                     }
176                 }
177             }
178             _ => {}
179         }
180     }
181
182     // Similar to operators, indexing is always assumed to be overloaded
183     // Here, correct cases where an indexing expression can be simplified
184     // to use builtin indexing because the index type is known to be
185     // usize-ish
186     fn fix_index_builtin_expr(&mut self, e: &hir::Expr) {
187         if let hir::ExprKind::Index(ref base, ref index) = e.node {
188             let mut tables = self.fcx.tables.borrow_mut();
189
190             // All valid indexing looks like this; might encounter non-valid indexes at this point
191             if let ty::Ref(_, base_ty, _) = tables.expr_ty_adjusted(&base).sty {
192                 let index_ty = tables.expr_ty_adjusted(&index);
193                 let index_ty = self.fcx.resolve_type_vars_if_possible(&index_ty);
194
195                 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
196                     // Remove the method call record
197                     tables.type_dependent_defs_mut().remove(e.hir_id);
198                     tables.node_substs_mut().remove(e.hir_id);
199
200                     tables.adjustments_mut().get_mut(base.hir_id).map(|a| {
201                         // Discard the need for a mutable borrow
202                         match a.pop() {
203                             // Extra adjustment made when indexing causes a drop
204                             // of size information - we need to get rid of it
205                             // Since this is "after" the other adjustment to be
206                             // discarded, we do an extra `pop()`
207                             Some(Adjustment {
208                                 kind: Adjust::Pointer(PointerCast::Unsize),
209                                 ..
210                             }) => {
211                                 // So the borrow discard actually happens here
212                                 a.pop();
213                             }
214                             _ => {}
215                         }
216                     });
217                 }
218             }
219         }
220     }
221 }
222
223 ///////////////////////////////////////////////////////////////////////////
224 // Impl of Visitor for Resolver
225 //
226 // This is the master code which walks the AST. It delegates most of
227 // the heavy lifting to the generic visit and resolve functions
228 // below. In general, a function is made into a `visitor` if it must
229 // traffic in node-ids or update tables in the type context etc.
230
231 impl<'cx, 'gcx, 'tcx> Visitor<'gcx> for WritebackCx<'cx, 'gcx, 'tcx> {
232     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
233         NestedVisitorMap::None
234     }
235
236     fn visit_expr(&mut self, e: &'gcx hir::Expr) {
237         self.fix_scalar_builtin_expr(e);
238         self.fix_index_builtin_expr(e);
239
240         self.visit_node_id(e.span, e.hir_id);
241
242         match e.node {
243             hir::ExprKind::Closure(_, _, body, _, _) => {
244                 let body = self.fcx.tcx.hir().body(body);
245                 for arg in &body.arguments {
246                     self.visit_node_id(e.span, arg.hir_id);
247                 }
248
249                 self.visit_body(body);
250             }
251             hir::ExprKind::Struct(_, ref fields, _) => {
252                 for field in fields {
253                     self.visit_field_id(field.hir_id);
254                 }
255             }
256             hir::ExprKind::Field(..) => {
257                 self.visit_field_id(e.hir_id);
258             }
259             _ => {}
260         }
261
262         intravisit::walk_expr(self, e);
263     }
264
265     fn visit_block(&mut self, b: &'gcx hir::Block) {
266         self.visit_node_id(b.span, b.hir_id);
267         intravisit::walk_block(self, b);
268     }
269
270     fn visit_pat(&mut self, p: &'gcx hir::Pat) {
271         match p.node {
272             hir::PatKind::Binding(..) => {
273                 if let Some(&bm) = self.fcx.tables.borrow().pat_binding_modes().get(p.hir_id) {
274                     self.tables.pat_binding_modes_mut().insert(p.hir_id, bm);
275                 } else {
276                     self.tcx()
277                         .sess
278                         .delay_span_bug(p.span, "missing binding mode");
279                 }
280             }
281             hir::PatKind::Struct(_, ref fields, _) => {
282                 for field in fields {
283                     self.visit_field_id(field.node.hir_id);
284                 }
285             }
286             _ => {}
287         };
288
289         self.visit_pat_adjustments(p.span, p.hir_id);
290
291         self.visit_node_id(p.span, p.hir_id);
292         intravisit::walk_pat(self, p);
293     }
294
295     fn visit_local(&mut self, l: &'gcx hir::Local) {
296         intravisit::walk_local(self, l);
297         let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
298         let var_ty = self.resolve(&var_ty, &l.span);
299         self.write_ty_to_tables(l.hir_id, var_ty);
300     }
301
302     fn visit_ty(&mut self, hir_ty: &'gcx hir::Ty) {
303         intravisit::walk_ty(self, hir_ty);
304         let ty = self.fcx.node_ty(hir_ty.hir_id);
305         let ty = self.resolve(&ty, &hir_ty.span);
306         self.write_ty_to_tables(hir_ty.hir_id, ty);
307     }
308
309     fn visit_argument_source(&mut self, s: &'gcx hir::ArgSource) {
310         match s {
311             // Don't visit the pattern in `ArgSource::AsyncFn`, it contains a pattern which has
312             // a `NodeId` w/out a type, as it is only used for getting the name of the original
313             // pattern for diagnostics where only an `hir::Arg` is present.
314             hir::ArgSource::AsyncFn(..) => {},
315             _ => intravisit::walk_argument_source(self, s),
316         }
317     }
318 }
319
320 impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
321     fn visit_upvar_capture_map(&mut self) {
322         for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() {
323             let new_upvar_capture = match *upvar_capture {
324                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
325                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
326                     let r = upvar_borrow.region;
327                     let r = self.resolve(&r, &upvar_id.var_path.hir_id);
328                     ty::UpvarCapture::ByRef(ty::UpvarBorrow {
329                         kind: upvar_borrow.kind,
330                         region: r,
331                     })
332                 }
333             };
334             debug!(
335                 "Upvar capture for {:?} resolved to {:?}",
336                 upvar_id, new_upvar_capture
337             );
338             self.tables
339                 .upvar_capture_map
340                 .insert(*upvar_id, new_upvar_capture);
341         }
342     }
343
344     /// Runs through the function context's upvar list map and adds the same to
345     /// the TypeckTables. upvarlist is a hashmap of the list of upvars referred
346     /// to in a closure..
347     fn visit_upvar_list_map(&mut self) {
348         for (closure_def_id, upvar_list) in self.fcx.tables.borrow().upvar_list.iter() {
349             debug!(
350                 "UpvarIDs captured by closure {:?} are: {:?}",
351                 closure_def_id, upvar_list
352             );
353             self.tables
354                 .upvar_list
355                 .insert(*closure_def_id, upvar_list.to_vec());
356         }
357     }
358
359     fn visit_closures(&mut self) {
360         let fcx_tables = self.fcx.tables.borrow();
361         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
362         let common_local_id_root = fcx_tables.local_id_root.unwrap();
363
364         for (&id, &origin) in fcx_tables.closure_kind_origins().iter() {
365             let hir_id = hir::HirId {
366                 owner: common_local_id_root.index,
367                 local_id: id,
368             };
369             self.tables
370                 .closure_kind_origins_mut()
371                 .insert(hir_id, origin);
372         }
373     }
374
375     fn visit_coercion_casts(&mut self) {
376         let fcx_tables = self.fcx.tables.borrow();
377         let fcx_coercion_casts = fcx_tables.coercion_casts();
378         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
379
380         for local_id in fcx_coercion_casts {
381             self.tables.set_coercion_cast(*local_id);
382         }
383     }
384
385     fn visit_free_region_map(&mut self) {
386         let free_region_map = self.tcx()
387             .lift_to_global(&self.fcx.tables.borrow().free_region_map);
388         let free_region_map = free_region_map.expect("all regions in free-region-map are global");
389         self.tables.free_region_map = free_region_map;
390     }
391
392     fn visit_user_provided_tys(&mut self) {
393         let fcx_tables = self.fcx.tables.borrow();
394         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
395         let common_local_id_root = fcx_tables.local_id_root.unwrap();
396
397         let mut errors_buffer = Vec::new();
398         for (&local_id, c_ty) in fcx_tables.user_provided_types().iter() {
399             let hir_id = hir::HirId {
400                 owner: common_local_id_root.index,
401                 local_id,
402             };
403
404             let c_ty = if let Some(c_ty) = self.tcx().lift_to_global(c_ty) {
405                 c_ty
406             } else {
407                 span_bug!(
408                     hir_id.to_span(self.fcx.tcx),
409                     "writeback: `{:?}` missing from the global type context",
410                     c_ty
411                 );
412             };
413
414             self.tables
415                 .user_provided_types_mut()
416                 .insert(hir_id, c_ty.clone());
417
418             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
419                 if self.rustc_dump_user_substs {
420                     // This is a unit-testing mechanism.
421                     let span = self.tcx().hir().span_by_hir_id(hir_id);
422                     // We need to buffer the errors in order to guarantee a consistent
423                     // order when emitting them.
424                     let err = self.tcx().sess.struct_span_err(
425                         span,
426                         &format!("user substs: {:?}", user_substs)
427                     );
428                     err.buffer(&mut errors_buffer);
429                 }
430             }
431         }
432
433         if !errors_buffer.is_empty() {
434             errors_buffer.sort_by_key(|diag| diag.span.primary_span());
435             for diag in errors_buffer.drain(..) {
436                 DiagnosticBuilder::new_diagnostic(self.tcx().sess.diagnostic(), diag).emit();
437             }
438         }
439     }
440
441     fn visit_user_provided_sigs(&mut self) {
442         let fcx_tables = self.fcx.tables.borrow();
443         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
444
445         for (&def_id, c_sig) in fcx_tables.user_provided_sigs.iter() {
446             let c_sig = if let Some(c_sig) = self.tcx().lift_to_global(c_sig) {
447                 c_sig
448             } else {
449                 span_bug!(
450                     self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
451                     "writeback: `{:?}` missing from the global type context",
452                     c_sig
453                 );
454             };
455
456             self.tables
457                 .user_provided_sigs
458                 .insert(def_id, c_sig.clone());
459         }
460     }
461
462     fn visit_opaque_types(&mut self, span: Span) {
463         for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
464             let hir_id = self.tcx().hir().as_local_hir_id(def_id).unwrap();
465             let instantiated_ty = self.resolve(&opaque_defn.concrete_ty, &hir_id);
466
467             let generics = self.tcx().generics_of(def_id);
468
469             let definition_ty = if generics.parent.is_some() {
470                 // impl trait
471                 self.fcx.infer_opaque_definition_from_instantiation(
472                     def_id,
473                     opaque_defn,
474                     instantiated_ty,
475                 )
476             } else {
477                 // prevent
478                 // * `fn foo<T>() -> Foo<T>`
479                 // * `fn foo<T: Bound + Other>() -> Foo<T>`
480                 // from being defining
481
482                 // Also replace all generic params with the ones from the existential type
483                 // definition so
484                 // ```rust
485                 // existential type Foo<T>: 'static;
486                 // fn foo<U>() -> Foo<U> { .. }
487                 // ```
488                 // figures out the concrete type with `U`, but the stored type is with `T`
489                 instantiated_ty.fold_with(&mut BottomUpFolder {
490                     tcx: self.tcx().global_tcx(),
491                     fldop: |ty| {
492                         trace!("checking type {:?}", ty);
493                         // find a type parameter
494                         if let ty::Param(..) = ty.sty {
495                             // look it up in the substitution list
496                             assert_eq!(opaque_defn.substs.len(), generics.params.len());
497                             for (subst, param) in opaque_defn.substs.iter().zip(&generics.params) {
498                                 if let UnpackedKind::Type(subst) = subst.unpack() {
499                                     if subst == ty {
500                                         // found it in the substitution list, replace with the
501                                         // parameter from the existential type
502                                         return self.tcx()
503                                             .global_tcx()
504                                             .mk_ty_param(param.index, param.name);
505                                     }
506                                 }
507                             }
508                             self.tcx()
509                                 .sess
510                                 .struct_span_err(
511                                     span,
512                                     &format!(
513                                         "type parameter `{}` is part of concrete type but not used \
514                                          in parameter list for existential type",
515                                         ty,
516                                     ),
517                                 )
518                                 .emit();
519                             return self.tcx().types.err;
520                         }
521                         ty
522                     },
523                     reg_op: |region| {
524                         match region {
525                             // ignore static regions
526                             ty::ReStatic => region,
527                             _ => {
528                                 trace!("checking {:?}", region);
529                                 for (subst, p) in opaque_defn.substs.iter().zip(&generics.params) {
530                                     if let UnpackedKind::Lifetime(subst) = subst.unpack() {
531                                         if subst == region {
532                                             // found it in the substitution list, replace with the
533                                             // parameter from the existential type
534                                             let reg = ty::EarlyBoundRegion {
535                                                 def_id: p.def_id,
536                                                 index: p.index,
537                                                 name: p.name,
538                                             };
539                                             trace!("replace {:?} with {:?}", region, reg);
540                                             return self.tcx()
541                                                 .global_tcx()
542                                                 .mk_region(ty::ReEarlyBound(reg));
543                                         }
544                                     }
545                                 }
546                                 trace!("opaque_defn: {:#?}", opaque_defn);
547                                 trace!("generics: {:#?}", generics);
548                                 self.tcx()
549                                     .sess
550                                     .struct_span_err(
551                                         span,
552                                         "non-defining existential type use in defining scope",
553                                     )
554                                     .span_label(
555                                         span,
556                                         format!(
557                                             "lifetime `{}` is part of concrete type but not used \
558                                              in parameter list of existential type",
559                                             region,
560                                         ),
561                                     )
562                                     .emit();
563                                 self.tcx().global_tcx().mk_region(ty::ReStatic)
564                             }
565                         }
566                     },
567                 })
568             };
569
570             if let ty::Opaque(defin_ty_def_id, _substs) = definition_ty.sty {
571                 if def_id == defin_ty_def_id {
572                     // Concrete type resolved to the existential type itself
573                     // Force a cycle error
574                     // FIXME(oli-obk): we could just not insert it into `concrete_existential_types`
575                     // which simply would make this use not a defining use.
576                     self.tcx().at(span).type_of(defin_ty_def_id);
577                 }
578             }
579
580             let new = ty::ResolvedOpaqueTy {
581                 concrete_type: definition_ty,
582                 substs: self.tcx().lift_to_global(&opaque_defn.substs).unwrap(),
583             };
584
585             let old = self.tables
586                 .concrete_existential_types
587                 .insert(def_id, new);
588             if let Some(old) = old {
589                 if old.concrete_type != definition_ty || old.substs != opaque_defn.substs {
590                     span_bug!(
591                         span,
592                         "visit_opaque_types tried to write \
593                         different types for the same existential type: {:?}, {:?}, {:?}, {:?}",
594                         def_id,
595                         definition_ty,
596                         opaque_defn,
597                         old,
598                     );
599                 }
600             }
601         }
602     }
603
604     fn visit_field_id(&mut self, hir_id: hir::HirId) {
605         if let Some(index) = self.fcx
606             .tables
607             .borrow_mut()
608             .field_indices_mut()
609             .remove(hir_id)
610         {
611             self.tables.field_indices_mut().insert(hir_id, index);
612         }
613     }
614
615     fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
616         // Export associated path extensions and method resolutions.
617         if let Some(def) = self.fcx
618             .tables
619             .borrow_mut()
620             .type_dependent_defs_mut()
621             .remove(hir_id)
622         {
623             self.tables.type_dependent_defs_mut().insert(hir_id, def);
624         }
625
626         // Resolve any borrowings for the node with id `node_id`
627         self.visit_adjustments(span, hir_id);
628
629         // Resolve the type of the node with id `node_id`
630         let n_ty = self.fcx.node_ty(hir_id);
631         let n_ty = self.resolve(&n_ty, &span);
632         self.write_ty_to_tables(hir_id, n_ty);
633         debug!("Node {:?} has type {:?}", hir_id, n_ty);
634
635         // Resolve any substitutions
636         if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) {
637             let substs = self.resolve(&substs, &span);
638             debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
639             assert!(!substs.needs_infer() && !substs.has_placeholders());
640             self.tables.node_substs_mut().insert(hir_id, substs);
641         }
642     }
643
644     fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
645         let adjustment = self.fcx
646             .tables
647             .borrow_mut()
648             .adjustments_mut()
649             .remove(hir_id);
650         match adjustment {
651             None => {
652                 debug!("No adjustments for node {:?}", hir_id);
653             }
654
655             Some(adjustment) => {
656                 let resolved_adjustment = self.resolve(&adjustment, &span);
657                 debug!(
658                     "Adjustments for node {:?}: {:?}",
659                     hir_id, resolved_adjustment
660                 );
661                 self.tables
662                     .adjustments_mut()
663                     .insert(hir_id, resolved_adjustment);
664             }
665         }
666     }
667
668     fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
669         let adjustment = self.fcx
670             .tables
671             .borrow_mut()
672             .pat_adjustments_mut()
673             .remove(hir_id);
674         match adjustment {
675             None => {
676                 debug!("No pat_adjustments for node {:?}", hir_id);
677             }
678
679             Some(adjustment) => {
680                 let resolved_adjustment = self.resolve(&adjustment, &span);
681                 debug!(
682                     "pat_adjustments for node {:?}: {:?}",
683                     hir_id, resolved_adjustment
684                 );
685                 self.tables
686                     .pat_adjustments_mut()
687                     .insert(hir_id, resolved_adjustment);
688             }
689         }
690     }
691
692     fn visit_liberated_fn_sigs(&mut self) {
693         let fcx_tables = self.fcx.tables.borrow();
694         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
695         let common_local_id_root = fcx_tables.local_id_root.unwrap();
696
697         for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() {
698             let hir_id = hir::HirId {
699                 owner: common_local_id_root.index,
700                 local_id,
701             };
702             let fn_sig = self.resolve(fn_sig, &hir_id);
703             self.tables
704                 .liberated_fn_sigs_mut()
705                 .insert(hir_id, fn_sig.clone());
706         }
707     }
708
709     fn visit_fru_field_types(&mut self) {
710         let fcx_tables = self.fcx.tables.borrow();
711         debug_assert_eq!(fcx_tables.local_id_root, self.tables.local_id_root);
712         let common_local_id_root = fcx_tables.local_id_root.unwrap();
713
714         for (&local_id, ftys) in fcx_tables.fru_field_types().iter() {
715             let hir_id = hir::HirId {
716                 owner: common_local_id_root.index,
717                 local_id,
718             };
719             let ftys = self.resolve(ftys, &hir_id);
720             self.tables.fru_field_types_mut().insert(hir_id, ftys);
721         }
722     }
723
724     fn resolve<T>(&self, x: &T, span: &dyn Locatable) -> T::Lifted
725     where
726         T: TypeFoldable<'tcx> + ty::Lift<'gcx>,
727     {
728         let x = x.fold_with(&mut Resolver::new(self.fcx, span, self.body));
729         if let Some(lifted) = self.tcx().lift_to_global(&x) {
730             lifted
731         } else {
732             span_bug!(
733                 span.to_span(self.fcx.tcx),
734                 "writeback: `{:?}` missing from the global type context",
735                 x
736             );
737         }
738     }
739 }
740
741 trait Locatable {
742     fn to_span(&self, tcx: TyCtxt<'_, '_, '_>) -> Span;
743 }
744
745 impl Locatable for Span {
746     fn to_span(&self, _: TyCtxt<'_, '_, '_>) -> Span {
747         *self
748     }
749 }
750
751 impl Locatable for DefIndex {
752     fn to_span(&self, tcx: TyCtxt<'_, '_, '_>) -> Span {
753         let hir_id = tcx.hir().def_index_to_hir_id(*self);
754         tcx.hir().span_by_hir_id(hir_id)
755     }
756 }
757
758 impl Locatable for hir::HirId {
759     fn to_span(&self, tcx: TyCtxt<'_, '_, '_>) -> Span {
760         tcx.hir().span_by_hir_id(*self)
761     }
762 }
763
764 ///////////////////////////////////////////////////////////////////////////
765 // The Resolver. This is the type folding engine that detects
766 // unresolved types and so forth.
767
768 struct Resolver<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
769     tcx: TyCtxt<'cx, 'gcx, 'tcx>,
770     infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
771     span: &'cx dyn Locatable,
772     body: &'gcx hir::Body,
773 }
774
775 impl<'cx, 'gcx, 'tcx> Resolver<'cx, 'gcx, 'tcx> {
776     fn new(
777         fcx: &'cx FnCtxt<'cx, 'gcx, 'tcx>,
778         span: &'cx dyn Locatable,
779         body: &'gcx hir::Body,
780     ) -> Resolver<'cx, 'gcx, 'tcx> {
781         Resolver {
782             tcx: fcx.tcx,
783             infcx: fcx,
784             span,
785             body,
786         }
787     }
788
789     fn report_error(&self, t: Ty<'tcx>) {
790         if !self.tcx.sess.has_errors() {
791             self.infcx
792                 .need_type_info_err(Some(self.body.id()), self.span.to_span(self.tcx), t)
793                 .emit();
794         }
795     }
796 }
797
798 impl<'cx, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for Resolver<'cx, 'gcx, 'tcx> {
799     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
800         self.tcx
801     }
802
803     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
804         match self.infcx.fully_resolve(&t) {
805             Ok(t) => t,
806             Err(_) => {
807                 debug!(
808                     "Resolver::fold_ty: input type `{:?}` not fully resolvable",
809                     t
810                 );
811                 self.report_error(t);
812                 self.tcx().types.err
813             }
814         }
815     }
816
817     // FIXME This should be carefully checked
818     // We could use `self.report_error` but it doesn't accept a ty::Region, right now.
819     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
820         self.infcx.fully_resolve(&r).unwrap_or(self.tcx.types.re_static)
821     }
822 }
823
824 ///////////////////////////////////////////////////////////////////////////
825 // During type check, we store promises with the result of trait
826 // lookup rather than the actual results (because the results are not
827 // necessarily available immediately). These routines unwind the
828 // promises. It is expected that we will have already reported any
829 // errors that may be encountered, so if the promises store an error,
830 // a dummy result is returned.