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