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