]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/print/pretty.rs
Auto merge of #83339 - Aaron1011:deep-recollect, r=petrochenkov
[rust.git] / compiler / rustc_middle / src / ty / print / pretty.rs
1 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
2 use crate::mir::interpret::{AllocId, ConstValue, GlobalAlloc, Pointer, Scalar};
3 use crate::ty::subst::{GenericArg, GenericArgKind, Subst};
4 use crate::ty::{self, ConstInt, DefIdTree, ParamConst, ScalarInt, Ty, TyCtxt, TypeFoldable};
5 use rustc_apfloat::ieee::{Double, Single};
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_hir as hir;
8 use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
9 use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
11 use rustc_hir::ItemKind;
12 use rustc_session::config::TrimmedDefPaths;
13 use rustc_span::symbol::{kw, Ident, Symbol};
14 use rustc_target::abi::Size;
15 use rustc_target::spec::abi::Abi;
16
17 use std::cell::Cell;
18 use std::char;
19 use std::collections::BTreeMap;
20 use std::convert::TryFrom;
21 use std::fmt::{self, Write as _};
22 use std::ops::{ControlFlow, Deref, DerefMut};
23
24 // `pretty` is a separate module only for organization.
25 use super::*;
26
27 macro_rules! p {
28     (@$lit:literal) => {
29         write!(scoped_cx!(), $lit)?
30     };
31     (@write($($data:expr),+)) => {
32         write!(scoped_cx!(), $($data),+)?
33     };
34     (@print($x:expr)) => {
35         scoped_cx!() = $x.print(scoped_cx!())?
36     };
37     (@$method:ident($($arg:expr),*)) => {
38         scoped_cx!() = scoped_cx!().$method($($arg),*)?
39     };
40     ($($elem:tt $(($($args:tt)*))?),+) => {{
41         $(p!(@ $elem $(($($args)*))?);)+
42     }};
43 }
44 macro_rules! define_scoped_cx {
45     ($cx:ident) => {
46         #[allow(unused_macros)]
47         macro_rules! scoped_cx {
48             () => {
49                 $cx
50             };
51         }
52     };
53 }
54
55 thread_local! {
56     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
57     static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
58     static NO_TRIMMED_PATH: Cell<bool> = Cell::new(false);
59     static NO_QUERIES: Cell<bool> = Cell::new(false);
60 }
61
62 /// Avoids running any queries during any prints that occur
63 /// during the closure. This may alter the appearance of some
64 /// types (e.g. forcing verbose printing for opaque types).
65 /// This method is used during some queries (e.g. `explicit_item_bounds`
66 /// for opaque types), to ensure that any debug printing that
67 /// occurs during the query computation does not end up recursively
68 /// calling the same query.
69 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
70     NO_QUERIES.with(|no_queries| {
71         let old = no_queries.replace(true);
72         let result = f();
73         no_queries.set(old);
74         result
75     })
76 }
77
78 /// Force us to name impls with just the filename/line number. We
79 /// normally try to use types. But at some points, notably while printing
80 /// cycle errors, this can result in extra or suboptimal error output,
81 /// so this variable disables that check.
82 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
83     FORCE_IMPL_FILENAME_LINE.with(|force| {
84         let old = force.replace(true);
85         let result = f();
86         force.set(old);
87         result
88     })
89 }
90
91 /// Adds the `crate::` prefix to paths where appropriate.
92 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
93     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
94         let old = flag.replace(true);
95         let result = f();
96         flag.set(old);
97         result
98     })
99 }
100
101 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
102 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
103 /// if no other `Vec` is found.
104 pub fn with_no_trimmed_paths<F: FnOnce() -> R, R>(f: F) -> R {
105     NO_TRIMMED_PATH.with(|flag| {
106         let old = flag.replace(true);
107         let result = f();
108         flag.set(old);
109         result
110     })
111 }
112
113 /// The "region highlights" are used to control region printing during
114 /// specific error messages. When a "region highlight" is enabled, it
115 /// gives an alternate way to print specific regions. For now, we
116 /// always print those regions using a number, so something like "`'0`".
117 ///
118 /// Regions not selected by the region highlight mode are presently
119 /// unaffected.
120 #[derive(Copy, Clone, Default)]
121 pub struct RegionHighlightMode {
122     /// If enabled, when we see the selected region, use "`'N`"
123     /// instead of the ordinary behavior.
124     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
125
126     /// If enabled, when printing a "free region" that originated from
127     /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
128     /// have names print as normal.
129     ///
130     /// This is used when you have a signature like `fn foo(x: &u32,
131     /// y: &'a u32)` and we want to give a name to the region of the
132     /// reference `x`.
133     highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
134 }
135
136 impl RegionHighlightMode {
137     /// If `region` and `number` are both `Some`, invokes
138     /// `highlighting_region`.
139     pub fn maybe_highlighting_region(
140         &mut self,
141         region: Option<ty::Region<'_>>,
142         number: Option<usize>,
143     ) {
144         if let Some(k) = region {
145             if let Some(n) = number {
146                 self.highlighting_region(k, n);
147             }
148         }
149     }
150
151     /// Highlights the region inference variable `vid` as `'N`.
152     pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) {
153         let num_slots = self.highlight_regions.len();
154         let first_avail_slot =
155             self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
156                 bug!("can only highlight {} placeholders at a time", num_slots,)
157             });
158         *first_avail_slot = Some((*region, number));
159     }
160
161     /// Convenience wrapper for `highlighting_region`.
162     pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
163         self.highlighting_region(&ty::ReVar(vid), number)
164     }
165
166     /// Returns `Some(n)` with the number to use for the given region, if any.
167     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
168         self.highlight_regions.iter().find_map(|h| match h {
169             Some((r, n)) if r == region => Some(*n),
170             _ => None,
171         })
172     }
173
174     /// Highlight the given bound region.
175     /// We can only highlight one bound region at a time. See
176     /// the field `highlight_bound_region` for more detailed notes.
177     pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
178         assert!(self.highlight_bound_region.is_none());
179         self.highlight_bound_region = Some((br, number));
180     }
181 }
182
183 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
184 pub trait PrettyPrinter<'tcx>:
185     Printer<
186         'tcx,
187         Error = fmt::Error,
188         Path = Self,
189         Region = Self,
190         Type = Self,
191         DynExistential = Self,
192         Const = Self,
193     > + fmt::Write
194 {
195     /// Like `print_def_path` but for value paths.
196     fn print_value_path(
197         self,
198         def_id: DefId,
199         substs: &'tcx [GenericArg<'tcx>],
200     ) -> Result<Self::Path, Self::Error> {
201         self.print_def_path(def_id, substs)
202     }
203
204     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
205     where
206         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
207     {
208         value.as_ref().skip_binder().print(self)
209     }
210
211     fn wrap_binder<T, F: Fn(&T, Self) -> Result<Self, fmt::Error>>(
212         self,
213         value: &ty::Binder<T>,
214         f: F,
215     ) -> Result<Self, Self::Error>
216     where
217         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
218     {
219         f(value.as_ref().skip_binder(), self)
220     }
221
222     /// Prints comma-separated elements.
223     fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
224     where
225         T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
226     {
227         if let Some(first) = elems.next() {
228             self = first.print(self)?;
229             for elem in elems {
230                 self.write_str(", ")?;
231                 self = elem.print(self)?;
232             }
233         }
234         Ok(self)
235     }
236
237     /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
238     fn typed_value(
239         mut self,
240         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
241         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
242         conversion: &str,
243     ) -> Result<Self::Const, Self::Error> {
244         self.write_str("{")?;
245         self = f(self)?;
246         self.write_str(conversion)?;
247         self = t(self)?;
248         self.write_str("}")?;
249         Ok(self)
250     }
251
252     /// Prints `<...>` around what `f` prints.
253     fn generic_delimiters(
254         self,
255         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
256     ) -> Result<Self, Self::Error>;
257
258     /// Returns `true` if the region should be printed in
259     /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
260     /// This is typically the case for all non-`'_` regions.
261     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool;
262
263     // Defaults (should not be overridden):
264
265     /// If possible, this returns a global path resolving to `def_id` that is visible
266     /// from at least one local module, and returns `true`. If the crate defining `def_id` is
267     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
268     fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
269         let mut callers = Vec::new();
270         self.try_print_visible_def_path_recur(def_id, &mut callers)
271     }
272
273     /// Try to see if this path can be trimmed to a unique symbol name.
274     fn try_print_trimmed_def_path(
275         mut self,
276         def_id: DefId,
277     ) -> Result<(Self::Path, bool), Self::Error> {
278         if !self.tcx().sess.opts.debugging_opts.trim_diagnostic_paths
279             || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
280             || NO_TRIMMED_PATH.with(|flag| flag.get())
281             || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
282         {
283             return Ok((self, false));
284         }
285
286         match self.tcx().trimmed_def_paths(LOCAL_CRATE).get(&def_id) {
287             None => Ok((self, false)),
288             Some(symbol) => {
289                 self.write_str(&symbol.as_str())?;
290                 Ok((self, true))
291             }
292         }
293     }
294
295     /// Does the work of `try_print_visible_def_path`, building the
296     /// full definition path recursively before attempting to
297     /// post-process it into the valid and visible version that
298     /// accounts for re-exports.
299     ///
300     /// This method should only be called by itself or
301     /// `try_print_visible_def_path`.
302     ///
303     /// `callers` is a chain of visible_parent's leading to `def_id`,
304     /// to support cycle detection during recursion.
305     fn try_print_visible_def_path_recur(
306         mut self,
307         def_id: DefId,
308         callers: &mut Vec<DefId>,
309     ) -> Result<(Self, bool), Self::Error> {
310         define_scoped_cx!(self);
311
312         debug!("try_print_visible_def_path: def_id={:?}", def_id);
313
314         // If `def_id` is a direct or injected extern crate, return the
315         // path to the crate followed by the path to the item within the crate.
316         if def_id.index == CRATE_DEF_INDEX {
317             let cnum = def_id.krate;
318
319             if cnum == LOCAL_CRATE {
320                 return Ok((self.path_crate(cnum)?, true));
321             }
322
323             // In local mode, when we encounter a crate other than
324             // LOCAL_CRATE, execution proceeds in one of two ways:
325             //
326             // 1. For a direct dependency, where user added an
327             //    `extern crate` manually, we put the `extern
328             //    crate` as the parent. So you wind up with
329             //    something relative to the current crate.
330             // 2. For an extern inferred from a path or an indirect crate,
331             //    where there is no explicit `extern crate`, we just prepend
332             //    the crate name.
333             match self.tcx().extern_crate(def_id) {
334                 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
335                     (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
336                         debug!("try_print_visible_def_path: def_id={:?}", def_id);
337                         return Ok((
338                             if !span.is_dummy() {
339                                 self.print_def_path(def_id, &[])?
340                             } else {
341                                 self.path_crate(cnum)?
342                             },
343                             true,
344                         ));
345                     }
346                     (ExternCrateSource::Path, LOCAL_CRATE) => {
347                         debug!("try_print_visible_def_path: def_id={:?}", def_id);
348                         return Ok((self.path_crate(cnum)?, true));
349                     }
350                     _ => {}
351                 },
352                 None => {
353                     return Ok((self.path_crate(cnum)?, true));
354                 }
355             }
356         }
357
358         if def_id.is_local() {
359             return Ok((self, false));
360         }
361
362         let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
363
364         let mut cur_def_key = self.tcx().def_key(def_id);
365         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
366
367         // For a constructor, we want the name of its parent rather than <unnamed>.
368         if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
369             let parent = DefId {
370                 krate: def_id.krate,
371                 index: cur_def_key
372                     .parent
373                     .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
374             };
375
376             cur_def_key = self.tcx().def_key(parent);
377         }
378
379         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
380             Some(parent) => parent,
381             None => return Ok((self, false)),
382         };
383         if callers.contains(&visible_parent) {
384             return Ok((self, false));
385         }
386         callers.push(visible_parent);
387         // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
388         // knowing ahead of time whether the entire path will succeed or not.
389         // To support printers that do not implement `PrettyPrinter`, a `Vec` or
390         // linked list on the stack would need to be built, before any printing.
391         match self.try_print_visible_def_path_recur(visible_parent, callers)? {
392             (cx, false) => return Ok((cx, false)),
393             (cx, true) => self = cx,
394         }
395         callers.pop();
396         let actual_parent = self.tcx().parent(def_id);
397         debug!(
398             "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
399             visible_parent, actual_parent,
400         );
401
402         let mut data = cur_def_key.disambiguated_data.data;
403         debug!(
404             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
405             data, visible_parent, actual_parent,
406         );
407
408         match data {
409             // In order to output a path that could actually be imported (valid and visible),
410             // we need to handle re-exports correctly.
411             //
412             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
413             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
414             //
415             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
416             // private so the "true" path to `CommandExt` isn't accessible.
417             //
418             // In this case, the `visible_parent_map` will look something like this:
419             //
420             // (child) -> (parent)
421             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
422             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
423             // `std::sys::unix::ext` -> `std::os`
424             //
425             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
426             // `std::os`.
427             //
428             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
429             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
430             // to the parent - resulting in a mangled path like
431             // `std::os::ext::process::CommandExt`.
432             //
433             // Instead, we must detect that there was a re-export and instead print `unix`
434             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
435             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
436             // the visible parent (`std::os`). If these do not match, then we iterate over
437             // the children of the visible parent (as was done when computing
438             // `visible_parent_map`), looking for the specific child we currently have and then
439             // have access to the re-exported name.
440             DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
441                 let reexport = self
442                     .tcx()
443                     .item_children(visible_parent)
444                     .iter()
445                     .find(|child| child.res.opt_def_id() == Some(def_id))
446                     .map(|child| child.ident.name);
447                 if let Some(reexport) = reexport {
448                     *name = reexport;
449                 }
450             }
451             // Re-exported `extern crate` (#43189).
452             DefPathData::CrateRoot => {
453                 data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate));
454             }
455             _ => {}
456         }
457         debug!("try_print_visible_def_path: data={:?}", data);
458
459         Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
460     }
461
462     fn pretty_path_qualified(
463         self,
464         self_ty: Ty<'tcx>,
465         trait_ref: Option<ty::TraitRef<'tcx>>,
466     ) -> Result<Self::Path, Self::Error> {
467         if trait_ref.is_none() {
468             // Inherent impls. Try to print `Foo::bar` for an inherent
469             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
470             // anything other than a simple path.
471             match self_ty.kind() {
472                 ty::Adt(..)
473                 | ty::Foreign(_)
474                 | ty::Bool
475                 | ty::Char
476                 | ty::Str
477                 | ty::Int(_)
478                 | ty::Uint(_)
479                 | ty::Float(_) => {
480                     return self_ty.print(self);
481                 }
482
483                 _ => {}
484             }
485         }
486
487         self.generic_delimiters(|mut cx| {
488             define_scoped_cx!(cx);
489
490             p!(print(self_ty));
491             if let Some(trait_ref) = trait_ref {
492                 p!(" as ", print(trait_ref.print_only_trait_path()));
493             }
494             Ok(cx)
495         })
496     }
497
498     fn pretty_path_append_impl(
499         mut self,
500         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
501         self_ty: Ty<'tcx>,
502         trait_ref: Option<ty::TraitRef<'tcx>>,
503     ) -> Result<Self::Path, Self::Error> {
504         self = print_prefix(self)?;
505
506         self.generic_delimiters(|mut cx| {
507             define_scoped_cx!(cx);
508
509             p!("impl ");
510             if let Some(trait_ref) = trait_ref {
511                 p!(print(trait_ref.print_only_trait_path()), " for ");
512             }
513             p!(print(self_ty));
514
515             Ok(cx)
516         })
517     }
518
519     fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
520         define_scoped_cx!(self);
521
522         match *ty.kind() {
523             ty::Bool => p!("bool"),
524             ty::Char => p!("char"),
525             ty::Int(t) => p!(write("{}", t.name_str())),
526             ty::Uint(t) => p!(write("{}", t.name_str())),
527             ty::Float(t) => p!(write("{}", t.name_str())),
528             ty::RawPtr(ref tm) => {
529                 p!(write(
530                     "*{} ",
531                     match tm.mutbl {
532                         hir::Mutability::Mut => "mut",
533                         hir::Mutability::Not => "const",
534                     }
535                 ));
536                 p!(print(tm.ty))
537             }
538             ty::Ref(r, ty, mutbl) => {
539                 p!("&");
540                 if self.region_should_not_be_omitted(r) {
541                     p!(print(r), " ");
542                 }
543                 p!(print(ty::TypeAndMut { ty, mutbl }))
544             }
545             ty::Never => p!("!"),
546             ty::Tuple(ref tys) => {
547                 p!("(", comma_sep(tys.iter()));
548                 if tys.len() == 1 {
549                     p!(",");
550                 }
551                 p!(")")
552             }
553             ty::FnDef(def_id, substs) => {
554                 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
555                 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
556             }
557             ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
558             ty::Infer(infer_ty) => {
559                 let verbose = self.tcx().sess.verbose();
560                 if let ty::TyVar(ty_vid) = infer_ty {
561                     if let Some(name) = self.infer_ty_name(ty_vid) {
562                         p!(write("{}", name))
563                     } else {
564                         if verbose {
565                             p!(write("{:?}", infer_ty))
566                         } else {
567                             p!(write("{}", infer_ty))
568                         }
569                     }
570                 } else {
571                     if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
572                 }
573             }
574             ty::Error(_) => p!("[type error]"),
575             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
576             ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
577                 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
578                 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
579             },
580             ty::Adt(def, substs) => {
581                 p!(print_def_path(def.did, substs));
582             }
583             ty::Dynamic(data, r) => {
584                 let print_r = self.region_should_not_be_omitted(r);
585                 if print_r {
586                     p!("(");
587                 }
588                 p!("dyn ", print(data));
589                 if print_r {
590                     p!(" + ", print(r), ")");
591                 }
592             }
593             ty::Foreign(def_id) => {
594                 p!(print_def_path(def_id, &[]));
595             }
596             ty::Projection(ref data) => p!(print(data)),
597             ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
598             ty::Opaque(def_id, substs) => {
599                 // FIXME(eddyb) print this with `print_def_path`.
600                 // We use verbose printing in 'NO_QUERIES' mode, to
601                 // avoid needing to call `predicates_of`. This should
602                 // only affect certain debug messages (e.g. messages printed
603                 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
604                 // and should have no effect on any compiler output.
605                 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
606                     p!(write("Opaque({:?}, {:?})", def_id, substs));
607                     return Ok(self);
608                 }
609
610                 return with_no_queries(|| {
611                     let def_key = self.tcx().def_key(def_id);
612                     if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
613                         p!(write("{}", name));
614                         // FIXME(eddyb) print this with `print_def_path`.
615                         if !substs.is_empty() {
616                             p!("::");
617                             p!(generic_delimiters(|cx| cx.comma_sep(substs.iter())));
618                         }
619                         return Ok(self);
620                     }
621                     // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
622                     // by looking up the projections associated with the def_id.
623                     let bounds = self.tcx().explicit_item_bounds(def_id);
624
625                     let mut first = true;
626                     let mut is_sized = false;
627                     p!("impl");
628                     for (predicate, _) in bounds {
629                         let predicate = predicate.subst(self.tcx(), substs);
630                         let bound_predicate = predicate.kind();
631                         if let ty::PredicateKind::Trait(pred, _) = bound_predicate.skip_binder() {
632                             let trait_ref = bound_predicate.rebind(pred.trait_ref);
633                             // Don't print +Sized, but rather +?Sized if absent.
634                             if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
635                                 is_sized = true;
636                                 continue;
637                             }
638
639                             p!(
640                                 write("{}", if first { " " } else { "+" }),
641                                 print(trait_ref.print_only_trait_path())
642                             );
643                             first = false;
644                         }
645                     }
646                     if !is_sized {
647                         p!(write("{}?Sized", if first { " " } else { "+" }));
648                     } else if first {
649                         p!(" Sized");
650                     }
651                     Ok(self)
652                 });
653             }
654             ty::Str => p!("str"),
655             ty::Generator(did, substs, movability) => {
656                 p!(write("["));
657                 match movability {
658                     hir::Movability::Movable => {}
659                     hir::Movability::Static => p!("static "),
660                 }
661
662                 if !self.tcx().sess.verbose() {
663                     p!("generator");
664                     // FIXME(eddyb) should use `def_span`.
665                     if let Some(did) = did.as_local() {
666                         let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
667                         let span = self.tcx().hir().span(hir_id);
668                         p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
669                     } else {
670                         p!(write("@"), print_def_path(did, substs));
671                     }
672                 } else {
673                     p!(print_def_path(did, substs));
674                     p!(" upvar_tys=(");
675                     if !substs.as_generator().is_valid() {
676                         p!("unavailable");
677                     } else {
678                         self = self.comma_sep(substs.as_generator().upvar_tys())?;
679                     }
680                     p!(")");
681                 }
682
683                 if substs.as_generator().is_valid() {
684                     p!(" ", print(substs.as_generator().witness()));
685                 }
686
687                 p!("]")
688             }
689             ty::GeneratorWitness(types) => {
690                 p!(in_binder(&types));
691             }
692             ty::Closure(did, substs) => {
693                 p!(write("["));
694                 if !self.tcx().sess.verbose() {
695                     p!(write("closure"));
696                     // FIXME(eddyb) should use `def_span`.
697                     if let Some(did) = did.as_local() {
698                         let hir_id = self.tcx().hir().local_def_id_to_hir_id(did);
699                         if self.tcx().sess.opts.debugging_opts.span_free_formats {
700                             p!("@", print_def_path(did.to_def_id(), substs));
701                         } else {
702                             let span = self.tcx().hir().span(hir_id);
703                             p!(write("@{}", self.tcx().sess.source_map().span_to_string(span)));
704                         }
705                     } else {
706                         p!(write("@"), print_def_path(did, substs));
707                     }
708                 } else {
709                     p!(print_def_path(did, substs));
710                     if !substs.as_closure().is_valid() {
711                         p!(" closure_substs=(unavailable)");
712                     } else {
713                         p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
714                         p!(
715                             " closure_sig_as_fn_ptr_ty=",
716                             print(substs.as_closure().sig_as_fn_ptr_ty())
717                         );
718                         p!(" upvar_tys=(");
719                         self = self.comma_sep(substs.as_closure().upvar_tys())?;
720                         p!(")");
721                     }
722                 }
723                 p!("]");
724             }
725             ty::Array(ty, sz) => {
726                 p!("[", print(ty), "; ");
727                 if self.tcx().sess.verbose() {
728                     p!(write("{:?}", sz));
729                 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
730                     // Do not try to evaluate unevaluated constants. If we are const evaluating an
731                     // array length anon const, rustc will (with debug assertions) print the
732                     // constant's path. Which will end up here again.
733                     p!("_");
734                 } else if let Some(n) = sz.val.try_to_bits(self.tcx().data_layout.pointer_size) {
735                     p!(write("{}", n));
736                 } else if let ty::ConstKind::Param(param) = sz.val {
737                     p!(write("{}", param));
738                 } else {
739                     p!("_");
740                 }
741                 p!("]")
742             }
743             ty::Slice(ty) => p!("[", print(ty), "]"),
744         }
745
746         Ok(self)
747     }
748
749     fn pretty_print_bound_var(
750         &mut self,
751         debruijn: ty::DebruijnIndex,
752         var: ty::BoundVar,
753     ) -> Result<(), Self::Error> {
754         if debruijn == ty::INNERMOST {
755             write!(self, "^{}", var.index())
756         } else {
757             write!(self, "^{}_{}", debruijn.index(), var.index())
758         }
759     }
760
761     fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
762         None
763     }
764
765     fn pretty_print_dyn_existential(
766         mut self,
767         predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
768     ) -> Result<Self::DynExistential, Self::Error> {
769         // Generate the main trait ref, including associated types.
770         let mut first = true;
771
772         if let Some(principal) = predicates.principal() {
773             self = self.wrap_binder(&principal, |principal, mut cx| {
774                 define_scoped_cx!(cx);
775                 p!(print_def_path(principal.def_id, &[]));
776
777                 let mut resugared = false;
778
779                 // Special-case `Fn(...) -> ...` and resugar it.
780                 let fn_trait_kind = cx.tcx().fn_trait_kind_from_lang_item(principal.def_id);
781                 if !cx.tcx().sess.verbose() && fn_trait_kind.is_some() {
782                     if let ty::Tuple(ref args) = principal.substs.type_at(0).kind() {
783                         let mut projections = predicates.projection_bounds();
784                         if let (Some(proj), None) = (projections.next(), projections.next()) {
785                             let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
786                             p!(pretty_fn_sig(&tys, false, proj.skip_binder().ty));
787                             resugared = true;
788                         }
789                     }
790                 }
791
792                 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
793                 // in order to place the projections inside the `<...>`.
794                 if !resugared {
795                     // Use a type that can't appear in defaults of type parameters.
796                     let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
797                     let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
798
799                     let args = cx.generic_args_to_print(
800                         cx.tcx().generics_of(principal.def_id),
801                         principal.substs,
802                     );
803
804                     // Don't print `'_` if there's no unerased regions.
805                     let print_regions = args.iter().any(|arg| match arg.unpack() {
806                         GenericArgKind::Lifetime(r) => *r != ty::ReErased,
807                         _ => false,
808                     });
809                     let mut args = args.iter().cloned().filter(|arg| match arg.unpack() {
810                         GenericArgKind::Lifetime(_) => print_regions,
811                         _ => true,
812                     });
813                     let mut projections = predicates.projection_bounds();
814
815                     let arg0 = args.next();
816                     let projection0 = projections.next();
817                     if arg0.is_some() || projection0.is_some() {
818                         let args = arg0.into_iter().chain(args);
819                         let projections = projection0.into_iter().chain(projections);
820
821                         p!(generic_delimiters(|mut cx| {
822                             cx = cx.comma_sep(args)?;
823                             if arg0.is_some() && projection0.is_some() {
824                                 write!(cx, ", ")?;
825                             }
826                             cx.comma_sep(projections)
827                         }));
828                     }
829                 }
830                 Ok(cx)
831             })?;
832
833             first = false;
834         }
835
836         define_scoped_cx!(self);
837
838         // Builtin bounds.
839         // FIXME(eddyb) avoid printing twice (needed to ensure
840         // that the auto traits are sorted *and* printed via cx).
841         let mut auto_traits: Vec<_> =
842             predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect();
843
844         // The auto traits come ordered by `DefPathHash`. While
845         // `DefPathHash` is *stable* in the sense that it depends on
846         // neither the host nor the phase of the moon, it depends
847         // "pseudorandomly" on the compiler version and the target.
848         //
849         // To avoid that causing instabilities in compiletest
850         // output, sort the auto-traits alphabetically.
851         auto_traits.sort();
852
853         for (_, def_id) in auto_traits {
854             if !first {
855                 p!(" + ");
856             }
857             first = false;
858
859             p!(print_def_path(def_id, &[]));
860         }
861
862         Ok(self)
863     }
864
865     fn pretty_fn_sig(
866         mut self,
867         inputs: &[Ty<'tcx>],
868         c_variadic: bool,
869         output: Ty<'tcx>,
870     ) -> Result<Self, Self::Error> {
871         define_scoped_cx!(self);
872
873         p!("(", comma_sep(inputs.iter().copied()));
874         if c_variadic {
875             if !inputs.is_empty() {
876                 p!(", ");
877             }
878             p!("...");
879         }
880         p!(")");
881         if !output.is_unit() {
882             p!(" -> ", print(output));
883         }
884
885         Ok(self)
886     }
887
888     fn pretty_print_const(
889         mut self,
890         ct: &'tcx ty::Const<'tcx>,
891         print_ty: bool,
892     ) -> Result<Self::Const, Self::Error> {
893         define_scoped_cx!(self);
894
895         if self.tcx().sess.verbose() {
896             p!(write("Const({:?}: {:?})", ct.val, ct.ty));
897             return Ok(self);
898         }
899
900         macro_rules! print_underscore {
901             () => {{
902                 if print_ty {
903                     self = self.typed_value(
904                         |mut this| {
905                             write!(this, "_")?;
906                             Ok(this)
907                         },
908                         |this| this.print_type(ct.ty),
909                         ": ",
910                     )?;
911                 } else {
912                     write!(self, "_")?;
913                 }
914             }};
915         }
916
917         match ct.val {
918             ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) => {
919                 if let Some(promoted) = promoted {
920                     p!(print_value_path(def.did, substs));
921                     p!(write("::{:?}", promoted));
922                 } else {
923                     match self.tcx().def_kind(def.did) {
924                         DefKind::Static | DefKind::Const | DefKind::AssocConst => {
925                             p!(print_value_path(def.did, substs))
926                         }
927                         _ => {
928                             if def.is_local() {
929                                 let span = self.tcx().def_span(def.did);
930                                 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
931                                 {
932                                     p!(write("{}", snip))
933                                 } else {
934                                     print_underscore!()
935                                 }
936                             } else {
937                                 print_underscore!()
938                             }
939                         }
940                     }
941                 }
942             }
943             ty::ConstKind::Infer(..) => print_underscore!(),
944             ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
945             ty::ConstKind::Value(value) => {
946                 return self.pretty_print_const_value(value, ct.ty, print_ty);
947             }
948
949             ty::ConstKind::Bound(debruijn, bound_var) => {
950                 self.pretty_print_bound_var(debruijn, bound_var)?
951             }
952             ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
953             ty::ConstKind::Error(_) => p!("[const error]"),
954         };
955         Ok(self)
956     }
957
958     fn pretty_print_const_scalar(
959         self,
960         scalar: Scalar,
961         ty: Ty<'tcx>,
962         print_ty: bool,
963     ) -> Result<Self::Const, Self::Error> {
964         match scalar {
965             Scalar::Ptr(ptr) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
966             Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
967         }
968     }
969
970     fn pretty_print_const_scalar_ptr(
971         mut self,
972         ptr: Pointer,
973         ty: Ty<'tcx>,
974         print_ty: bool,
975     ) -> Result<Self::Const, Self::Error> {
976         define_scoped_cx!(self);
977
978         match ty.kind() {
979             // Byte strings (&[u8; N])
980             ty::Ref(
981                 _,
982                 ty::TyS {
983                     kind:
984                         ty::Array(
985                             ty::TyS { kind: ty::Uint(ty::UintTy::U8), .. },
986                             ty::Const {
987                                 val: ty::ConstKind::Value(ConstValue::Scalar(int)), ..
988                             },
989                         ),
990                     ..
991                 },
992                 _,
993             ) => match self.tcx().get_global_alloc(ptr.alloc_id) {
994                 Some(GlobalAlloc::Memory(alloc)) => {
995                     let bytes = int.assert_bits(self.tcx().data_layout.pointer_size);
996                     let size = Size::from_bytes(bytes);
997                     if let Ok(byte_str) = alloc.get_bytes(&self.tcx(), ptr, size) {
998                         p!(pretty_print_byte_str(byte_str))
999                     } else {
1000                         p!("<too short allocation>")
1001                     }
1002                 }
1003                 // FIXME: for statics and functions, we could in principle print more detail.
1004                 Some(GlobalAlloc::Static(def_id)) => p!(write("<static({:?})>", def_id)),
1005                 Some(GlobalAlloc::Function(_)) => p!("<function>"),
1006                 None => p!("<dangling pointer>"),
1007             },
1008             ty::FnPtr(_) => {
1009                 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1010                 // printing above (which also has to handle pointers to all sorts of things).
1011                 match self.tcx().get_global_alloc(ptr.alloc_id) {
1012                     Some(GlobalAlloc::Function(instance)) => {
1013                         self = self.typed_value(
1014                             |this| this.print_value_path(instance.def_id(), instance.substs),
1015                             |this| this.print_type(ty),
1016                             " as ",
1017                         )?;
1018                     }
1019                     _ => self = self.pretty_print_const_pointer(ptr, ty, print_ty)?,
1020                 }
1021             }
1022             // Any pointer values not covered by a branch above
1023             _ => {
1024                 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
1025             }
1026         }
1027         Ok(self)
1028     }
1029
1030     fn pretty_print_const_scalar_int(
1031         mut self,
1032         int: ScalarInt,
1033         ty: Ty<'tcx>,
1034         print_ty: bool,
1035     ) -> Result<Self::Const, Self::Error> {
1036         define_scoped_cx!(self);
1037
1038         match ty.kind() {
1039             // Bool
1040             ty::Bool if int == ScalarInt::FALSE => p!("false"),
1041             ty::Bool if int == ScalarInt::TRUE => p!("true"),
1042             // Float
1043             ty::Float(ty::FloatTy::F32) => {
1044                 p!(write("{}f32", Single::try_from(int).unwrap()))
1045             }
1046             ty::Float(ty::FloatTy::F64) => {
1047                 p!(write("{}f64", Double::try_from(int).unwrap()))
1048             }
1049             // Int
1050             ty::Uint(_) | ty::Int(_) => {
1051                 let int =
1052                     ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
1053                 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
1054             }
1055             // Char
1056             ty::Char if char::try_from(int).is_ok() => {
1057                 p!(write("{:?}", char::try_from(int).unwrap()))
1058             }
1059             // Raw pointers
1060             ty::RawPtr(_) | ty::FnPtr(_) => {
1061                 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
1062                 self = self.typed_value(
1063                     |mut this| {
1064                         write!(this, "0x{:x}", data)?;
1065                         Ok(this)
1066                     },
1067                     |this| this.print_type(ty),
1068                     " as ",
1069                 )?;
1070             }
1071             // For function type zsts just printing the path is enough
1072             ty::FnDef(d, s) if int == ScalarInt::ZST => {
1073                 p!(print_value_path(*d, s))
1074             }
1075             // Nontrivial types with scalar bit representation
1076             _ => {
1077                 let print = |mut this: Self| {
1078                     if int.size() == Size::ZERO {
1079                         write!(this, "transmute(())")?;
1080                     } else {
1081                         write!(this, "transmute(0x{:x})", int)?;
1082                     }
1083                     Ok(this)
1084                 };
1085                 self = if print_ty {
1086                     self.typed_value(print, |this| this.print_type(ty), ": ")?
1087                 } else {
1088                     print(self)?
1089                 };
1090             }
1091         }
1092         Ok(self)
1093     }
1094
1095     /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1096     /// from MIR where it is actually useful.
1097     fn pretty_print_const_pointer(
1098         mut self,
1099         _: Pointer,
1100         ty: Ty<'tcx>,
1101         print_ty: bool,
1102     ) -> Result<Self::Const, Self::Error> {
1103         if print_ty {
1104             self.typed_value(
1105                 |mut this| {
1106                     this.write_str("&_")?;
1107                     Ok(this)
1108                 },
1109                 |this| this.print_type(ty),
1110                 ": ",
1111             )
1112         } else {
1113             self.write_str("&_")?;
1114             Ok(self)
1115         }
1116     }
1117
1118     fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
1119         define_scoped_cx!(self);
1120         p!("b\"");
1121         for &c in byte_str {
1122             for e in std::ascii::escape_default(c) {
1123                 self.write_char(e as char)?;
1124             }
1125         }
1126         p!("\"");
1127         Ok(self)
1128     }
1129
1130     fn pretty_print_const_value(
1131         mut self,
1132         ct: ConstValue<'tcx>,
1133         ty: Ty<'tcx>,
1134         print_ty: bool,
1135     ) -> Result<Self::Const, Self::Error> {
1136         define_scoped_cx!(self);
1137
1138         if self.tcx().sess.verbose() {
1139             p!(write("ConstValue({:?}: ", ct), print(ty), ")");
1140             return Ok(self);
1141         }
1142
1143         let u8_type = self.tcx().types.u8;
1144
1145         match (ct, ty.kind()) {
1146             // Byte/string slices, printed as (byte) string literals.
1147             (
1148                 ConstValue::Slice { data, start, end },
1149                 ty::Ref(_, ty::TyS { kind: ty::Slice(t), .. }, _),
1150             ) if *t == u8_type => {
1151                 // The `inspect` here is okay since we checked the bounds, and there are
1152                 // no relocations (we have an active slice reference here). We don't use
1153                 // this result to affect interpreter execution.
1154                 let byte_str = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1155                 self.pretty_print_byte_str(byte_str)
1156             }
1157             (
1158                 ConstValue::Slice { data, start, end },
1159                 ty::Ref(_, ty::TyS { kind: ty::Str, .. }, _),
1160             ) => {
1161                 // The `inspect` here is okay since we checked the bounds, and there are no
1162                 // relocations (we have an active `str` reference here). We don't use this
1163                 // result to affect interpreter execution.
1164                 let slice = data.inspect_with_uninit_and_ptr_outside_interpreter(start..end);
1165                 let s = std::str::from_utf8(slice).expect("non utf8 str from miri");
1166                 p!(write("{:?}", s));
1167                 Ok(self)
1168             }
1169             (ConstValue::ByRef { alloc, offset }, ty::Array(t, n)) if *t == u8_type => {
1170                 let n = n.val.try_to_bits(self.tcx().data_layout.pointer_size).unwrap();
1171                 // cast is ok because we already checked for pointer size (32 or 64 bit) above
1172                 let n = Size::from_bytes(n);
1173                 let ptr = Pointer::new(AllocId(0), offset);
1174
1175                 let byte_str = alloc.get_bytes(&self.tcx(), ptr, n).unwrap();
1176                 p!("*");
1177                 p!(pretty_print_byte_str(byte_str));
1178                 Ok(self)
1179             }
1180
1181             // Aggregates, printed as array/tuple/struct/variant construction syntax.
1182             //
1183             // NB: the `has_param_types_or_consts` check ensures that we can use
1184             // the `destructure_const` query with an empty `ty::ParamEnv` without
1185             // introducing ICEs (e.g. via `layout_of`) from missing bounds.
1186             // E.g. `transmute([0usize; 2]): (u8, *mut T)` needs to know `T: Sized`
1187             // to be able to destructure the tuple into `(0u8, *mut T)
1188             //
1189             // FIXME(eddyb) for `--emit=mir`/`-Z dump-mir`, we should provide the
1190             // correct `ty::ParamEnv` to allow printing *all* constant values.
1191             (_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_param_types_or_consts() => {
1192                 let contents = self.tcx().destructure_const(
1193                     ty::ParamEnv::reveal_all()
1194                         .and(self.tcx().mk_const(ty::Const { val: ty::ConstKind::Value(ct), ty })),
1195                 );
1196                 let fields = contents.fields.iter().copied();
1197
1198                 match *ty.kind() {
1199                     ty::Array(..) => {
1200                         p!("[", comma_sep(fields), "]");
1201                     }
1202                     ty::Tuple(..) => {
1203                         p!("(", comma_sep(fields));
1204                         if contents.fields.len() == 1 {
1205                             p!(",");
1206                         }
1207                         p!(")");
1208                     }
1209                     ty::Adt(def, substs) if def.variants.is_empty() => {
1210                         p!(print_value_path(def.did, substs));
1211                     }
1212                     ty::Adt(def, substs) => {
1213                         let variant_id =
1214                             contents.variant.expect("destructed const of adt without variant id");
1215                         let variant_def = &def.variants[variant_id];
1216                         p!(print_value_path(variant_def.def_id, substs));
1217
1218                         match variant_def.ctor_kind {
1219                             CtorKind::Const => {}
1220                             CtorKind::Fn => {
1221                                 p!("(", comma_sep(fields), ")");
1222                             }
1223                             CtorKind::Fictive => {
1224                                 p!(" {{ ");
1225                                 let mut first = true;
1226                                 for (field_def, field) in variant_def.fields.iter().zip(fields) {
1227                                     if !first {
1228                                         p!(", ");
1229                                     }
1230                                     p!(write("{}: ", field_def.ident), print(field));
1231                                     first = false;
1232                                 }
1233                                 p!(" }}");
1234                             }
1235                         }
1236                     }
1237                     _ => unreachable!(),
1238                 }
1239
1240                 Ok(self)
1241             }
1242
1243             (ConstValue::Scalar(scalar), _) => self.pretty_print_const_scalar(scalar, ty, print_ty),
1244
1245             // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1246             // their fields instead of just dumping the memory.
1247             _ => {
1248                 // fallback
1249                 p!(write("{:?}", ct));
1250                 if print_ty {
1251                     p!(": ", print(ty));
1252                 }
1253                 Ok(self)
1254             }
1255         }
1256     }
1257 }
1258
1259 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1260 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1261
1262 pub struct FmtPrinterData<'a, 'tcx, F> {
1263     tcx: TyCtxt<'tcx>,
1264     fmt: F,
1265
1266     empty_path: bool,
1267     in_value: bool,
1268     pub print_alloc_ids: bool,
1269
1270     used_region_names: FxHashSet<Symbol>,
1271     region_index: usize,
1272     binder_depth: usize,
1273     printed_type_count: usize,
1274
1275     pub region_highlight_mode: RegionHighlightMode,
1276
1277     pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
1278 }
1279
1280 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1281     type Target = FmtPrinterData<'a, 'tcx, F>;
1282     fn deref(&self) -> &Self::Target {
1283         &self.0
1284     }
1285 }
1286
1287 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1288     fn deref_mut(&mut self) -> &mut Self::Target {
1289         &mut self.0
1290     }
1291 }
1292
1293 impl<F> FmtPrinter<'a, 'tcx, F> {
1294     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1295         FmtPrinter(Box::new(FmtPrinterData {
1296             tcx,
1297             fmt,
1298             empty_path: false,
1299             in_value: ns == Namespace::ValueNS,
1300             print_alloc_ids: false,
1301             used_region_names: Default::default(),
1302             region_index: 0,
1303             binder_depth: 0,
1304             printed_type_count: 0,
1305             region_highlight_mode: RegionHighlightMode::default(),
1306             name_resolver: None,
1307         }))
1308     }
1309 }
1310
1311 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1312 // (but also some things just print a `DefId` generally so maybe we need this?)
1313 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1314     match tcx.def_key(def_id).disambiguated_data.data {
1315         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1316             Namespace::TypeNS
1317         }
1318
1319         DefPathData::ValueNs(..)
1320         | DefPathData::AnonConst
1321         | DefPathData::ClosureExpr
1322         | DefPathData::Ctor => Namespace::ValueNS,
1323
1324         DefPathData::MacroNs(..) => Namespace::MacroNS,
1325
1326         _ => Namespace::TypeNS,
1327     }
1328 }
1329
1330 impl TyCtxt<'t> {
1331     /// Returns a string identifying this `DefId`. This string is
1332     /// suitable for user output.
1333     pub fn def_path_str(self, def_id: DefId) -> String {
1334         self.def_path_str_with_substs(def_id, &[])
1335     }
1336
1337     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1338         let ns = guess_def_namespace(self, def_id);
1339         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1340         let mut s = String::new();
1341         let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1342         s
1343     }
1344 }
1345
1346 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1347     fn write_str(&mut self, s: &str) -> fmt::Result {
1348         self.fmt.write_str(s)
1349     }
1350 }
1351
1352 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1353     type Error = fmt::Error;
1354
1355     type Path = Self;
1356     type Region = Self;
1357     type Type = Self;
1358     type DynExistential = Self;
1359     type Const = Self;
1360
1361     fn tcx(&'a self) -> TyCtxt<'tcx> {
1362         self.tcx
1363     }
1364
1365     fn print_def_path(
1366         mut self,
1367         def_id: DefId,
1368         substs: &'tcx [GenericArg<'tcx>],
1369     ) -> Result<Self::Path, Self::Error> {
1370         define_scoped_cx!(self);
1371
1372         if substs.is_empty() {
1373             match self.try_print_trimmed_def_path(def_id)? {
1374                 (cx, true) => return Ok(cx),
1375                 (cx, false) => self = cx,
1376             }
1377
1378             match self.try_print_visible_def_path(def_id)? {
1379                 (cx, true) => return Ok(cx),
1380                 (cx, false) => self = cx,
1381             }
1382         }
1383
1384         let key = self.tcx.def_key(def_id);
1385         if let DefPathData::Impl = key.disambiguated_data.data {
1386             // Always use types for non-local impls, where types are always
1387             // available, and filename/line-number is mostly uninteresting.
1388             let use_types = !def_id.is_local() || {
1389                 // Otherwise, use filename/line-number if forced.
1390                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1391                 !force_no_types
1392             };
1393
1394             if !use_types {
1395                 // If no type info is available, fall back to
1396                 // pretty printing some span information. This should
1397                 // only occur very early in the compiler pipeline.
1398                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1399                 let span = self.tcx.def_span(def_id);
1400
1401                 self = self.print_def_path(parent_def_id, &[])?;
1402
1403                 // HACK(eddyb) copy of `path_append` to avoid
1404                 // constructing a `DisambiguatedDefPathData`.
1405                 if !self.empty_path {
1406                     write!(self, "::")?;
1407                 }
1408                 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1409                 self.empty_path = false;
1410
1411                 return Ok(self);
1412             }
1413         }
1414
1415         self.default_print_def_path(def_id, substs)
1416     }
1417
1418     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1419         self.pretty_print_region(region)
1420     }
1421
1422     fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1423         if self.tcx.sess.type_length_limit().value_within_limit(self.printed_type_count) {
1424             self.printed_type_count += 1;
1425             self.pretty_print_type(ty)
1426         } else {
1427             write!(self, "...")?;
1428             Ok(self)
1429         }
1430     }
1431
1432     fn print_dyn_existential(
1433         self,
1434         predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1435     ) -> Result<Self::DynExistential, Self::Error> {
1436         self.pretty_print_dyn_existential(predicates)
1437     }
1438
1439     fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1440         self.pretty_print_const(ct, true)
1441     }
1442
1443     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1444         self.empty_path = true;
1445         if cnum == LOCAL_CRATE {
1446             if self.tcx.sess.rust_2018() {
1447                 // We add the `crate::` keyword on Rust 2018, only when desired.
1448                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1449                     write!(self, "{}", kw::Crate)?;
1450                     self.empty_path = false;
1451                 }
1452             }
1453         } else {
1454             write!(self, "{}", self.tcx.crate_name(cnum))?;
1455             self.empty_path = false;
1456         }
1457         Ok(self)
1458     }
1459
1460     fn path_qualified(
1461         mut self,
1462         self_ty: Ty<'tcx>,
1463         trait_ref: Option<ty::TraitRef<'tcx>>,
1464     ) -> Result<Self::Path, Self::Error> {
1465         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1466         self.empty_path = false;
1467         Ok(self)
1468     }
1469
1470     fn path_append_impl(
1471         mut self,
1472         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1473         _disambiguated_data: &DisambiguatedDefPathData,
1474         self_ty: Ty<'tcx>,
1475         trait_ref: Option<ty::TraitRef<'tcx>>,
1476     ) -> Result<Self::Path, Self::Error> {
1477         self = self.pretty_path_append_impl(
1478             |mut cx| {
1479                 cx = print_prefix(cx)?;
1480                 if !cx.empty_path {
1481                     write!(cx, "::")?;
1482                 }
1483
1484                 Ok(cx)
1485             },
1486             self_ty,
1487             trait_ref,
1488         )?;
1489         self.empty_path = false;
1490         Ok(self)
1491     }
1492
1493     fn path_append(
1494         mut self,
1495         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1496         disambiguated_data: &DisambiguatedDefPathData,
1497     ) -> Result<Self::Path, Self::Error> {
1498         self = print_prefix(self)?;
1499
1500         // Skip `::{{constructor}}` on tuple/unit structs.
1501         if let DefPathData::Ctor = disambiguated_data.data {
1502             return Ok(self);
1503         }
1504
1505         // FIXME(eddyb) `name` should never be empty, but it
1506         // currently is for `extern { ... }` "foreign modules".
1507         let name = disambiguated_data.data.name();
1508         if name != DefPathDataName::Named(kw::Empty) {
1509             if !self.empty_path {
1510                 write!(self, "::")?;
1511             }
1512
1513             if let DefPathDataName::Named(name) = name {
1514                 if Ident::with_dummy_span(name).is_raw_guess() {
1515                     write!(self, "r#")?;
1516                 }
1517             }
1518
1519             let verbose = self.tcx.sess.verbose();
1520             disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1521
1522             self.empty_path = false;
1523         }
1524
1525         Ok(self)
1526     }
1527
1528     fn path_generic_args(
1529         mut self,
1530         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1531         args: &[GenericArg<'tcx>],
1532     ) -> Result<Self::Path, Self::Error> {
1533         self = print_prefix(self)?;
1534
1535         // Don't print `'_` if there's no unerased regions.
1536         let print_regions = args.iter().any(|arg| match arg.unpack() {
1537             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1538             _ => false,
1539         });
1540         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1541             GenericArgKind::Lifetime(_) => print_regions,
1542             _ => true,
1543         });
1544
1545         if args.clone().next().is_some() {
1546             if self.in_value {
1547                 write!(self, "::")?;
1548             }
1549             self.generic_delimiters(|cx| cx.comma_sep(args))
1550         } else {
1551             Ok(self)
1552         }
1553     }
1554 }
1555
1556 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1557     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1558         self.0.name_resolver.as_ref().and_then(|func| func(id))
1559     }
1560
1561     fn print_value_path(
1562         mut self,
1563         def_id: DefId,
1564         substs: &'tcx [GenericArg<'tcx>],
1565     ) -> Result<Self::Path, Self::Error> {
1566         let was_in_value = std::mem::replace(&mut self.in_value, true);
1567         self = self.print_def_path(def_id, substs)?;
1568         self.in_value = was_in_value;
1569
1570         Ok(self)
1571     }
1572
1573     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1574     where
1575         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1576     {
1577         self.pretty_in_binder(value)
1578     }
1579
1580     fn wrap_binder<T, C: Fn(&T, Self) -> Result<Self, Self::Error>>(
1581         self,
1582         value: &ty::Binder<T>,
1583         f: C,
1584     ) -> Result<Self, Self::Error>
1585     where
1586         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1587     {
1588         self.pretty_wrap_binder(value, f)
1589     }
1590
1591     fn typed_value(
1592         mut self,
1593         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1594         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1595         conversion: &str,
1596     ) -> Result<Self::Const, Self::Error> {
1597         self.write_str("{")?;
1598         self = f(self)?;
1599         self.write_str(conversion)?;
1600         let was_in_value = std::mem::replace(&mut self.in_value, false);
1601         self = t(self)?;
1602         self.in_value = was_in_value;
1603         self.write_str("}")?;
1604         Ok(self)
1605     }
1606
1607     fn generic_delimiters(
1608         mut self,
1609         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1610     ) -> Result<Self, Self::Error> {
1611         write!(self, "<")?;
1612
1613         let was_in_value = std::mem::replace(&mut self.in_value, false);
1614         let mut inner = f(self)?;
1615         inner.in_value = was_in_value;
1616
1617         write!(inner, ">")?;
1618         Ok(inner)
1619     }
1620
1621     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1622         let highlight = self.region_highlight_mode;
1623         if highlight.region_highlighted(region).is_some() {
1624             return true;
1625         }
1626
1627         if self.tcx.sess.verbose() {
1628             return true;
1629         }
1630
1631         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1632
1633         match *region {
1634             ty::ReEarlyBound(ref data) => {
1635                 data.name != kw::Empty && data.name != kw::UnderscoreLifetime
1636             }
1637
1638             ty::ReLateBound(_, ty::BoundRegion { kind: br })
1639             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1640             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1641                 if let ty::BrNamed(_, name) = br {
1642                     if name != kw::Empty && name != kw::UnderscoreLifetime {
1643                         return true;
1644                     }
1645                 }
1646
1647                 if let Some((region, _)) = highlight.highlight_bound_region {
1648                     if br == region {
1649                         return true;
1650                     }
1651                 }
1652
1653                 false
1654             }
1655
1656             ty::ReVar(_) if identify_regions => true,
1657
1658             ty::ReVar(_) | ty::ReErased => false,
1659
1660             ty::ReStatic | ty::ReEmpty(_) => true,
1661         }
1662     }
1663
1664     fn pretty_print_const_pointer(
1665         self,
1666         p: Pointer,
1667         ty: Ty<'tcx>,
1668         print_ty: bool,
1669     ) -> Result<Self::Const, Self::Error> {
1670         let print = |mut this: Self| {
1671             define_scoped_cx!(this);
1672             if this.print_alloc_ids {
1673                 p!(write("{:?}", p));
1674             } else {
1675                 p!("&_");
1676             }
1677             Ok(this)
1678         };
1679         if print_ty {
1680             self.typed_value(print, |this| this.print_type(ty), ": ")
1681         } else {
1682             print(self)
1683         }
1684     }
1685 }
1686
1687 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1688 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1689     pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1690         define_scoped_cx!(self);
1691
1692         // Watch out for region highlights.
1693         let highlight = self.region_highlight_mode;
1694         if let Some(n) = highlight.region_highlighted(region) {
1695             p!(write("'{}", n));
1696             return Ok(self);
1697         }
1698
1699         if self.tcx.sess.verbose() {
1700             p!(write("{:?}", region));
1701             return Ok(self);
1702         }
1703
1704         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1705
1706         // These printouts are concise.  They do not contain all the information
1707         // the user might want to diagnose an error, but there is basically no way
1708         // to fit that into a short string.  Hence the recommendation to use
1709         // `explain_region()` or `note_and_explain_region()`.
1710         match *region {
1711             ty::ReEarlyBound(ref data) => {
1712                 if data.name != kw::Empty {
1713                     p!(write("{}", data.name));
1714                     return Ok(self);
1715                 }
1716             }
1717             ty::ReLateBound(_, ty::BoundRegion { kind: br })
1718             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1719             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1720                 if let ty::BrNamed(_, name) = br {
1721                     if name != kw::Empty && name != kw::UnderscoreLifetime {
1722                         p!(write("{}", name));
1723                         return Ok(self);
1724                     }
1725                 }
1726
1727                 if let Some((region, counter)) = highlight.highlight_bound_region {
1728                     if br == region {
1729                         p!(write("'{}", counter));
1730                         return Ok(self);
1731                     }
1732                 }
1733             }
1734             ty::ReVar(region_vid) if identify_regions => {
1735                 p!(write("{:?}", region_vid));
1736                 return Ok(self);
1737             }
1738             ty::ReVar(_) => {}
1739             ty::ReErased => {}
1740             ty::ReStatic => {
1741                 p!("'static");
1742                 return Ok(self);
1743             }
1744             ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1745                 p!("'<empty>");
1746                 return Ok(self);
1747             }
1748             ty::ReEmpty(ui) => {
1749                 p!(write("'<empty:{:?}>", ui));
1750                 return Ok(self);
1751             }
1752         }
1753
1754         p!("'_");
1755
1756         Ok(self)
1757     }
1758 }
1759
1760 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1761 // `region_index` and `used_region_names`.
1762 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1763     pub fn name_all_regions<T>(
1764         mut self,
1765         value: &ty::Binder<T>,
1766     ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1767     where
1768         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1769     {
1770         fn name_by_region_index(index: usize) -> Symbol {
1771             match index {
1772                 0 => Symbol::intern("'r"),
1773                 1 => Symbol::intern("'s"),
1774                 i => Symbol::intern(&format!("'t{}", i - 2)),
1775             }
1776         }
1777
1778         // Replace any anonymous late-bound regions with named
1779         // variants, using new unique identifiers, so that we can
1780         // clearly differentiate between named and unnamed regions in
1781         // the output. We'll probably want to tweak this over time to
1782         // decide just how much information to give.
1783         if self.binder_depth == 0 {
1784             self.prepare_late_bound_region_info(value);
1785         }
1786
1787         let mut empty = true;
1788         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1789             write!(
1790                 cx,
1791                 "{}",
1792                 if empty {
1793                     empty = false;
1794                     start
1795                 } else {
1796                     cont
1797                 }
1798             )
1799         };
1800
1801         define_scoped_cx!(self);
1802
1803         let mut region_index = self.region_index;
1804         let new_value = self.tcx.replace_late_bound_regions(value.clone(), |br| {
1805             let _ = start_or_continue(&mut self, "for<", ", ");
1806             let kind = match br.kind {
1807                 ty::BrNamed(_, name) => {
1808                     let _ = write!(self, "{}", name);
1809                     br.kind
1810                 }
1811                 ty::BrAnon(_) | ty::BrEnv => {
1812                     let name = loop {
1813                         let name = name_by_region_index(region_index);
1814                         region_index += 1;
1815                         if !self.used_region_names.contains(&name) {
1816                             break name;
1817                         }
1818                     };
1819                     let _ = write!(self, "{}", name);
1820                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1821                 }
1822             };
1823             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { kind }))
1824         });
1825         start_or_continue(&mut self, "", "> ")?;
1826
1827         self.binder_depth += 1;
1828         self.region_index = region_index;
1829         Ok((self, new_value))
1830     }
1831
1832     pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1833     where
1834         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1835     {
1836         let old_region_index = self.region_index;
1837         let (new, new_value) = self.name_all_regions(value)?;
1838         let mut inner = new_value.0.print(new)?;
1839         inner.region_index = old_region_index;
1840         inner.binder_depth -= 1;
1841         Ok(inner)
1842     }
1843
1844     pub fn pretty_wrap_binder<T, C: Fn(&T, Self) -> Result<Self, fmt::Error>>(
1845         self,
1846         value: &ty::Binder<T>,
1847         f: C,
1848     ) -> Result<Self, fmt::Error>
1849     where
1850         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1851     {
1852         let old_region_index = self.region_index;
1853         let (new, new_value) = self.name_all_regions(value)?;
1854         let mut inner = f(&new_value.0, new)?;
1855         inner.region_index = old_region_index;
1856         inner.binder_depth -= 1;
1857         Ok(inner)
1858     }
1859
1860     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1861     where
1862         T: TypeFoldable<'tcx>,
1863     {
1864         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1865         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1866             fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
1867                 if let ty::ReLateBound(_, ty::BoundRegion { kind: ty::BrNamed(_, name) }) = *r {
1868                     self.0.insert(name);
1869                 }
1870                 r.super_visit_with(self)
1871             }
1872         }
1873
1874         self.used_region_names.clear();
1875         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1876         value.visit_with(&mut collector);
1877         self.region_index = 0;
1878     }
1879 }
1880
1881 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1882 where
1883     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1884 {
1885     type Output = P;
1886     type Error = P::Error;
1887     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1888         cx.in_binder(self)
1889     }
1890 }
1891
1892 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1893 where
1894     T: Print<'tcx, P, Output = P, Error = P::Error>,
1895     U: Print<'tcx, P, Output = P, Error = P::Error>,
1896 {
1897     type Output = P;
1898     type Error = P::Error;
1899     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1900         define_scoped_cx!(cx);
1901         p!(print(self.0), ": ", print(self.1));
1902         Ok(cx)
1903     }
1904 }
1905
1906 macro_rules! forward_display_to_print {
1907     ($($ty:ty),+) => {
1908         $(impl fmt::Display for $ty {
1909             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1910                 ty::tls::with(|tcx| {
1911                     tcx.lift(*self)
1912                         .expect("could not lift for printing")
1913                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1914                     Ok(())
1915                 })
1916             }
1917         })+
1918     };
1919 }
1920
1921 macro_rules! define_print_and_forward_display {
1922     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1923         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1924             type Output = P;
1925             type Error = fmt::Error;
1926             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1927                 #[allow(unused_mut)]
1928                 let mut $cx = $cx;
1929                 define_scoped_cx!($cx);
1930                 let _: () = $print;
1931                 #[allow(unreachable_code)]
1932                 Ok($cx)
1933             }
1934         })+
1935
1936         forward_display_to_print!($($ty),+);
1937     };
1938 }
1939
1940 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1941 impl fmt::Display for ty::RegionKind {
1942     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1943         ty::tls::with(|tcx| {
1944             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1945             Ok(())
1946         })
1947     }
1948 }
1949
1950 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1951 /// the trait path. That is, it will print `Trait<U>` instead of
1952 /// `<T as Trait<U>>`.
1953 #[derive(Copy, Clone, TypeFoldable, Lift)]
1954 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1955
1956 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1957     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1958         fmt::Display::fmt(self, f)
1959     }
1960 }
1961
1962 impl ty::TraitRef<'tcx> {
1963     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1964         TraitRefPrintOnlyTraitPath(self)
1965     }
1966 }
1967
1968 impl ty::Binder<ty::TraitRef<'tcx>> {
1969     pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1970         self.map_bound(|tr| tr.print_only_trait_path())
1971     }
1972 }
1973
1974 forward_display_to_print! {
1975     Ty<'tcx>,
1976     &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
1977     &'tcx ty::Const<'tcx>,
1978
1979     // HACK(eddyb) these are exhaustive instead of generic,
1980     // because `for<'tcx>` isn't possible yet.
1981     ty::Binder<ty::ExistentialPredicate<'tcx>>,
1982     ty::Binder<ty::TraitRef<'tcx>>,
1983     ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1984     ty::Binder<ty::FnSig<'tcx>>,
1985     ty::Binder<ty::TraitPredicate<'tcx>>,
1986     ty::Binder<ty::SubtypePredicate<'tcx>>,
1987     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1988     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1989     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1990
1991     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1992     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1993 }
1994
1995 define_print_and_forward_display! {
1996     (self, cx):
1997
1998     &'tcx ty::List<Ty<'tcx>> {
1999         p!("{{", comma_sep(self.iter()), "}}")
2000     }
2001
2002     ty::TypeAndMut<'tcx> {
2003         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
2004     }
2005
2006     ty::ExistentialTraitRef<'tcx> {
2007         // Use a type that can't appear in defaults of type parameters.
2008         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
2009         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
2010         p!(print(trait_ref.print_only_trait_path()))
2011     }
2012
2013     ty::ExistentialProjection<'tcx> {
2014         let name = cx.tcx().associated_item(self.item_def_id).ident;
2015         p!(write("{} = ", name), print(self.ty))
2016     }
2017
2018     ty::ExistentialPredicate<'tcx> {
2019         match *self {
2020             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2021             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2022             ty::ExistentialPredicate::AutoTrait(def_id) => {
2023                 p!(print_def_path(def_id, &[]));
2024             }
2025         }
2026     }
2027
2028     ty::FnSig<'tcx> {
2029         p!(write("{}", self.unsafety.prefix_str()));
2030
2031         if self.abi != Abi::Rust {
2032             p!(write("extern {} ", self.abi));
2033         }
2034
2035         p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
2036     }
2037
2038     ty::TraitRef<'tcx> {
2039         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2040     }
2041
2042     TraitRefPrintOnlyTraitPath<'tcx> {
2043         p!(print_def_path(self.0.def_id, self.0.substs));
2044     }
2045
2046     ty::ParamTy {
2047         p!(write("{}", self.name))
2048     }
2049
2050     ty::ParamConst {
2051         p!(write("{}", self.name))
2052     }
2053
2054     ty::SubtypePredicate<'tcx> {
2055         p!(print(self.a), " <: ", print(self.b))
2056     }
2057
2058     ty::TraitPredicate<'tcx> {
2059         p!(print(self.trait_ref.self_ty()), ": ",
2060            print(self.trait_ref.print_only_trait_path()))
2061     }
2062
2063     ty::ProjectionPredicate<'tcx> {
2064         p!(print(self.projection_ty), " == ", print(self.ty))
2065     }
2066
2067     ty::ProjectionTy<'tcx> {
2068         p!(print_def_path(self.item_def_id, self.substs));
2069     }
2070
2071     ty::ClosureKind {
2072         match *self {
2073             ty::ClosureKind::Fn => p!("Fn"),
2074             ty::ClosureKind::FnMut => p!("FnMut"),
2075             ty::ClosureKind::FnOnce => p!("FnOnce"),
2076         }
2077     }
2078
2079     ty::Predicate<'tcx> {
2080         let binder = self.kind();
2081         p!(print(binder))
2082     }
2083
2084     ty::PredicateKind<'tcx> {
2085         match *self {
2086             ty::PredicateKind::Trait(ref data, constness) => {
2087                 if let hir::Constness::Const = constness {
2088                     p!("const ");
2089                 }
2090                 p!(print(data))
2091             }
2092             ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
2093             ty::PredicateKind::RegionOutlives(predicate) => p!(print(predicate)),
2094             ty::PredicateKind::TypeOutlives(predicate) => p!(print(predicate)),
2095             ty::PredicateKind::Projection(predicate) => p!(print(predicate)),
2096             ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2097             ty::PredicateKind::ObjectSafe(trait_def_id) => {
2098                 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
2099             }
2100             ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
2101                 p!("the closure `",
2102                 print_value_path(closure_def_id, &[]),
2103                 write("` implements the trait `{}`", kind))
2104             }
2105             ty::PredicateKind::ConstEvaluatable(def, substs) => {
2106                 p!("the constant `", print_value_path(def.did, substs), "` can be evaluated")
2107             }
2108             ty::PredicateKind::ConstEquate(c1, c2) => {
2109                 p!("the constant `", print(c1), "` equals `", print(c2), "`")
2110             }
2111             ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
2112                 p!("the type `", print(ty), "` is found in the environment")
2113             }
2114         }
2115     }
2116
2117     GenericArg<'tcx> {
2118         match self.unpack() {
2119             GenericArgKind::Lifetime(lt) => p!(print(lt)),
2120             GenericArgKind::Type(ty) => p!(print(ty)),
2121             GenericArgKind::Const(ct) => p!(print(ct)),
2122         }
2123     }
2124 }
2125
2126 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2127     // Iterate all local crate items no matter where they are defined.
2128     let hir = tcx.hir();
2129     for item in hir.krate().items.values() {
2130         if item.ident.name.as_str().is_empty() || matches!(item.kind, ItemKind::Use(_, _)) {
2131             continue;
2132         }
2133
2134         let def_id = item.def_id.to_def_id();
2135         let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2136         collect_fn(&item.ident, ns, def_id);
2137     }
2138
2139     // Now take care of extern crate items.
2140     let queue = &mut Vec::new();
2141     let mut seen_defs: DefIdSet = Default::default();
2142
2143     for &cnum in tcx.crates().iter() {
2144         let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2145
2146         // Ignore crates that are not direct dependencies.
2147         match tcx.extern_crate(def_id) {
2148             None => continue,
2149             Some(extern_crate) => {
2150                 if !extern_crate.is_direct() {
2151                     continue;
2152                 }
2153             }
2154         }
2155
2156         queue.push(def_id);
2157     }
2158
2159     // Iterate external crate defs but be mindful about visibility
2160     while let Some(def) = queue.pop() {
2161         for child in tcx.item_children(def).iter() {
2162             if child.vis != ty::Visibility::Public {
2163                 continue;
2164             }
2165
2166             match child.res {
2167                 def::Res::Def(DefKind::AssocTy, _) => {}
2168                 def::Res::Def(DefKind::TyAlias, _) => {}
2169                 def::Res::Def(defkind, def_id) => {
2170                     if let Some(ns) = defkind.ns() {
2171                         collect_fn(&child.ident, ns, def_id);
2172                     }
2173
2174                     if seen_defs.insert(def_id) {
2175                         queue.push(def_id);
2176                     }
2177                 }
2178                 _ => {}
2179             }
2180         }
2181     }
2182 }
2183
2184 /// The purpose of this function is to collect public symbols names that are unique across all
2185 /// crates in the build. Later, when printing about types we can use those names instead of the
2186 /// full exported path to them.
2187 ///
2188 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2189 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2190 /// path and print only the name.
2191 ///
2192 /// This has wide implications on error messages with types, for example, shortening
2193 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2194 ///
2195 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2196 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2197     assert_eq!(crate_num, LOCAL_CRATE);
2198
2199     let mut map = FxHashMap::default();
2200
2201     if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2202         // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2203         // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2204         tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2205     }
2206
2207     let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2208         &mut FxHashMap::default();
2209
2210     for symbol_set in tcx.glob_map.values() {
2211         for symbol in symbol_set {
2212             unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2213             unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2214             unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2215         }
2216     }
2217
2218     for_each_def(tcx, |ident, ns, def_id| {
2219         use std::collections::hash_map::Entry::{Occupied, Vacant};
2220
2221         match unique_symbols_rev.entry((ns, ident.name)) {
2222             Occupied(mut v) => match v.get() {
2223                 None => {}
2224                 Some(existing) => {
2225                     if *existing != def_id {
2226                         v.insert(None);
2227                     }
2228                 }
2229             },
2230             Vacant(v) => {
2231                 v.insert(Some(def_id));
2232             }
2233         }
2234     });
2235
2236     for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2237         if let Some(def_id) = opt_def_id {
2238             map.insert(def_id, symbol);
2239         }
2240     }
2241
2242     map
2243 }
2244
2245 pub fn provide(providers: &mut ty::query::Providers) {
2246     *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2247 }