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