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