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