]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
generate GeneratorSubsts from SubstsRef
[rust.git] / src / librustc / ty / print / pretty.rs
1 use crate::hir;
2 use crate::hir::def::{Namespace, DefKind};
3 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
6 use crate::middle::region;
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
8 use crate::ty::subst::{GenericArg, Subst, GenericArgKind};
9 use crate::ty::layout::{Integer, IntegerExt, Size};
10 use crate::mir::interpret::{ConstValue, sign_extend, Scalar, truncate};
11
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_target::spec::abi::Abi;
15 use syntax::ast;
16 use syntax::attr::{SignedInt, UnsignedInt};
17 use syntax::symbol::{kw, InternedString};
18
19 use std::cell::Cell;
20 use std::fmt::{self, Write as _};
21 use std::ops::{Deref, DerefMut};
22
23 // `pretty` is a separate module only for organization.
24 use super::*;
25
26 macro_rules! p {
27     (@write($($data:expr),+)) => {
28         write!(scoped_cx!(), $($data),+)?
29     };
30     (@print($x:expr)) => {
31         scoped_cx!() = $x.print(scoped_cx!())?
32     };
33     (@$method:ident($($arg:expr),*)) => {
34         scoped_cx!() = scoped_cx!().$method($($arg),*)?
35     };
36     ($($kind:ident $data:tt),+) => {{
37         $(p!(@$kind $data);)+
38     }};
39 }
40 macro_rules! define_scoped_cx {
41     ($cx:ident) => {
42         #[allow(unused_macros)]
43         macro_rules! scoped_cx {
44             () => ($cx)
45         }
46     };
47 }
48
49 thread_local! {
50     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
51     static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
52 }
53
54 /// Force us to name impls with just the filename/line number. We
55 /// normally try to use types. But at some points, notably while printing
56 /// cycle errors, this can result in extra or suboptimal error output,
57 /// so this variable disables that check.
58 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
59     FORCE_IMPL_FILENAME_LINE.with(|force| {
60         let old = force.get();
61         force.set(true);
62         let result = f();
63         force.set(old);
64         result
65     })
66 }
67
68 /// Adds the `crate::` prefix to paths where appropriate.
69 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
70     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
71         let old = flag.get();
72         flag.set(true);
73         let result = f();
74         flag.set(old);
75         result
76     })
77 }
78
79 /// The "region highlights" are used to control region printing during
80 /// specific error messages. When a "region highlight" is enabled, it
81 /// gives an alternate way to print specific regions. For now, we
82 /// always print those regions using a number, so something like "`'0`".
83 ///
84 /// Regions not selected by the region highlight mode are presently
85 /// unaffected.
86 #[derive(Copy, Clone, Default)]
87 pub struct RegionHighlightMode {
88     /// If enabled, when we see the selected region, use "`'N`"
89     /// instead of the ordinary behavior.
90     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
91
92     /// If enabled, when printing a "free region" that originated from
93     /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
94     /// have names print as normal.
95     ///
96     /// This is used when you have a signature like `fn foo(x: &u32,
97     /// y: &'a u32)` and we want to give a name to the region of the
98     /// reference `x`.
99     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
100 }
101
102 impl RegionHighlightMode {
103     /// If `region` and `number` are both `Some`, invokes
104     /// `highlighting_region`.
105     pub fn maybe_highlighting_region(
106         &mut self,
107         region: Option<ty::Region<'_>>,
108         number: Option<usize>,
109     ) {
110         if let Some(k) = region {
111             if let Some(n) = number {
112                 self.highlighting_region(k, n);
113             }
114         }
115     }
116
117     /// Highlights the region inference variable `vid` as `'N`.
118     pub fn highlighting_region(
119         &mut self,
120         region: ty::Region<'_>,
121         number: usize,
122     ) {
123         let num_slots = self.highlight_regions.len();
124         let first_avail_slot = self.highlight_regions.iter_mut()
125             .filter(|s| s.is_none())
126             .next()
127             .unwrap_or_else(|| {
128                 bug!(
129                     "can only highlight {} placeholders at a time",
130                     num_slots,
131                 )
132             });
133         *first_avail_slot = Some((*region, number));
134     }
135
136     /// Convenience wrapper for `highlighting_region`.
137     pub fn highlighting_region_vid(
138         &mut self,
139         vid: ty::RegionVid,
140         number: usize,
141     ) {
142         self.highlighting_region(&ty::ReVar(vid), number)
143     }
144
145     /// Returns `Some(n)` with the number to use for the given region, if any.
146     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
147         self
148             .highlight_regions
149             .iter()
150             .filter_map(|h| match h {
151                 Some((r, n)) if r == region => Some(*n),
152                 _ => None,
153             })
154             .next()
155     }
156
157     /// Highlight the given bound region.
158     /// We can only highlight one bound region at a time. See
159     /// the field `highlight_bound_region` for more detailed notes.
160     pub fn highlighting_bound_region(
161         &mut self,
162         br: ty::BoundRegion,
163         number: usize,
164     ) {
165         assert!(self.highlight_bound_region.is_none());
166         self.highlight_bound_region = Some((br, number));
167     }
168 }
169
170 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
171 pub trait PrettyPrinter<'tcx>:
172     Printer<
173         'tcx,
174         Error = fmt::Error,
175         Path = Self,
176         Region = Self,
177         Type = Self,
178         DynExistential = Self,
179         Const = Self,
180     > + fmt::Write
181 {
182     /// Like `print_def_path` but for value paths.
183     fn print_value_path(
184         self,
185         def_id: DefId,
186         substs: &'tcx [GenericArg<'tcx>],
187     ) -> Result<Self::Path, Self::Error> {
188         self.print_def_path(def_id, substs)
189     }
190
191     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
192     where
193         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
194     {
195         value.skip_binder().print(self)
196     }
197
198     /// Prints comma-separated elements.
199     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
200     where
201         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
202     {
203         if let Some(first) = elems.next() {
204             self = first.print(self)?;
205             for elem in elems {
206                 self.write_str(", ")?;
207                 self = elem.print(self)?;
208             }
209         }
210         Ok(self)
211     }
212
213     /// Prints `<...>` around what `f` prints.
214     fn generic_delimiters(
215         self,
216         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
217     ) -> Result<Self, Self::Error>;
218
219     /// Returns `true` if the region should be printed in
220     /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
221     /// This is typically the case for all non-`'_` regions.
222     fn region_should_not_be_omitted(
223         &self,
224         region: ty::Region<'_>,
225     ) -> bool;
226
227     // Defaults (should not be overriden):
228
229     /// If possible, this returns a global path resolving to `def_id` that is visible
230     /// from at least one local module, and returns `true`. If the crate defining `def_id` is
231     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
232     fn try_print_visible_def_path(
233         self,
234         def_id: DefId,
235     ) -> Result<(Self, bool), Self::Error> {
236         let mut callers = Vec::new();
237         self.try_print_visible_def_path_recur(def_id, &mut callers)
238     }
239
240     /// Does the work of `try_print_visible_def_path`, building the
241     /// full definition path recursively before attempting to
242     /// post-process it into the valid and visible version that
243     /// accounts for re-exports.
244     ///
245     /// This method should only be callled by itself or
246     /// `try_print_visible_def_path`.
247     ///
248     /// `callers` is a chain of visible_parent's leading to `def_id`,
249     /// to support cycle detection during recursion.
250     fn try_print_visible_def_path_recur(
251         mut self,
252         def_id: DefId,
253         callers: &mut Vec<DefId>,
254     ) -> Result<(Self, bool), Self::Error> {
255         define_scoped_cx!(self);
256
257         debug!("try_print_visible_def_path: def_id={:?}", def_id);
258
259         // If `def_id` is a direct or injected extern crate, return the
260         // path to the crate followed by the path to the item within the crate.
261         if def_id.index == CRATE_DEF_INDEX {
262             let cnum = def_id.krate;
263
264             if cnum == LOCAL_CRATE {
265                 return Ok((self.path_crate(cnum)?, true));
266             }
267
268             // In local mode, when we encounter a crate other than
269             // LOCAL_CRATE, execution proceeds in one of two ways:
270             //
271             // 1. For a direct dependency, where user added an
272             //    `extern crate` manually, we put the `extern
273             //    crate` as the parent. So you wind up with
274             //    something relative to the current crate.
275             // 2. For an extern inferred from a path or an indirect crate,
276             //    where there is no explicit `extern crate`, we just prepend
277             //    the crate name.
278             match self.tcx().extern_crate(def_id) {
279                 Some(&ExternCrate {
280                     src: ExternCrateSource::Extern(def_id),
281                     dependency_of: LOCAL_CRATE,
282                     span,
283                     ..
284                 }) => {
285                     debug!("try_print_visible_def_path: def_id={:?}", def_id);
286                     return Ok((if !span.is_dummy() {
287                         self.print_def_path(def_id, &[])?
288                     } else {
289                         self.path_crate(cnum)?
290                     }, true));
291                 }
292                 None => {
293                     return Ok((self.path_crate(cnum)?, true));
294                 }
295                 _ => {},
296             }
297         }
298
299         if def_id.is_local() {
300             return Ok((self, false));
301         }
302
303         let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
304
305         let mut cur_def_key = self.tcx().def_key(def_id);
306         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
307
308         // For a constructor, we want the name of its parent rather than <unnamed>.
309         match cur_def_key.disambiguated_data.data {
310             DefPathData::Ctor => {
311                 let parent = DefId {
312                     krate: def_id.krate,
313                     index: cur_def_key.parent
314                         .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
315                 };
316
317                 cur_def_key = self.tcx().def_key(parent);
318             },
319             _ => {},
320         }
321
322         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
323             Some(parent) => parent,
324             None => return Ok((self, false)),
325         };
326         if callers.contains(&visible_parent) {
327             return Ok((self, false));
328         }
329         callers.push(visible_parent);
330         // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
331         // knowing ahead of time whether the entire path will succeed or not.
332         // To support printers that do not implement `PrettyPrinter`, a `Vec` or
333         // linked list on the stack would need to be built, before any printing.
334         match self.try_print_visible_def_path_recur(visible_parent, callers)? {
335             (cx, false) => return Ok((cx, false)),
336             (cx, true) => self = cx,
337         }
338         callers.pop();
339         let actual_parent = self.tcx().parent(def_id);
340         debug!(
341             "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
342             visible_parent, actual_parent,
343         );
344
345         let mut data = cur_def_key.disambiguated_data.data;
346         debug!(
347             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
348             data, visible_parent, actual_parent,
349         );
350
351         match data {
352             // In order to output a path that could actually be imported (valid and visible),
353             // we need to handle re-exports correctly.
354             //
355             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
356             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
357             //
358             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
359             // private so the "true" path to `CommandExt` isn't accessible.
360             //
361             // In this case, the `visible_parent_map` will look something like this:
362             //
363             // (child) -> (parent)
364             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
365             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
366             // `std::sys::unix::ext` -> `std::os`
367             //
368             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
369             // `std::os`.
370             //
371             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
372             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
373             // to the parent - resulting in a mangled path like
374             // `std::os::ext::process::CommandExt`.
375             //
376             // Instead, we must detect that there was a re-export and instead print `unix`
377             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
378             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
379             // the visible parent (`std::os`). If these do not match, then we iterate over
380             // the children of the visible parent (as was done when computing
381             // `visible_parent_map`), looking for the specific child we currently have and then
382             // have access to the re-exported name.
383             DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
384                 let reexport = self.tcx().item_children(visible_parent)
385                     .iter()
386                     .find(|child| child.res.def_id() == def_id)
387                     .map(|child| child.ident.as_interned_str());
388                 if let Some(reexport) = reexport {
389                     *name = reexport;
390                 }
391             }
392             // Re-exported `extern crate` (#43189).
393             DefPathData::CrateRoot => {
394                 data = DefPathData::TypeNs(
395                     self.tcx().original_crate_name(def_id.krate).as_interned_str(),
396                 );
397             }
398             _ => {}
399         }
400         debug!("try_print_visible_def_path: data={:?}", data);
401
402         Ok((self.path_append(Ok, &DisambiguatedDefPathData {
403             data,
404             disambiguator: 0,
405         })?, true))
406     }
407
408     fn pretty_path_qualified(
409         self,
410         self_ty: Ty<'tcx>,
411         trait_ref: Option<ty::TraitRef<'tcx>>,
412     ) -> Result<Self::Path, Self::Error> {
413         if trait_ref.is_none() {
414             // Inherent impls. Try to print `Foo::bar` for an inherent
415             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
416             // anything other than a simple path.
417             match self_ty.kind {
418                 ty::Adt(..) | ty::Foreign(_) |
419                 ty::Bool | ty::Char | ty::Str |
420                 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
421                     return self_ty.print(self);
422                 }
423
424                 _ => {}
425             }
426         }
427
428         self.generic_delimiters(|mut cx| {
429             define_scoped_cx!(cx);
430
431             p!(print(self_ty));
432             if let Some(trait_ref) = trait_ref {
433                 p!(write(" as "), print(trait_ref));
434             }
435             Ok(cx)
436         })
437     }
438
439     fn pretty_path_append_impl(
440         mut self,
441         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
442         self_ty: Ty<'tcx>,
443         trait_ref: Option<ty::TraitRef<'tcx>>,
444     ) -> Result<Self::Path, Self::Error> {
445         self = print_prefix(self)?;
446
447         self.generic_delimiters(|mut cx| {
448             define_scoped_cx!(cx);
449
450             p!(write("impl "));
451             if let Some(trait_ref) = trait_ref {
452                 p!(print(trait_ref), write(" for "));
453             }
454             p!(print(self_ty));
455
456             Ok(cx)
457         })
458     }
459
460     fn pretty_print_type(
461         mut self,
462         ty: Ty<'tcx>,
463     ) -> Result<Self::Type, Self::Error> {
464         define_scoped_cx!(self);
465
466         match ty.kind {
467             ty::Bool => p!(write("bool")),
468             ty::Char => p!(write("char")),
469             ty::Int(t) => p!(write("{}", t.ty_to_string())),
470             ty::Uint(t) => p!(write("{}", t.ty_to_string())),
471             ty::Float(t) => p!(write("{}", t.ty_to_string())),
472             ty::RawPtr(ref tm) => {
473                 p!(write("*{} ", match tm.mutbl {
474                     hir::MutMutable => "mut",
475                     hir::MutImmutable => "const",
476                 }));
477                 p!(print(tm.ty))
478             }
479             ty::Ref(r, ty, mutbl) => {
480                 p!(write("&"));
481                 if self.region_should_not_be_omitted(r) {
482                     p!(print(r), write(" "));
483                 }
484                 p!(print(ty::TypeAndMut { ty, mutbl }))
485             }
486             ty::Never => p!(write("!")),
487             ty::Tuple(ref tys) => {
488                 p!(write("("));
489                 let mut tys = tys.iter();
490                 if let Some(&ty) = tys.next() {
491                     p!(print(ty), write(","));
492                     if let Some(&ty) = tys.next() {
493                         p!(write(" "), print(ty));
494                         for &ty in tys {
495                             p!(write(", "), print(ty));
496                         }
497                     }
498                 }
499                 p!(write(")"))
500             }
501             ty::FnDef(def_id, substs) => {
502                 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
503                 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
504             }
505             ty::FnPtr(ref bare_fn) => {
506                 p!(print(bare_fn))
507             }
508             ty::Infer(infer_ty) => {
509                 if let ty::TyVar(ty_vid) = infer_ty {
510                     if let Some(name) = self.infer_ty_name(ty_vid) {
511                         p!(write("{}", name))
512                     } else {
513                         p!(write("{}", infer_ty))
514                     }
515                 } else {
516                     p!(write("{}", infer_ty))
517                 }
518             },
519             ty::Error => p!(write("[type error]")),
520             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
521             ty::Bound(debruijn, bound_ty) => {
522                 match bound_ty.kind {
523                     ty::BoundTyKind::Anon => {
524                         if debruijn == ty::INNERMOST {
525                             p!(write("^{}", bound_ty.var.index()))
526                         } else {
527                             p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
528                         }
529                     }
530
531                     ty::BoundTyKind::Param(p) => p!(write("{}", p)),
532                 }
533             }
534             ty::Adt(def, substs) => {
535                 p!(print_def_path(def.did, substs));
536             }
537             ty::Dynamic(data, r) => {
538                 let print_r = self.region_should_not_be_omitted(r);
539                 if print_r {
540                     p!(write("("));
541                 }
542                 p!(write("dyn "), print(data));
543                 if print_r {
544                     p!(write(" + "), print(r), write(")"));
545                 }
546             }
547             ty::Foreign(def_id) => {
548                 p!(print_def_path(def_id, &[]));
549             }
550             ty::Projection(ref data) => p!(print(data)),
551             ty::UnnormalizedProjection(ref data) => {
552                 p!(write("Unnormalized("), print(data), write(")"))
553             }
554             ty::Placeholder(placeholder) => {
555                 p!(write("Placeholder({:?})", placeholder))
556             }
557             ty::Opaque(def_id, substs) => {
558                 // FIXME(eddyb) print this with `print_def_path`.
559                 if self.tcx().sess.verbose() {
560                     p!(write("Opaque({:?}, {:?})", def_id, substs));
561                     return Ok(self);
562                 }
563
564                 let def_key = self.tcx().def_key(def_id);
565                 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
566                     p!(write("{}", name));
567                     let mut substs = substs.iter();
568                     // FIXME(eddyb) print this with `print_def_path`.
569                     if let Some(first) = substs.next() {
570                         p!(write("::<"));
571                         p!(print(first));
572                         for subst in substs {
573                             p!(write(", "), print(subst));
574                         }
575                         p!(write(">"));
576                     }
577                     return Ok(self);
578                 }
579                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
580                 // by looking up the projections associated with the def_id.
581                 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
582
583                 let mut first = true;
584                 let mut is_sized = false;
585                 p!(write("impl"));
586                 for predicate in bounds.predicates {
587                     if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
588                         // Don't print +Sized, but rather +?Sized if absent.
589                         if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
590                             is_sized = true;
591                             continue;
592                         }
593
594                         p!(
595                                 write("{}", if first { " " } else { "+" }),
596                                 print(trait_ref));
597                         first = false;
598                     }
599                 }
600                 if !is_sized {
601                     p!(write("{}?Sized", if first { " " } else { "+" }));
602                 } else if first {
603                     p!(write(" Sized"));
604                 }
605             }
606             ty::Str => p!(write("str")),
607             ty::Generator(did, substs, movability) => {
608                 let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx());
609                 let witness = substs.as_generator().witness(did, self.tcx());
610                 if movability == hir::GeneratorMovability::Movable {
611                     p!(write("[generator"));
612                 } else {
613                     p!(write("[static generator"));
614                 }
615
616                 // FIXME(eddyb) should use `def_span`.
617                 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
618                     p!(write("@{:?}", self.tcx().hir().span(hir_id)));
619                     let mut sep = " ";
620                     for (&var_id, upvar_ty) in self.tcx().upvars(did)
621                         .as_ref()
622                         .iter()
623                         .flat_map(|v| v.keys())
624                         .zip(upvar_tys)
625                     {
626                         p!(
627                             write("{}{}:",
628                                     sep,
629                                     self.tcx().hir().name(var_id)),
630                             print(upvar_ty));
631                         sep = ", ";
632                     }
633                 } else {
634                     // Cross-crate closure types should only be
635                     // visible in codegen bug reports, I imagine.
636                     p!(write("@{:?}", did));
637                     let mut sep = " ";
638                     for (index, upvar_ty) in upvar_tys.enumerate() {
639                         p!(
640                                 write("{}{}:", sep, index),
641                                 print(upvar_ty));
642                         sep = ", ";
643                     }
644                 }
645
646                 p!(write(" "), print(witness), write("]"))
647             },
648             ty::GeneratorWitness(types) => {
649                 p!(in_binder(&types));
650             }
651             ty::Closure(did, substs) => {
652                 let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx());
653                 p!(write("[closure"));
654
655                 // FIXME(eddyb) should use `def_span`.
656                 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
657                     if self.tcx().sess.opts.debugging_opts.span_free_formats {
658                         p!(write("@{:?}", hir_id));
659                     } else {
660                         p!(write("@{:?}", self.tcx().hir().span(hir_id)));
661                     }
662                     let mut sep = " ";
663                     for (&var_id, upvar_ty) in self.tcx().upvars(did)
664                         .as_ref()
665                         .iter()
666                         .flat_map(|v| v.keys())
667                         .zip(upvar_tys)
668                     {
669                         p!(
670                             write("{}{}:",
671                                     sep,
672                                     self.tcx().hir().name(var_id)),
673                             print(upvar_ty));
674                         sep = ", ";
675                     }
676                 } else {
677                     // Cross-crate closure types should only be
678                     // visible in codegen bug reports, I imagine.
679                     p!(write("@{:?}", did));
680                     let mut sep = " ";
681                     for (index, upvar_ty) in upvar_tys.enumerate() {
682                         p!(
683                                 write("{}{}:", sep, index),
684                                 print(upvar_ty));
685                         sep = ", ";
686                     }
687                 }
688
689                 if self.tcx().sess.verbose() {
690                     p!(write(
691                         " closure_kind_ty={:?} closure_sig_ty={:?}",
692                         substs.as_closure().kind(did, self.tcx()),
693                         substs.as_closure().sig_ty(did, self.tcx())
694                     ));
695                 }
696
697                 p!(write("]"))
698             },
699             ty::Array(ty, sz) => {
700                 p!(write("["), print(ty), write("; "));
701                 if let ConstValue::Unevaluated(..) = sz.val {
702                     // do not try to evalute unevaluated constants. If we are const evaluating an
703                     // array length anon const, rustc will (with debug assertions) print the
704                     // constant's path. Which will end up here again.
705                     p!(write("_"));
706                 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
707                     p!(write("{}", n));
708                 } else {
709                     p!(write("_"));
710                 }
711                 p!(write("]"))
712             }
713             ty::Slice(ty) => {
714                 p!(write("["), print(ty), write("]"))
715             }
716         }
717
718         Ok(self)
719     }
720
721     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
722         None
723     }
724
725     fn pretty_print_dyn_existential(
726         mut self,
727         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
728     ) -> Result<Self::DynExistential, Self::Error> {
729         define_scoped_cx!(self);
730
731         // Generate the main trait ref, including associated types.
732         let mut first = true;
733
734         if let Some(principal) = predicates.principal() {
735             p!(print_def_path(principal.def_id, &[]));
736
737             let mut resugared = false;
738
739             // Special-case `Fn(...) -> ...` and resugar it.
740             let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
741             if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
742                 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
743                     let mut projections = predicates.projection_bounds();
744                     if let (Some(proj), None) = (projections.next(), projections.next()) {
745                         let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
746                         p!(pretty_fn_sig(&tys, false, proj.ty));
747                         resugared = true;
748                     }
749                 }
750             }
751
752             // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
753             // in order to place the projections inside the `<...>`.
754             if !resugared {
755                 // Use a type that can't appear in defaults of type parameters.
756                 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
757                 let principal = principal.with_self_ty(self.tcx(), dummy_self);
758
759                 let args = self.generic_args_to_print(
760                     self.tcx().generics_of(principal.def_id),
761                     principal.substs,
762                 );
763
764                 // Don't print `'_` if there's no unerased regions.
765                 let print_regions = args.iter().any(|arg| {
766                     match arg.unpack() {
767                         GenericArgKind::Lifetime(r) => *r != ty::ReErased,
768                         _ => false,
769                     }
770                 });
771                 let mut args = args.iter().cloned().filter(|arg| {
772                     match arg.unpack() {
773                         GenericArgKind::Lifetime(_) => print_regions,
774                         _ => true,
775                     }
776                 });
777                 let mut projections = predicates.projection_bounds();
778
779                 let arg0 = args.next();
780                 let projection0 = projections.next();
781                 if arg0.is_some() || projection0.is_some() {
782                     let args = arg0.into_iter().chain(args);
783                     let projections = projection0.into_iter().chain(projections);
784
785                     p!(generic_delimiters(|mut cx| {
786                         cx = cx.comma_sep(args)?;
787                         if arg0.is_some() && projection0.is_some() {
788                             write!(cx, ", ")?;
789                         }
790                         cx.comma_sep(projections)
791                     }));
792                 }
793             }
794             first = false;
795         }
796
797         // Builtin bounds.
798         // FIXME(eddyb) avoid printing twice (needed to ensure
799         // that the auto traits are sorted *and* printed via cx).
800         let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
801             (self.tcx().def_path_str(did), did)
802         }).collect();
803
804         // The auto traits come ordered by `DefPathHash`. While
805         // `DefPathHash` is *stable* in the sense that it depends on
806         // neither the host nor the phase of the moon, it depends
807         // "pseudorandomly" on the compiler version and the target.
808         //
809         // To avoid that causing instabilities in compiletest
810         // output, sort the auto-traits alphabetically.
811         auto_traits.sort();
812
813         for (_, def_id) in auto_traits {
814             if !first {
815                 p!(write(" + "));
816             }
817             first = false;
818
819             p!(print_def_path(def_id, &[]));
820         }
821
822         Ok(self)
823     }
824
825     fn pretty_fn_sig(
826         mut self,
827         inputs: &[Ty<'tcx>],
828         c_variadic: bool,
829         output: Ty<'tcx>,
830     ) -> Result<Self, Self::Error> {
831         define_scoped_cx!(self);
832
833         p!(write("("));
834         let mut inputs = inputs.iter();
835         if let Some(&ty) = inputs.next() {
836             p!(print(ty));
837             for &ty in inputs {
838                 p!(write(", "), print(ty));
839             }
840             if c_variadic {
841                 p!(write(", ..."));
842             }
843         }
844         p!(write(")"));
845         if !output.is_unit() {
846             p!(write(" -> "), print(output));
847         }
848
849         Ok(self)
850     }
851
852     fn pretty_print_const(
853         mut self,
854         ct: &'tcx ty::Const<'tcx>,
855     ) -> Result<Self::Const, Self::Error> {
856         define_scoped_cx!(self);
857
858         let u8 = self.tcx().types.u8;
859         if let ty::FnDef(did, substs) = ct.ty.kind {
860             p!(print_value_path(did, substs));
861             return Ok(self);
862         }
863         if let ConstValue::Unevaluated(did, substs) = ct.val {
864             match self.tcx().def_kind(did) {
865                 | Some(DefKind::Static)
866                 | Some(DefKind::Const)
867                 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
868                 _ => if did.is_local() {
869                     let span = self.tcx().def_span(did);
870                     if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
871                         p!(write("{}", snip))
872                     } else {
873                         p!(write("_: "), print(ct.ty))
874                     }
875                 } else {
876                     p!(write("_: "), print(ct.ty))
877                 },
878             }
879             return Ok(self);
880         }
881         if let ConstValue::Infer(..) = ct.val {
882             p!(write("_: "), print(ct.ty));
883             return Ok(self);
884         }
885         if let ConstValue::Param(ParamConst { name, .. }) = ct.val {
886             p!(write("{}", name));
887             return Ok(self);
888         }
889         if let ConstValue::Scalar(Scalar::Raw { data, .. }) = ct.val {
890             match ct.ty.kind {
891                 ty::Bool => {
892                     p!(write("{}", if data == 0 { "false" } else { "true" }));
893                     return Ok(self);
894                 },
895                 ty::Float(ast::FloatTy::F32) => {
896                     p!(write("{}f32", Single::from_bits(data)));
897                     return Ok(self);
898                 },
899                 ty::Float(ast::FloatTy::F64) => {
900                     p!(write("{}f64", Double::from_bits(data)));
901                     return Ok(self);
902                 },
903                 ty::Uint(ui) => {
904                     let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(ui)).size();
905                     let max = truncate(u128::max_value(), bit_size);
906
907                     if data == max {
908                         p!(write("std::{}::MAX", ui))
909                     } else {
910                         p!(write("{}{}", data, ui))
911                     };
912                     return Ok(self);
913                 },
914                 ty::Int(i) =>{
915                     let bit_size = Integer::from_attr(&self.tcx(), SignedInt(i))
916                         .size().bits() as u128;
917                     let min = 1u128 << (bit_size - 1);
918                     let max = min - 1;
919
920                     let ty = self.tcx().lift(&ct.ty).unwrap();
921                     let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
922                         .unwrap()
923                         .size;
924                     match data {
925                         d if d == min => p!(write("std::{}::MIN", i)),
926                         d if d == max => p!(write("std::{}::MAX", i)),
927                         _ => p!(write("{}{}", sign_extend(data, size) as i128, i))
928                     }
929                     return Ok(self);
930                 },
931                 ty::Char => {
932                     p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()));
933                     return Ok(self);
934                 }
935                 _ => {},
936             }
937         }
938         if let ty::Ref(_, ref_ty, _) = ct.ty.kind {
939             let byte_str = match (ct.val, &ref_ty.kind) {
940                 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
941                     let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
942                     Some(self.tcx()
943                         .alloc_map.lock()
944                         .unwrap_memory(ptr.alloc_id)
945                         .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
946                 },
947                 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
948                     // The `inspect` here is okay since we checked the bounds, and there are no
949                     // relocations (we have an active slice reference here). We don't use this
950                     // result to affect interpreter execution.
951                     Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
952                 },
953                 (ConstValue::Slice { data, start, end }, ty::Str) => {
954                     // The `inspect` here is okay since we checked the bounds, and there are no
955                     // relocations (we have an active `str` reference here). We don't use this
956                     // result to affect interpreter execution.
957                     let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
958                     let s = ::std::str::from_utf8(slice)
959                         .expect("non utf8 str from miri");
960                     p!(write("{:?}", s));
961                     return Ok(self);
962                 },
963                 _ => None,
964             };
965             if let Some(byte_str) = byte_str {
966                 p!(write("b\""));
967                 for &c in byte_str {
968                     for e in std::ascii::escape_default(c) {
969                         self.write_char(e as char)?;
970                     }
971                 }
972                 p!(write("\""));
973                 return Ok(self);
974             }
975         }
976         p!(write("{:?} : ", ct.val), print(ct.ty));
977
978         Ok(self)
979     }
980 }
981
982 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
983 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
984
985 pub struct FmtPrinterData<'a, 'tcx, F> {
986     tcx: TyCtxt<'tcx>,
987     fmt: F,
988
989     empty_path: bool,
990     in_value: bool,
991
992     used_region_names: FxHashSet<InternedString>,
993     region_index: usize,
994     binder_depth: usize,
995
996     pub region_highlight_mode: RegionHighlightMode,
997
998     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
999 }
1000
1001 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1002     type Target = FmtPrinterData<'a, 'tcx, F>;
1003     fn deref(&self) -> &Self::Target {
1004         &self.0
1005     }
1006 }
1007
1008 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1009     fn deref_mut(&mut self) -> &mut Self::Target {
1010         &mut self.0
1011     }
1012 }
1013
1014 impl<F> FmtPrinter<'a, 'tcx, F> {
1015     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1016         FmtPrinter(Box::new(FmtPrinterData {
1017             tcx,
1018             fmt,
1019             empty_path: false,
1020             in_value: ns == Namespace::ValueNS,
1021             used_region_names: Default::default(),
1022             region_index: 0,
1023             binder_depth: 0,
1024             region_highlight_mode: RegionHighlightMode::default(),
1025             name_resolver: None,
1026         }))
1027     }
1028 }
1029
1030 impl TyCtxt<'_> {
1031     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1032     // (but also some things just print a `DefId` generally so maybe we need this?)
1033     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1034         match self.def_key(def_id).disambiguated_data.data {
1035             DefPathData::TypeNs(..)
1036             | DefPathData::CrateRoot
1037             | DefPathData::ImplTrait => Namespace::TypeNS,
1038
1039             DefPathData::ValueNs(..)
1040             | DefPathData::AnonConst
1041             | DefPathData::ClosureExpr
1042             | DefPathData::Ctor => Namespace::ValueNS,
1043
1044             DefPathData::MacroNs(..) => Namespace::MacroNS,
1045
1046             _ => Namespace::TypeNS,
1047         }
1048     }
1049
1050     /// Returns a string identifying this `DefId`. This string is
1051     /// suitable for user output.
1052     pub fn def_path_str(self, def_id: DefId) -> String {
1053         let ns = self.guess_def_namespace(def_id);
1054         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1055         let mut s = String::new();
1056         let _ = FmtPrinter::new(self, &mut s, ns)
1057             .print_def_path(def_id, &[]);
1058         s
1059     }
1060 }
1061
1062 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1063     fn write_str(&mut self, s: &str) -> fmt::Result {
1064         self.fmt.write_str(s)
1065     }
1066 }
1067
1068 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1069     type Error = fmt::Error;
1070
1071     type Path = Self;
1072     type Region = Self;
1073     type Type = Self;
1074     type DynExistential = Self;
1075     type Const = Self;
1076
1077     fn tcx(&'a self) -> TyCtxt<'tcx> {
1078         self.tcx
1079     }
1080
1081     fn print_def_path(
1082         mut self,
1083         def_id: DefId,
1084         substs: &'tcx [GenericArg<'tcx>],
1085     ) -> Result<Self::Path, Self::Error> {
1086         define_scoped_cx!(self);
1087
1088         if substs.is_empty() {
1089             match self.try_print_visible_def_path(def_id)? {
1090                 (cx, true) => return Ok(cx),
1091                 (cx, false) => self = cx,
1092             }
1093         }
1094
1095         let key = self.tcx.def_key(def_id);
1096         if let DefPathData::Impl = key.disambiguated_data.data {
1097             // Always use types for non-local impls, where types are always
1098             // available, and filename/line-number is mostly uninteresting.
1099             let use_types =
1100                 !def_id.is_local() || {
1101                     // Otherwise, use filename/line-number if forced.
1102                     let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1103                     !force_no_types
1104                 };
1105
1106             if !use_types {
1107                 // If no type info is available, fall back to
1108                 // pretty printing some span information. This should
1109                 // only occur very early in the compiler pipeline.
1110                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1111                 let span = self.tcx.def_span(def_id);
1112
1113                 self = self.print_def_path(parent_def_id, &[])?;
1114
1115                 // HACK(eddyb) copy of `path_append` to avoid
1116                 // constructing a `DisambiguatedDefPathData`.
1117                 if !self.empty_path {
1118                     write!(self, "::")?;
1119                 }
1120                 write!(self, "<impl at {:?}>", span)?;
1121                 self.empty_path = false;
1122
1123                 return Ok(self);
1124             }
1125         }
1126
1127         self.default_print_def_path(def_id, substs)
1128     }
1129
1130     fn print_region(
1131         self,
1132         region: ty::Region<'_>,
1133     ) -> Result<Self::Region, Self::Error> {
1134         self.pretty_print_region(region)
1135     }
1136
1137     fn print_type(
1138         self,
1139         ty: Ty<'tcx>,
1140     ) -> Result<Self::Type, Self::Error> {
1141         self.pretty_print_type(ty)
1142     }
1143
1144     fn print_dyn_existential(
1145         self,
1146         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1147     ) -> Result<Self::DynExistential, Self::Error> {
1148         self.pretty_print_dyn_existential(predicates)
1149     }
1150
1151     fn print_const(
1152         self,
1153         ct: &'tcx ty::Const<'tcx>,
1154     ) -> Result<Self::Const, Self::Error> {
1155         self.pretty_print_const(ct)
1156     }
1157
1158     fn path_crate(
1159         mut self,
1160         cnum: CrateNum,
1161     ) -> Result<Self::Path, Self::Error> {
1162         self.empty_path = true;
1163         if cnum == LOCAL_CRATE {
1164             if self.tcx.sess.rust_2018() {
1165                 // We add the `crate::` keyword on Rust 2018, only when desired.
1166                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1167                     write!(self, "{}", kw::Crate)?;
1168                     self.empty_path = false;
1169                 }
1170             }
1171         } else {
1172             write!(self, "{}", self.tcx.crate_name(cnum))?;
1173             self.empty_path = false;
1174         }
1175         Ok(self)
1176     }
1177
1178     fn path_qualified(
1179         mut self,
1180         self_ty: Ty<'tcx>,
1181         trait_ref: Option<ty::TraitRef<'tcx>>,
1182     ) -> Result<Self::Path, Self::Error> {
1183         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1184         self.empty_path = false;
1185         Ok(self)
1186     }
1187
1188     fn path_append_impl(
1189         mut self,
1190         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1191         _disambiguated_data: &DisambiguatedDefPathData,
1192         self_ty: Ty<'tcx>,
1193         trait_ref: Option<ty::TraitRef<'tcx>>,
1194     ) -> Result<Self::Path, Self::Error> {
1195         self = self.pretty_path_append_impl(|mut cx| {
1196             cx = print_prefix(cx)?;
1197             if !cx.empty_path {
1198                 write!(cx, "::")?;
1199             }
1200
1201             Ok(cx)
1202         }, self_ty, trait_ref)?;
1203         self.empty_path = false;
1204         Ok(self)
1205     }
1206
1207     fn path_append(
1208         mut self,
1209         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1210         disambiguated_data: &DisambiguatedDefPathData,
1211     ) -> Result<Self::Path, Self::Error> {
1212         self = print_prefix(self)?;
1213
1214         // Skip `::{{constructor}}` on tuple/unit structs.
1215         match disambiguated_data.data {
1216             DefPathData::Ctor => return Ok(self),
1217             _ => {}
1218         }
1219
1220         // FIXME(eddyb) `name` should never be empty, but it
1221         // currently is for `extern { ... }` "foreign modules".
1222         let name = disambiguated_data.data.as_interned_str().as_str();
1223         if !name.is_empty() {
1224             if !self.empty_path {
1225                 write!(self, "::")?;
1226             }
1227             write!(self, "{}", name)?;
1228
1229             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1230             // might be nicer to use something else, e.g. `{closure#3}`.
1231             let dis = disambiguated_data.disambiguator;
1232             let print_dis =
1233                 disambiguated_data.data.get_opt_name().is_none() ||
1234                 dis != 0 && self.tcx.sess.verbose();
1235             if print_dis {
1236                 write!(self, "#{}", dis)?;
1237             }
1238
1239             self.empty_path = false;
1240         }
1241
1242         Ok(self)
1243     }
1244
1245     fn path_generic_args(
1246         mut self,
1247         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1248         args: &[GenericArg<'tcx>],
1249     ) -> Result<Self::Path, Self::Error> {
1250         self = print_prefix(self)?;
1251
1252         // Don't print `'_` if there's no unerased regions.
1253         let print_regions = args.iter().any(|arg| {
1254             match arg.unpack() {
1255                 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1256                 _ => false,
1257             }
1258         });
1259         let args = args.iter().cloned().filter(|arg| {
1260             match arg.unpack() {
1261                 GenericArgKind::Lifetime(_) => print_regions,
1262                 _ => true,
1263             }
1264         });
1265
1266         if args.clone().next().is_some() {
1267             if self.in_value {
1268                 write!(self, "::")?;
1269             }
1270             self.generic_delimiters(|cx| cx.comma_sep(args))
1271         } else {
1272             Ok(self)
1273         }
1274     }
1275 }
1276
1277 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1278     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1279         self.0.name_resolver.as_ref().and_then(|func| func(id))
1280     }
1281
1282     fn print_value_path(
1283         mut self,
1284         def_id: DefId,
1285         substs: &'tcx [GenericArg<'tcx>],
1286     ) -> Result<Self::Path, Self::Error> {
1287         let was_in_value = std::mem::replace(&mut self.in_value, true);
1288         self = self.print_def_path(def_id, substs)?;
1289         self.in_value = was_in_value;
1290
1291         Ok(self)
1292     }
1293
1294     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1295     where
1296         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1297     {
1298         self.pretty_in_binder(value)
1299     }
1300
1301     fn generic_delimiters(
1302         mut self,
1303         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1304     ) -> Result<Self, Self::Error> {
1305         write!(self, "<")?;
1306
1307         let was_in_value = std::mem::replace(&mut self.in_value, false);
1308         let mut inner = f(self)?;
1309         inner.in_value = was_in_value;
1310
1311         write!(inner, ">")?;
1312         Ok(inner)
1313     }
1314
1315     fn region_should_not_be_omitted(
1316         &self,
1317         region: ty::Region<'_>,
1318     ) -> bool {
1319         let highlight = self.region_highlight_mode;
1320         if highlight.region_highlighted(region).is_some() {
1321             return true;
1322         }
1323
1324         if self.tcx.sess.verbose() {
1325             return true;
1326         }
1327
1328         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1329
1330         match *region {
1331             ty::ReEarlyBound(ref data) => {
1332                 data.name.as_symbol() != kw::Invalid &&
1333                 data.name.as_symbol() != kw::UnderscoreLifetime
1334             }
1335
1336             ty::ReLateBound(_, br) |
1337             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1338             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1339                 if let ty::BrNamed(_, name) = br {
1340                     if name.as_symbol() != kw::Invalid &&
1341                        name.as_symbol() != kw::UnderscoreLifetime {
1342                         return true;
1343                     }
1344                 }
1345
1346                 if let Some((region, _)) = highlight.highlight_bound_region {
1347                     if br == region {
1348                         return true;
1349                     }
1350                 }
1351
1352                 false
1353             }
1354
1355             ty::ReScope(_) |
1356             ty::ReVar(_) if identify_regions => true,
1357
1358             ty::ReVar(_) |
1359             ty::ReScope(_) |
1360             ty::ReErased => false,
1361
1362             ty::ReStatic |
1363             ty::ReEmpty |
1364             ty::ReClosureBound(_) => true,
1365         }
1366     }
1367 }
1368
1369 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1370 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1371     pub fn pretty_print_region(
1372         mut self,
1373         region: ty::Region<'_>,
1374     ) -> Result<Self, fmt::Error> {
1375         define_scoped_cx!(self);
1376
1377         // Watch out for region highlights.
1378         let highlight = self.region_highlight_mode;
1379         if let Some(n) = highlight.region_highlighted(region) {
1380             p!(write("'{}", n));
1381             return Ok(self);
1382         }
1383
1384         if self.tcx.sess.verbose() {
1385             p!(write("{:?}", region));
1386             return Ok(self);
1387         }
1388
1389         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1390
1391         // These printouts are concise.  They do not contain all the information
1392         // the user might want to diagnose an error, but there is basically no way
1393         // to fit that into a short string.  Hence the recommendation to use
1394         // `explain_region()` or `note_and_explain_region()`.
1395         match *region {
1396             ty::ReEarlyBound(ref data) => {
1397                 if data.name.as_symbol() != kw::Invalid {
1398                     p!(write("{}", data.name));
1399                     return Ok(self);
1400                 }
1401             }
1402             ty::ReLateBound(_, br) |
1403             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1404             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1405                 if let ty::BrNamed(_, name) = br {
1406                     if name.as_symbol() != kw::Invalid &&
1407                        name.as_symbol() != kw::UnderscoreLifetime {
1408                         p!(write("{}", name));
1409                         return Ok(self);
1410                     }
1411                 }
1412
1413                 if let Some((region, counter)) = highlight.highlight_bound_region {
1414                     if br == region {
1415                         p!(write("'{}", counter));
1416                         return Ok(self);
1417                     }
1418                 }
1419             }
1420             ty::ReScope(scope) if identify_regions => {
1421                 match scope.data {
1422                     region::ScopeData::Node =>
1423                         p!(write("'{}s", scope.item_local_id().as_usize())),
1424                     region::ScopeData::CallSite =>
1425                         p!(write("'{}cs", scope.item_local_id().as_usize())),
1426                     region::ScopeData::Arguments =>
1427                         p!(write("'{}as", scope.item_local_id().as_usize())),
1428                     region::ScopeData::Destruction =>
1429                         p!(write("'{}ds", scope.item_local_id().as_usize())),
1430                     region::ScopeData::Remainder(first_statement_index) => p!(write(
1431                         "'{}_{}rs",
1432                         scope.item_local_id().as_usize(),
1433                         first_statement_index.index()
1434                     )),
1435                 }
1436                 return Ok(self);
1437             }
1438             ty::ReVar(region_vid) if identify_regions => {
1439                 p!(write("{:?}", region_vid));
1440                 return Ok(self);
1441             }
1442             ty::ReVar(_) => {}
1443             ty::ReScope(_) |
1444             ty::ReErased => {}
1445             ty::ReStatic => {
1446                 p!(write("'static"));
1447                 return Ok(self);
1448             }
1449             ty::ReEmpty => {
1450                 p!(write("'<empty>"));
1451                 return Ok(self);
1452             }
1453
1454             // The user should never encounter these in unsubstituted form.
1455             ty::ReClosureBound(vid) => {
1456                 p!(write("{:?}", vid));
1457                 return Ok(self);
1458             }
1459         }
1460
1461         p!(write("'_"));
1462
1463         Ok(self)
1464     }
1465 }
1466
1467 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1468 // `region_index` and `used_region_names`.
1469 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1470     pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1471     where
1472         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1473     {
1474         fn name_by_region_index(index: usize) -> InternedString {
1475             match index {
1476                 0 => InternedString::intern("'r"),
1477                 1 => InternedString::intern("'s"),
1478                 i => InternedString::intern(&format!("'t{}", i-2)),
1479             }
1480         }
1481
1482         // Replace any anonymous late-bound regions with named
1483         // variants, using gensym'd identifiers, so that we can
1484         // clearly differentiate between named and unnamed regions in
1485         // the output. We'll probably want to tweak this over time to
1486         // decide just how much information to give.
1487         if self.binder_depth == 0 {
1488             self.prepare_late_bound_region_info(value);
1489         }
1490
1491         let mut empty = true;
1492         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1493             write!(cx, "{}", if empty {
1494                 empty = false;
1495                 start
1496             } else {
1497                 cont
1498             })
1499         };
1500
1501         define_scoped_cx!(self);
1502
1503         let old_region_index = self.region_index;
1504         let mut region_index = old_region_index;
1505         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1506             let _ = start_or_continue(&mut self, "for<", ", ");
1507             let br = match br {
1508                 ty::BrNamed(_, name) => {
1509                     let _ = write!(self, "{}", name);
1510                     br
1511                 }
1512                 ty::BrAnon(_) |
1513                 ty::BrEnv => {
1514                     let name = loop {
1515                         let name = name_by_region_index(region_index);
1516                         region_index += 1;
1517                         if !self.used_region_names.contains(&name) {
1518                             break name;
1519                         }
1520                     };
1521                     let _ = write!(self, "{}", name);
1522                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1523                 }
1524             };
1525             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1526         }).0;
1527         start_or_continue(&mut self, "", "> ")?;
1528
1529         self.binder_depth += 1;
1530         self.region_index = region_index;
1531         let mut inner = new_value.print(self)?;
1532         inner.region_index = old_region_index;
1533         inner.binder_depth -= 1;
1534         Ok(inner)
1535     }
1536
1537     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1538         where T: TypeFoldable<'tcx>
1539     {
1540
1541         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1542         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1543             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1544                 match *r {
1545                     ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1546                         self.0.insert(name);
1547                     },
1548                     _ => {},
1549                 }
1550                 r.super_visit_with(self)
1551             }
1552         }
1553
1554         self.used_region_names.clear();
1555         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1556         value.visit_with(&mut collector);
1557         self.region_index = 0;
1558     }
1559 }
1560
1561 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1562 where
1563     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1564 {
1565     type Output = P;
1566     type Error = P::Error;
1567     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1568         cx.in_binder(self)
1569     }
1570 }
1571
1572 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1573 where
1574     T: Print<'tcx, P, Output = P, Error = P::Error>,
1575     U: Print<'tcx, P, Output = P, Error = P::Error>,
1576 {
1577     type Output = P;
1578     type Error = P::Error;
1579     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1580         define_scoped_cx!(cx);
1581         p!(print(self.0), write(" : "), print(self.1));
1582         Ok(cx)
1583     }
1584 }
1585
1586 macro_rules! forward_display_to_print {
1587     ($($ty:ty),+) => {
1588         $(impl fmt::Display for $ty {
1589             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590                 ty::tls::with(|tcx| {
1591                     tcx.lift(self)
1592                         .expect("could not lift for printing")
1593                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1594                     Ok(())
1595                 })
1596             }
1597         })+
1598     };
1599 }
1600
1601 macro_rules! define_print_and_forward_display {
1602     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1603         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1604             type Output = P;
1605             type Error = fmt::Error;
1606             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1607                 #[allow(unused_mut)]
1608                 let mut $cx = $cx;
1609                 define_scoped_cx!($cx);
1610                 let _: () = $print;
1611                 #[allow(unreachable_code)]
1612                 Ok($cx)
1613             }
1614         })+
1615
1616         forward_display_to_print!($($ty),+);
1617     };
1618 }
1619
1620 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1621 impl fmt::Display for ty::RegionKind {
1622     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623         ty::tls::with(|tcx| {
1624             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1625             Ok(())
1626         })
1627     }
1628 }
1629
1630 forward_display_to_print! {
1631     Ty<'tcx>,
1632     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1633     &'tcx ty::Const<'tcx>,
1634
1635     // HACK(eddyb) these are exhaustive instead of generic,
1636     // because `for<'tcx>` isn't possible yet.
1637     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1638     ty::Binder<ty::TraitRef<'tcx>>,
1639     ty::Binder<ty::FnSig<'tcx>>,
1640     ty::Binder<ty::TraitPredicate<'tcx>>,
1641     ty::Binder<ty::SubtypePredicate<'tcx>>,
1642     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1643     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1644     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1645
1646     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1647     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1648 }
1649
1650 define_print_and_forward_display! {
1651     (self, cx):
1652
1653     &'tcx ty::List<Ty<'tcx>> {
1654         p!(write("{{"));
1655         let mut tys = self.iter();
1656         if let Some(&ty) = tys.next() {
1657             p!(print(ty));
1658             for &ty in tys {
1659                 p!(write(", "), print(ty));
1660             }
1661         }
1662         p!(write("}}"))
1663     }
1664
1665     ty::TypeAndMut<'tcx> {
1666         p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1667             print(self.ty))
1668     }
1669
1670     ty::ExistentialTraitRef<'tcx> {
1671         // Use a type that can't appear in defaults of type parameters.
1672         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1673         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1674         p!(print(trait_ref))
1675     }
1676
1677     ty::ExistentialProjection<'tcx> {
1678         let name = cx.tcx().associated_item(self.item_def_id).ident;
1679         p!(write("{} = ", name), print(self.ty))
1680     }
1681
1682     ty::ExistentialPredicate<'tcx> {
1683         match *self {
1684             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1685             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1686             ty::ExistentialPredicate::AutoTrait(def_id) => {
1687                 p!(print_def_path(def_id, &[]));
1688             }
1689         }
1690     }
1691
1692     ty::FnSig<'tcx> {
1693         if self.unsafety == hir::Unsafety::Unsafe {
1694             p!(write("unsafe "));
1695         }
1696
1697         if self.abi != Abi::Rust {
1698             p!(write("extern {} ", self.abi));
1699         }
1700
1701         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1702     }
1703
1704     ty::InferTy {
1705         if cx.tcx().sess.verbose() {
1706             p!(write("{:?}", self));
1707             return Ok(cx);
1708         }
1709         match *self {
1710             ty::TyVar(_) => p!(write("_")),
1711             ty::IntVar(_) => p!(write("{}", "{integer}")),
1712             ty::FloatVar(_) => p!(write("{}", "{float}")),
1713             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1714             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1715             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1716         }
1717     }
1718
1719     ty::TraitRef<'tcx> {
1720         p!(print_def_path(self.def_id, self.substs));
1721     }
1722
1723     ty::ParamTy {
1724         p!(write("{}", self.name))
1725     }
1726
1727     ty::ParamConst {
1728         p!(write("{}", self.name))
1729     }
1730
1731     ty::SubtypePredicate<'tcx> {
1732         p!(print(self.a), write(" <: "), print(self.b))
1733     }
1734
1735     ty::TraitPredicate<'tcx> {
1736         p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1737     }
1738
1739     ty::ProjectionPredicate<'tcx> {
1740         p!(print(self.projection_ty), write(" == "), print(self.ty))
1741     }
1742
1743     ty::ProjectionTy<'tcx> {
1744         p!(print_def_path(self.item_def_id, self.substs));
1745     }
1746
1747     ty::ClosureKind {
1748         match *self {
1749             ty::ClosureKind::Fn => p!(write("Fn")),
1750             ty::ClosureKind::FnMut => p!(write("FnMut")),
1751             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1752         }
1753     }
1754
1755     ty::Predicate<'tcx> {
1756         match *self {
1757             ty::Predicate::Trait(ref data) => p!(print(data)),
1758             ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1759             ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1760             ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1761             ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1762             ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1763             ty::Predicate::ObjectSafe(trait_def_id) => {
1764                 p!(write("the trait `"),
1765                    print_def_path(trait_def_id, &[]),
1766                    write("` is object-safe"))
1767             }
1768             ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1769                 p!(write("the closure `"),
1770                    print_value_path(closure_def_id, &[]),
1771                    write("` implements the trait `{}`", kind))
1772             }
1773             ty::Predicate::ConstEvaluatable(def_id, substs) => {
1774                 p!(write("the constant `"),
1775                    print_value_path(def_id, substs),
1776                    write("` can be evaluated"))
1777             }
1778         }
1779     }
1780
1781     GenericArg<'tcx> {
1782         match self.unpack() {
1783             GenericArgKind::Lifetime(lt) => p!(print(lt)),
1784             GenericArgKind::Type(ty) => p!(print(ty)),
1785             GenericArgKind::Const(ct) => p!(print(ct)),
1786         }
1787     }
1788 }