]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/print/pretty.rs
use iter:: before free functions
[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, 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
1268     pub region_highlight_mode: RegionHighlightMode,
1269
1270     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1271 }
1272
1273 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1274     type Target = FmtPrinterData<'a, 'tcx, F>;
1275     fn deref(&self) -> &Self::Target {
1276         &self.0
1277     }
1278 }
1279
1280 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1281     fn deref_mut(&mut self) -> &mut Self::Target {
1282         &mut self.0
1283     }
1284 }
1285
1286 impl<F> FmtPrinter<'a, 'tcx, F> {
1287     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1288         FmtPrinter(Box::new(FmtPrinterData {
1289             tcx,
1290             fmt,
1291             empty_path: false,
1292             in_value: ns == Namespace::ValueNS,
1293             print_alloc_ids: false,
1294             used_region_names: Default::default(),
1295             region_index: 0,
1296             binder_depth: 0,
1297             region_highlight_mode: RegionHighlightMode::default(),
1298             name_resolver: None,
1299         }))
1300     }
1301 }
1302
1303 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1304 // (but also some things just print a `DefId` generally so maybe we need this?)
1305 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1306     match tcx.def_key(def_id).disambiguated_data.data {
1307         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1308             Namespace::TypeNS
1309         }
1310
1311         DefPathData::ValueNs(..)
1312         | DefPathData::AnonConst
1313         | DefPathData::ClosureExpr
1314         | DefPathData::Ctor => Namespace::ValueNS,
1315
1316         DefPathData::MacroNs(..) => Namespace::MacroNS,
1317
1318         _ => Namespace::TypeNS,
1319     }
1320 }
1321
1322 impl TyCtxt<'t> {
1323     /// Returns a string identifying this `DefId`. This string is
1324     /// suitable for user output.
1325     pub fn def_path_str(self, def_id: DefId) -> String {
1326         self.def_path_str_with_substs(def_id, &[])
1327     }
1328
1329     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1330         let ns = guess_def_namespace(self, def_id);
1331         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1332         let mut s = String::new();
1333         let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1334         s
1335     }
1336 }
1337
1338 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1339     fn write_str(&mut self, s: &str) -> fmt::Result {
1340         self.fmt.write_str(s)
1341     }
1342 }
1343
1344 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1345     type Error = fmt::Error;
1346
1347     type Path = Self;
1348     type Region = Self;
1349     type Type = Self;
1350     type DynExistential = Self;
1351     type Const = Self;
1352
1353     fn tcx(&'a self) -> TyCtxt<'tcx> {
1354         self.tcx
1355     }
1356
1357     fn print_def_path(
1358         mut self,
1359         def_id: DefId,
1360         substs: &'tcx [GenericArg<'tcx>],
1361     ) -> Result<Self::Path, Self::Error> {
1362         define_scoped_cx!(self);
1363
1364         if substs.is_empty() {
1365             match self.try_print_trimmed_def_path(def_id)? {
1366                 (cx, true) => return Ok(cx),
1367                 (cx, false) => self = cx,
1368             }
1369
1370             match self.try_print_visible_def_path(def_id)? {
1371                 (cx, true) => return Ok(cx),
1372                 (cx, false) => self = cx,
1373             }
1374         }
1375
1376         let key = self.tcx.def_key(def_id);
1377         if let DefPathData::Impl = key.disambiguated_data.data {
1378             // Always use types for non-local impls, where types are always
1379             // available, and filename/line-number is mostly uninteresting.
1380             let use_types = !def_id.is_local() || {
1381                 // Otherwise, use filename/line-number if forced.
1382                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1383                 !force_no_types
1384             };
1385
1386             if !use_types {
1387                 // If no type info is available, fall back to
1388                 // pretty printing some span information. This should
1389                 // only occur very early in the compiler pipeline.
1390                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1391                 let span = self.tcx.def_span(def_id);
1392
1393                 self = self.print_def_path(parent_def_id, &[])?;
1394
1395                 // HACK(eddyb) copy of `path_append` to avoid
1396                 // constructing a `DisambiguatedDefPathData`.
1397                 if !self.empty_path {
1398                     write!(self, "::")?;
1399                 }
1400                 write!(self, "<impl at {}>", self.tcx.sess.source_map().span_to_string(span))?;
1401                 self.empty_path = false;
1402
1403                 return Ok(self);
1404             }
1405         }
1406
1407         self.default_print_def_path(def_id, substs)
1408     }
1409
1410     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1411         self.pretty_print_region(region)
1412     }
1413
1414     fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1415         self.pretty_print_type(ty)
1416     }
1417
1418     fn print_dyn_existential(
1419         self,
1420         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1421     ) -> Result<Self::DynExistential, Self::Error> {
1422         self.pretty_print_dyn_existential(predicates)
1423     }
1424
1425     fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1426         self.pretty_print_const(ct, true)
1427     }
1428
1429     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1430         self.empty_path = true;
1431         if cnum == LOCAL_CRATE {
1432             if self.tcx.sess.rust_2018() {
1433                 // We add the `crate::` keyword on Rust 2018, only when desired.
1434                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1435                     write!(self, "{}", kw::Crate)?;
1436                     self.empty_path = false;
1437                 }
1438             }
1439         } else {
1440             write!(self, "{}", self.tcx.crate_name(cnum))?;
1441             self.empty_path = false;
1442         }
1443         Ok(self)
1444     }
1445
1446     fn path_qualified(
1447         mut self,
1448         self_ty: Ty<'tcx>,
1449         trait_ref: Option<ty::TraitRef<'tcx>>,
1450     ) -> Result<Self::Path, Self::Error> {
1451         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1452         self.empty_path = false;
1453         Ok(self)
1454     }
1455
1456     fn path_append_impl(
1457         mut self,
1458         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1459         _disambiguated_data: &DisambiguatedDefPathData,
1460         self_ty: Ty<'tcx>,
1461         trait_ref: Option<ty::TraitRef<'tcx>>,
1462     ) -> Result<Self::Path, Self::Error> {
1463         self = self.pretty_path_append_impl(
1464             |mut cx| {
1465                 cx = print_prefix(cx)?;
1466                 if !cx.empty_path {
1467                     write!(cx, "::")?;
1468                 }
1469
1470                 Ok(cx)
1471             },
1472             self_ty,
1473             trait_ref,
1474         )?;
1475         self.empty_path = false;
1476         Ok(self)
1477     }
1478
1479     fn path_append(
1480         mut self,
1481         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1482         disambiguated_data: &DisambiguatedDefPathData,
1483     ) -> Result<Self::Path, Self::Error> {
1484         self = print_prefix(self)?;
1485
1486         // Skip `::{{constructor}}` on tuple/unit structs.
1487         if let DefPathData::Ctor = disambiguated_data.data {
1488             return Ok(self);
1489         }
1490
1491         // FIXME(eddyb) `name` should never be empty, but it
1492         // currently is for `extern { ... }` "foreign modules".
1493         let name = disambiguated_data.data.as_symbol();
1494         if name != kw::Invalid {
1495             if !self.empty_path {
1496                 write!(self, "::")?;
1497             }
1498             if Ident::with_dummy_span(name).is_raw_guess() {
1499                 write!(self, "r#")?;
1500             }
1501             write!(self, "{}", name)?;
1502
1503             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1504             // might be nicer to use something else, e.g. `{closure#3}`.
1505             let dis = disambiguated_data.disambiguator;
1506             let print_dis = disambiguated_data.data.get_opt_name().is_none()
1507                 || dis != 0 && self.tcx.sess.verbose();
1508             if print_dis {
1509                 write!(self, "#{}", dis)?;
1510             }
1511
1512             self.empty_path = false;
1513         }
1514
1515         Ok(self)
1516     }
1517
1518     fn path_generic_args(
1519         mut self,
1520         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1521         args: &[GenericArg<'tcx>],
1522     ) -> Result<Self::Path, Self::Error> {
1523         self = print_prefix(self)?;
1524
1525         // Don't print `'_` if there's no unerased regions.
1526         let print_regions = args.iter().any(|arg| match arg.unpack() {
1527             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1528             _ => false,
1529         });
1530         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1531             GenericArgKind::Lifetime(_) => print_regions,
1532             _ => true,
1533         });
1534
1535         if args.clone().next().is_some() {
1536             if self.in_value {
1537                 write!(self, "::")?;
1538             }
1539             self.generic_delimiters(|cx| cx.comma_sep(args))
1540         } else {
1541             Ok(self)
1542         }
1543     }
1544 }
1545
1546 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1547     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1548         self.0.name_resolver.as_ref().and_then(|func| func(id))
1549     }
1550
1551     fn print_value_path(
1552         mut self,
1553         def_id: DefId,
1554         substs: &'tcx [GenericArg<'tcx>],
1555     ) -> Result<Self::Path, Self::Error> {
1556         let was_in_value = std::mem::replace(&mut self.in_value, true);
1557         self = self.print_def_path(def_id, substs)?;
1558         self.in_value = was_in_value;
1559
1560         Ok(self)
1561     }
1562
1563     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1564     where
1565         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1566     {
1567         self.pretty_in_binder(value)
1568     }
1569
1570     fn typed_value(
1571         mut self,
1572         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1573         t: impl FnOnce(Self) -> Result<Self, Self::Error>,
1574         conversion: &str,
1575     ) -> Result<Self::Const, Self::Error> {
1576         self.write_str("{")?;
1577         self = f(self)?;
1578         self.write_str(conversion)?;
1579         let was_in_value = std::mem::replace(&mut self.in_value, false);
1580         self = t(self)?;
1581         self.in_value = was_in_value;
1582         self.write_str("}")?;
1583         Ok(self)
1584     }
1585
1586     fn generic_delimiters(
1587         mut self,
1588         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1589     ) -> Result<Self, Self::Error> {
1590         write!(self, "<")?;
1591
1592         let was_in_value = std::mem::replace(&mut self.in_value, false);
1593         let mut inner = f(self)?;
1594         inner.in_value = was_in_value;
1595
1596         write!(inner, ">")?;
1597         Ok(inner)
1598     }
1599
1600     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1601         let highlight = self.region_highlight_mode;
1602         if highlight.region_highlighted(region).is_some() {
1603             return true;
1604         }
1605
1606         if self.tcx.sess.verbose() {
1607             return true;
1608         }
1609
1610         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1611
1612         match *region {
1613             ty::ReEarlyBound(ref data) => {
1614                 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1615             }
1616
1617             ty::ReLateBound(_, br)
1618             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1619             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1620                 if let ty::BrNamed(_, name) = br {
1621                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1622                         return true;
1623                     }
1624                 }
1625
1626                 if let Some((region, _)) = highlight.highlight_bound_region {
1627                     if br == region {
1628                         return true;
1629                     }
1630                 }
1631
1632                 false
1633             }
1634
1635             ty::ReVar(_) if identify_regions => true,
1636
1637             ty::ReVar(_) | ty::ReErased => false,
1638
1639             ty::ReStatic | ty::ReEmpty(_) => true,
1640         }
1641     }
1642
1643     fn pretty_print_const_pointer(
1644         self,
1645         p: Pointer,
1646         ty: Ty<'tcx>,
1647         print_ty: bool,
1648     ) -> Result<Self::Const, Self::Error> {
1649         let print = |mut this: Self| {
1650             define_scoped_cx!(this);
1651             if this.print_alloc_ids {
1652                 p!(write("{:?}", p));
1653             } else {
1654                 p!(write("&_"));
1655             }
1656             Ok(this)
1657         };
1658         if print_ty {
1659             self.typed_value(print, |this| this.print_type(ty), ": ")
1660         } else {
1661             print(self)
1662         }
1663     }
1664 }
1665
1666 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1667 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1668     pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1669         define_scoped_cx!(self);
1670
1671         // Watch out for region highlights.
1672         let highlight = self.region_highlight_mode;
1673         if let Some(n) = highlight.region_highlighted(region) {
1674             p!(write("'{}", n));
1675             return Ok(self);
1676         }
1677
1678         if self.tcx.sess.verbose() {
1679             p!(write("{:?}", region));
1680             return Ok(self);
1681         }
1682
1683         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1684
1685         // These printouts are concise.  They do not contain all the information
1686         // the user might want to diagnose an error, but there is basically no way
1687         // to fit that into a short string.  Hence the recommendation to use
1688         // `explain_region()` or `note_and_explain_region()`.
1689         match *region {
1690             ty::ReEarlyBound(ref data) => {
1691                 if data.name != kw::Invalid {
1692                     p!(write("{}", data.name));
1693                     return Ok(self);
1694                 }
1695             }
1696             ty::ReLateBound(_, br)
1697             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1698             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1699                 if let ty::BrNamed(_, name) = br {
1700                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1701                         p!(write("{}", name));
1702                         return Ok(self);
1703                     }
1704                 }
1705
1706                 if let Some((region, counter)) = highlight.highlight_bound_region {
1707                     if br == region {
1708                         p!(write("'{}", counter));
1709                         return Ok(self);
1710                     }
1711                 }
1712             }
1713             ty::ReVar(region_vid) if identify_regions => {
1714                 p!(write("{:?}", region_vid));
1715                 return Ok(self);
1716             }
1717             ty::ReVar(_) => {}
1718             ty::ReErased => {}
1719             ty::ReStatic => {
1720                 p!(write("'static"));
1721                 return Ok(self);
1722             }
1723             ty::ReEmpty(ty::UniverseIndex::ROOT) => {
1724                 p!(write("'<empty>"));
1725                 return Ok(self);
1726             }
1727             ty::ReEmpty(ui) => {
1728                 p!(write("'<empty:{:?}>", ui));
1729                 return Ok(self);
1730             }
1731         }
1732
1733         p!(write("'_"));
1734
1735         Ok(self)
1736     }
1737 }
1738
1739 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1740 // `region_index` and `used_region_names`.
1741 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1742     pub fn name_all_regions<T>(
1743         mut self,
1744         value: &ty::Binder<T>,
1745     ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1746     where
1747         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1748     {
1749         fn name_by_region_index(index: usize) -> Symbol {
1750             match index {
1751                 0 => Symbol::intern("'r"),
1752                 1 => Symbol::intern("'s"),
1753                 i => Symbol::intern(&format!("'t{}", i - 2)),
1754             }
1755         }
1756
1757         // Replace any anonymous late-bound regions with named
1758         // variants, using new unique identifiers, so that we can
1759         // clearly differentiate between named and unnamed regions in
1760         // the output. We'll probably want to tweak this over time to
1761         // decide just how much information to give.
1762         if self.binder_depth == 0 {
1763             self.prepare_late_bound_region_info(value);
1764         }
1765
1766         let mut empty = true;
1767         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1768             write!(
1769                 cx,
1770                 "{}",
1771                 if empty {
1772                     empty = false;
1773                     start
1774                 } else {
1775                     cont
1776                 }
1777             )
1778         };
1779
1780         define_scoped_cx!(self);
1781
1782         let mut region_index = self.region_index;
1783         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1784             let _ = start_or_continue(&mut self, "for<", ", ");
1785             let br = match br {
1786                 ty::BrNamed(_, name) => {
1787                     let _ = write!(self, "{}", name);
1788                     br
1789                 }
1790                 ty::BrAnon(_) | ty::BrEnv => {
1791                     let name = loop {
1792                         let name = name_by_region_index(region_index);
1793                         region_index += 1;
1794                         if !self.used_region_names.contains(&name) {
1795                             break name;
1796                         }
1797                     };
1798                     let _ = write!(self, "{}", name);
1799                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1800                 }
1801             };
1802             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1803         });
1804         start_or_continue(&mut self, "", "> ")?;
1805
1806         self.binder_depth += 1;
1807         self.region_index = region_index;
1808         Ok((self, new_value))
1809     }
1810
1811     pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1812     where
1813         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1814     {
1815         let old_region_index = self.region_index;
1816         let (new, new_value) = self.name_all_regions(value)?;
1817         let mut inner = new_value.0.print(new)?;
1818         inner.region_index = old_region_index;
1819         inner.binder_depth -= 1;
1820         Ok(inner)
1821     }
1822
1823     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1824     where
1825         T: TypeFoldable<'tcx>,
1826     {
1827         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1828         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1829             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1830                 if let ty::ReLateBound(_, ty::BrNamed(_, name)) = *r {
1831                     self.0.insert(name);
1832                 }
1833                 r.super_visit_with(self)
1834             }
1835         }
1836
1837         self.used_region_names.clear();
1838         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1839         value.visit_with(&mut collector);
1840         self.region_index = 0;
1841     }
1842 }
1843
1844 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1845 where
1846     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1847 {
1848     type Output = P;
1849     type Error = P::Error;
1850     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1851         cx.in_binder(self)
1852     }
1853 }
1854
1855 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1856 where
1857     T: Print<'tcx, P, Output = P, Error = P::Error>,
1858     U: Print<'tcx, P, Output = P, Error = P::Error>,
1859 {
1860     type Output = P;
1861     type Error = P::Error;
1862     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1863         define_scoped_cx!(cx);
1864         p!(print(self.0), write(": "), print(self.1));
1865         Ok(cx)
1866     }
1867 }
1868
1869 macro_rules! forward_display_to_print {
1870     ($($ty:ty),+) => {
1871         $(impl fmt::Display for $ty {
1872             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1873                 ty::tls::with(|tcx| {
1874                     tcx.lift(self)
1875                         .expect("could not lift for printing")
1876                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1877                     Ok(())
1878                 })
1879             }
1880         })+
1881     };
1882 }
1883
1884 macro_rules! define_print_and_forward_display {
1885     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1886         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1887             type Output = P;
1888             type Error = fmt::Error;
1889             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1890                 #[allow(unused_mut)]
1891                 let mut $cx = $cx;
1892                 define_scoped_cx!($cx);
1893                 let _: () = $print;
1894                 #[allow(unreachable_code)]
1895                 Ok($cx)
1896             }
1897         })+
1898
1899         forward_display_to_print!($($ty),+);
1900     };
1901 }
1902
1903 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1904 impl fmt::Display for ty::RegionKind {
1905     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1906         ty::tls::with(|tcx| {
1907             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1908             Ok(())
1909         })
1910     }
1911 }
1912
1913 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1914 /// the trait path. That is, it will print `Trait<U>` instead of
1915 /// `<T as Trait<U>>`.
1916 #[derive(Copy, Clone, TypeFoldable, Lift)]
1917 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1918
1919 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1920     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1921         fmt::Display::fmt(self, f)
1922     }
1923 }
1924
1925 impl ty::TraitRef<'tcx> {
1926     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1927         TraitRefPrintOnlyTraitPath(self)
1928     }
1929 }
1930
1931 impl ty::Binder<ty::TraitRef<'tcx>> {
1932     pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1933         self.map_bound(|tr| tr.print_only_trait_path())
1934     }
1935 }
1936
1937 forward_display_to_print! {
1938     Ty<'tcx>,
1939     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1940     &'tcx ty::Const<'tcx>,
1941
1942     // HACK(eddyb) these are exhaustive instead of generic,
1943     // because `for<'tcx>` isn't possible yet.
1944     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1945     ty::Binder<ty::TraitRef<'tcx>>,
1946     ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1947     ty::Binder<ty::FnSig<'tcx>>,
1948     ty::Binder<ty::TraitPredicate<'tcx>>,
1949     ty::Binder<ty::SubtypePredicate<'tcx>>,
1950     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1951     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1952     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1953
1954     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1955     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1956 }
1957
1958 define_print_and_forward_display! {
1959     (self, cx):
1960
1961     &'tcx ty::List<Ty<'tcx>> {
1962         p!(write("{{"), comma_sep(self.iter()), write("}}"))
1963     }
1964
1965     ty::TypeAndMut<'tcx> {
1966         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1967     }
1968
1969     ty::ExistentialTraitRef<'tcx> {
1970         // Use a type that can't appear in defaults of type parameters.
1971         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1972         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1973         p!(print(trait_ref.print_only_trait_path()))
1974     }
1975
1976     ty::ExistentialProjection<'tcx> {
1977         let name = cx.tcx().associated_item(self.item_def_id).ident;
1978         p!(write("{} = ", name), print(self.ty))
1979     }
1980
1981     ty::ExistentialPredicate<'tcx> {
1982         match *self {
1983             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1984             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1985             ty::ExistentialPredicate::AutoTrait(def_id) => {
1986                 p!(print_def_path(def_id, &[]));
1987             }
1988         }
1989     }
1990
1991     ty::FnSig<'tcx> {
1992         p!(write("{}", self.unsafety.prefix_str()));
1993
1994         if self.abi != Abi::Rust {
1995             p!(write("extern {} ", self.abi));
1996         }
1997
1998         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1999     }
2000
2001     ty::InferTy {
2002         if cx.tcx().sess.verbose() {
2003             p!(write("{:?}", self));
2004             return Ok(cx);
2005         }
2006         match *self {
2007             ty::TyVar(_) => p!(write("_")),
2008             ty::IntVar(_) => p!(write("{}", "{integer}")),
2009             ty::FloatVar(_) => p!(write("{}", "{float}")),
2010             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
2011             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
2012             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
2013         }
2014     }
2015
2016     ty::TraitRef<'tcx> {
2017         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2018     }
2019
2020     TraitRefPrintOnlyTraitPath<'tcx> {
2021         p!(print_def_path(self.0.def_id, self.0.substs));
2022     }
2023
2024     ty::ParamTy {
2025         p!(write("{}", self.name))
2026     }
2027
2028     ty::ParamConst {
2029         p!(write("{}", self.name))
2030     }
2031
2032     ty::SubtypePredicate<'tcx> {
2033         p!(print(self.a), write(" <: "), print(self.b))
2034     }
2035
2036     ty::TraitPredicate<'tcx> {
2037         p!(print(self.trait_ref.self_ty()), write(": "),
2038            print(self.trait_ref.print_only_trait_path()))
2039     }
2040
2041     ty::ProjectionPredicate<'tcx> {
2042         p!(print(self.projection_ty), write(" == "), print(self.ty))
2043     }
2044
2045     ty::ProjectionTy<'tcx> {
2046         p!(print_def_path(self.item_def_id, self.substs));
2047     }
2048
2049     ty::ClosureKind {
2050         match *self {
2051             ty::ClosureKind::Fn => p!(write("Fn")),
2052             ty::ClosureKind::FnMut => p!(write("FnMut")),
2053             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
2054         }
2055     }
2056
2057     ty::Predicate<'tcx> {
2058         match self.kind() {
2059             &ty::PredicateKind::Atom(atom) => p!(print(atom)),
2060             ty::PredicateKind::ForAll(binder) => p!(print(binder)),
2061         }
2062     }
2063
2064     ty::PredicateAtom<'tcx> {
2065         match *self {
2066             ty::PredicateAtom::Trait(ref data, constness) => {
2067                 if let hir::Constness::Const = constness {
2068                     p!(write("const "));
2069                 }
2070                 p!(print(data))
2071             }
2072             ty::PredicateAtom::Subtype(predicate) => p!(print(predicate)),
2073             ty::PredicateAtom::RegionOutlives(predicate) => p!(print(predicate)),
2074             ty::PredicateAtom::TypeOutlives(predicate) => p!(print(predicate)),
2075             ty::PredicateAtom::Projection(predicate) => p!(print(predicate)),
2076             ty::PredicateAtom::WellFormed(arg) => p!(print(arg), write(" well-formed")),
2077             ty::PredicateAtom::ObjectSafe(trait_def_id) => {
2078                 p!(write("the trait `"),
2079                 print_def_path(trait_def_id, &[]),
2080                 write("` is object-safe"))
2081             }
2082             ty::PredicateAtom::ClosureKind(closure_def_id, _closure_substs, kind) => {
2083                 p!(write("the closure `"),
2084                 print_value_path(closure_def_id, &[]),
2085                 write("` implements the trait `{}`", kind))
2086             }
2087             ty::PredicateAtom::ConstEvaluatable(def, substs) => {
2088                 p!(write("the constant `"),
2089                 print_value_path(def.did, substs),
2090                 write("` can be evaluated"))
2091             }
2092             ty::PredicateAtom::ConstEquate(c1, c2) => {
2093                 p!(write("the constant `"),
2094                 print(c1),
2095                 write("` equals `"),
2096                 print(c2),
2097                 write("`"))
2098             }
2099             ty::PredicateAtom::TypeWellFormedFromEnv(ty) => {
2100                 p!(write("the type `"),
2101                 print(ty),
2102                 write("` is found in the environment"))
2103             }
2104         }
2105     }
2106
2107     GenericArg<'tcx> {
2108         match self.unpack() {
2109             GenericArgKind::Lifetime(lt) => p!(print(lt)),
2110             GenericArgKind::Type(ty) => p!(print(ty)),
2111             GenericArgKind::Const(ct) => p!(print(ct)),
2112         }
2113     }
2114 }
2115
2116 fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2117     // Iterate all local crate items no matter where they are defined.
2118     let hir = tcx.hir();
2119     for item in hir.krate().items.values() {
2120         if item.ident.name.as_str().is_empty() {
2121             continue;
2122         }
2123
2124         match item.kind {
2125             ItemKind::Use(_, _) => {
2126                 continue;
2127             }
2128             _ => {}
2129         }
2130
2131         if let Some(local_def_id) = hir.definitions().opt_hir_id_to_local_def_id(item.hir_id) {
2132             let def_id = local_def_id.to_def_id();
2133             let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2134             collect_fn(&item.ident, ns, def_id);
2135         }
2136     }
2137
2138     // Now take care of extern crate items.
2139     let queue = &mut Vec::new();
2140     let mut seen_defs: DefIdSet = Default::default();
2141
2142     for &cnum in tcx.crates().iter() {
2143         let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
2144
2145         // Ignore crates that are not direct dependencies.
2146         match tcx.extern_crate(def_id) {
2147             None => continue,
2148             Some(extern_crate) => {
2149                 if !extern_crate.is_direct() {
2150                     continue;
2151                 }
2152             }
2153         }
2154
2155         queue.push(def_id);
2156     }
2157
2158     // Iterate external crate defs but be mindful about visibility
2159     while let Some(def) = queue.pop() {
2160         for child in tcx.item_children(def).iter() {
2161             if child.vis != ty::Visibility::Public {
2162                 continue;
2163             }
2164
2165             match child.res {
2166                 def::Res::Def(DefKind::AssocTy, _) => {}
2167                 def::Res::Def(defkind, def_id) => {
2168                     if let Some(ns) = defkind.ns() {
2169                         collect_fn(&child.ident, ns, def_id);
2170                     }
2171
2172                     if seen_defs.insert(def_id) {
2173                         queue.push(def_id);
2174                     }
2175                 }
2176                 _ => {}
2177             }
2178         }
2179     }
2180 }
2181
2182 /// The purpose of this function is to collect public symbols names that are unique across all
2183 /// crates in the build. Later, when printing about types we can use those names instead of the
2184 /// full exported path to them.
2185 ///
2186 /// So essentially, if a symbol name can only be imported from one place for a type, and as
2187 /// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2188 /// path and print only the name.
2189 ///
2190 /// This has wide implications on error messages with types, for example, shortening
2191 /// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2192 ///
2193 /// The implementation uses similar import discovery logic to that of 'use' suggestions.
2194 fn trimmed_def_paths(tcx: TyCtxt<'_>, crate_num: CrateNum) -> FxHashMap<DefId, Symbol> {
2195     assert_eq!(crate_num, LOCAL_CRATE);
2196
2197     let mut map = FxHashMap::default();
2198
2199     if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
2200         // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2201         // wrapper can be used to suppress this query, in exchange for full paths being formatted.
2202         tcx.sess.delay_good_path_bug("trimmed_def_paths constructed");
2203     }
2204
2205     let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2206         &mut FxHashMap::default();
2207
2208     for symbol_set in tcx.glob_map.values() {
2209         for symbol in symbol_set {
2210             unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2211             unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2212             unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2213         }
2214     }
2215
2216     for_each_def(tcx, |ident, ns, def_id| {
2217         use std::collections::hash_map::Entry::{Occupied, Vacant};
2218
2219         match unique_symbols_rev.entry((ns, ident.name)) {
2220             Occupied(mut v) => match v.get() {
2221                 None => {}
2222                 Some(existing) => {
2223                     if *existing != def_id {
2224                         v.insert(None);
2225                     }
2226                 }
2227             },
2228             Vacant(v) => {
2229                 v.insert(Some(def_id));
2230             }
2231         }
2232     });
2233
2234     for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
2235         if let Some(def_id) = opt_def_id {
2236             map.insert(def_id, symbol);
2237         }
2238     }
2239
2240     map
2241 }
2242
2243 pub fn provide(providers: &mut ty::query::Providers) {
2244     *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2245 }