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