]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
9091de55b7d8ea5f4762e9f3f25e3a239c7170c3
[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, promoted), _) => {
845                 if let Some(promoted) = promoted {
846                     p!(print_value_path(did, substs));
847                     p!(write("::{:?}", promoted));
848                 } else {
849                     match self.tcx().def_kind(did) {
850                         Some(DefKind::Static)
851                         | Some(DefKind::Const)
852                         | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
853                         _ => {
854                             if did.is_local() {
855                                 let span = self.tcx().def_span(did);
856                                 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
857                                 {
858                                     p!(write("{}", snip))
859                                 } else {
860                                     p!(write("_: "), print(ct.ty))
861                                 }
862                             } else {
863                                 p!(write("_: "), print(ct.ty))
864                             }
865                         }
866                     }
867                 }
868             }
869             (ty::ConstKind::Infer(..), _) => p!(write("_: "), print(ct.ty)),
870             (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
871             (ty::ConstKind::Value(value), _) => return self.pretty_print_const_value(value, ct.ty),
872
873             _ => {
874                 // fallback
875                 p!(write("{:?} : ", ct.val), print(ct.ty))
876             }
877         };
878         Ok(self)
879     }
880
881     fn pretty_print_const_value(
882         mut self,
883         ct: ConstValue<'tcx>,
884         ty: Ty<'tcx>,
885     ) -> Result<Self::Const, Self::Error> {
886         define_scoped_cx!(self);
887
888         if self.tcx().sess.verbose() {
889             p!(write("ConstValue({:?}: {:?})", ct, ty));
890             return Ok(self);
891         }
892
893         let u8 = self.tcx().types.u8;
894
895         match (ct, &ty.kind) {
896             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) => {
897                 p!(write("{}", if data == 0 { "false" } else { "true" }))
898             }
899             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) => {
900                 p!(write("{}f32", Single::from_bits(data)))
901             }
902             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) => {
903                 p!(write("{}f64", Double::from_bits(data)))
904             }
905             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => {
906                 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
907                 let max = truncate(u128::max_value(), bit_size);
908
909                 let ui_str = ui.name_str();
910                 if data == max {
911                     p!(write("std::{}::MAX", ui_str))
912                 } else {
913                     p!(write("{}{}", data, ui_str))
914                 };
915             }
916             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => {
917                 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size().bits() as u128;
918                 let min = 1u128 << (bit_size - 1);
919                 let max = min - 1;
920
921                 let ty = self.tcx().lift(&ty).unwrap();
922                 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
923                 let i_str = i.name_str();
924                 match data {
925                     d if d == min => p!(write("std::{}::MIN", i_str)),
926                     d if d == max => p!(write("std::{}::MAX", i_str)),
927                     _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str)),
928                 }
929             }
930             (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) => {
931                 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap()))
932             }
933             (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")),
934             (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => {
935                 let instance = {
936                     let alloc_map = self.tcx().alloc_map.lock();
937                     alloc_map.unwrap_fn(ptr.alloc_id)
938                 };
939                 p!(print_value_path(instance.def_id(), instance.substs));
940             }
941             _ => {
942                 let printed = if let ty::Ref(_, ref_ty, _) = ty.kind {
943                     let byte_str = match (ct, &ref_ty.kind) {
944                         (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
945                             let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
946                             Some(
947                                 self.tcx()
948                                     .alloc_map
949                                     .lock()
950                                     .unwrap_memory(ptr.alloc_id)
951                                     .get_bytes(&self.tcx(), ptr, Size::from_bytes(n))
952                                     .unwrap(),
953                             )
954                         }
955                         (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
956                             // The `inspect` here is okay since we checked the bounds, and there are
957                             // no relocations (we have an active slice reference here). We don't use
958                             // this result to affect interpreter execution.
959                             Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
960                         }
961                         _ => None,
962                     };
963
964                     if let Some(byte_str) = byte_str {
965                         p!(write("b\""));
966                         for &c in byte_str {
967                             for e in std::ascii::escape_default(c) {
968                                 self.write_char(e as char)?;
969                             }
970                         }
971                         p!(write("\""));
972                         true
973                     } else if let (ConstValue::Slice { data, start, end }, ty::Str) =
974                         (ct, &ref_ty.kind)
975                     {
976                         // The `inspect` here is okay since we checked the bounds, and there are no
977                         // relocations (we have an active `str` reference here). We don't use this
978                         // result to affect interpreter execution.
979                         let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
980                         let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri");
981                         p!(write("{:?}", s));
982                         true
983                     } else {
984                         false
985                     }
986                 } else {
987                     false
988                 };
989                 if !printed {
990                     // fallback
991                     p!(write("{:?} : ", ct), print(ty))
992                 }
993             }
994         };
995         Ok(self)
996     }
997 }
998
999 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1000 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1001
1002 pub struct FmtPrinterData<'a, 'tcx, F> {
1003     tcx: TyCtxt<'tcx>,
1004     fmt: F,
1005
1006     empty_path: bool,
1007     in_value: bool,
1008
1009     used_region_names: FxHashSet<Symbol>,
1010     region_index: usize,
1011     binder_depth: usize,
1012
1013     pub region_highlight_mode: RegionHighlightMode,
1014
1015     pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1016 }
1017
1018 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1019     type Target = FmtPrinterData<'a, 'tcx, F>;
1020     fn deref(&self) -> &Self::Target {
1021         &self.0
1022     }
1023 }
1024
1025 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1026     fn deref_mut(&mut self) -> &mut Self::Target {
1027         &mut self.0
1028     }
1029 }
1030
1031 impl<F> FmtPrinter<'a, 'tcx, F> {
1032     pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1033         FmtPrinter(Box::new(FmtPrinterData {
1034             tcx,
1035             fmt,
1036             empty_path: false,
1037             in_value: ns == Namespace::ValueNS,
1038             used_region_names: Default::default(),
1039             region_index: 0,
1040             binder_depth: 0,
1041             region_highlight_mode: RegionHighlightMode::default(),
1042             name_resolver: None,
1043         }))
1044     }
1045 }
1046
1047 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1048 // (but also some things just print a `DefId` generally so maybe we need this?)
1049 fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1050     match tcx.def_key(def_id).disambiguated_data.data {
1051         DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1052             Namespace::TypeNS
1053         }
1054
1055         DefPathData::ValueNs(..)
1056         | DefPathData::AnonConst
1057         | DefPathData::ClosureExpr
1058         | DefPathData::Ctor => Namespace::ValueNS,
1059
1060         DefPathData::MacroNs(..) => Namespace::MacroNS,
1061
1062         _ => Namespace::TypeNS,
1063     }
1064 }
1065
1066 impl TyCtxt<'t> {
1067     /// Returns a string identifying this `DefId`. This string is
1068     /// suitable for user output.
1069     pub fn def_path_str(self, def_id: DefId) -> String {
1070         self.def_path_str_with_substs(def_id, &[])
1071     }
1072
1073     pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1074         let ns = guess_def_namespace(self, def_id);
1075         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1076         let mut s = String::new();
1077         let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1078         s
1079     }
1080 }
1081
1082 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1083     fn write_str(&mut self, s: &str) -> fmt::Result {
1084         self.fmt.write_str(s)
1085     }
1086 }
1087
1088 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1089     type Error = fmt::Error;
1090
1091     type Path = Self;
1092     type Region = Self;
1093     type Type = Self;
1094     type DynExistential = Self;
1095     type Const = Self;
1096
1097     fn tcx(&'a self) -> TyCtxt<'tcx> {
1098         self.tcx
1099     }
1100
1101     fn print_def_path(
1102         mut self,
1103         def_id: DefId,
1104         substs: &'tcx [GenericArg<'tcx>],
1105     ) -> Result<Self::Path, Self::Error> {
1106         define_scoped_cx!(self);
1107
1108         if substs.is_empty() {
1109             match self.try_print_visible_def_path(def_id)? {
1110                 (cx, true) => return Ok(cx),
1111                 (cx, false) => self = cx,
1112             }
1113         }
1114
1115         let key = self.tcx.def_key(def_id);
1116         if let DefPathData::Impl = key.disambiguated_data.data {
1117             // Always use types for non-local impls, where types are always
1118             // available, and filename/line-number is mostly uninteresting.
1119             let use_types = !def_id.is_local() || {
1120                 // Otherwise, use filename/line-number if forced.
1121                 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1122                 !force_no_types
1123             };
1124
1125             if !use_types {
1126                 // If no type info is available, fall back to
1127                 // pretty printing some span information. This should
1128                 // only occur very early in the compiler pipeline.
1129                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1130                 let span = self.tcx.def_span(def_id);
1131
1132                 self = self.print_def_path(parent_def_id, &[])?;
1133
1134                 // HACK(eddyb) copy of `path_append` to avoid
1135                 // constructing a `DisambiguatedDefPathData`.
1136                 if !self.empty_path {
1137                     write!(self, "::")?;
1138                 }
1139                 write!(self, "<impl at {:?}>", span)?;
1140                 self.empty_path = false;
1141
1142                 return Ok(self);
1143             }
1144         }
1145
1146         self.default_print_def_path(def_id, substs)
1147     }
1148
1149     fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
1150         self.pretty_print_region(region)
1151     }
1152
1153     fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
1154         self.pretty_print_type(ty)
1155     }
1156
1157     fn print_dyn_existential(
1158         self,
1159         predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1160     ) -> Result<Self::DynExistential, Self::Error> {
1161         self.pretty_print_dyn_existential(predicates)
1162     }
1163
1164     fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
1165         self.pretty_print_const(ct)
1166     }
1167
1168     fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
1169         self.empty_path = true;
1170         if cnum == LOCAL_CRATE {
1171             if self.tcx.sess.rust_2018() {
1172                 // We add the `crate::` keyword on Rust 2018, only when desired.
1173                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1174                     write!(self, "{}", kw::Crate)?;
1175                     self.empty_path = false;
1176                 }
1177             }
1178         } else {
1179             write!(self, "{}", self.tcx.crate_name(cnum))?;
1180             self.empty_path = false;
1181         }
1182         Ok(self)
1183     }
1184
1185     fn path_qualified(
1186         mut self,
1187         self_ty: Ty<'tcx>,
1188         trait_ref: Option<ty::TraitRef<'tcx>>,
1189     ) -> Result<Self::Path, Self::Error> {
1190         self = self.pretty_path_qualified(self_ty, trait_ref)?;
1191         self.empty_path = false;
1192         Ok(self)
1193     }
1194
1195     fn path_append_impl(
1196         mut self,
1197         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1198         _disambiguated_data: &DisambiguatedDefPathData,
1199         self_ty: Ty<'tcx>,
1200         trait_ref: Option<ty::TraitRef<'tcx>>,
1201     ) -> Result<Self::Path, Self::Error> {
1202         self = self.pretty_path_append_impl(
1203             |mut cx| {
1204                 cx = print_prefix(cx)?;
1205                 if !cx.empty_path {
1206                     write!(cx, "::")?;
1207                 }
1208
1209                 Ok(cx)
1210             },
1211             self_ty,
1212             trait_ref,
1213         )?;
1214         self.empty_path = false;
1215         Ok(self)
1216     }
1217
1218     fn path_append(
1219         mut self,
1220         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1221         disambiguated_data: &DisambiguatedDefPathData,
1222     ) -> Result<Self::Path, Self::Error> {
1223         self = print_prefix(self)?;
1224
1225         // Skip `::{{constructor}}` on tuple/unit structs.
1226         match disambiguated_data.data {
1227             DefPathData::Ctor => return Ok(self),
1228             _ => {}
1229         }
1230
1231         // FIXME(eddyb) `name` should never be empty, but it
1232         // currently is for `extern { ... }` "foreign modules".
1233         let name = disambiguated_data.data.as_symbol().as_str();
1234         if !name.is_empty() {
1235             if !self.empty_path {
1236                 write!(self, "::")?;
1237             }
1238             if ast::Ident::from_str(&name).is_raw_guess() {
1239                 write!(self, "r#")?;
1240             }
1241             write!(self, "{}", name)?;
1242
1243             // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1244             // might be nicer to use something else, e.g. `{closure#3}`.
1245             let dis = disambiguated_data.disambiguator;
1246             let print_dis = disambiguated_data.data.get_opt_name().is_none()
1247                 || dis != 0 && self.tcx.sess.verbose();
1248             if print_dis {
1249                 write!(self, "#{}", dis)?;
1250             }
1251
1252             self.empty_path = false;
1253         }
1254
1255         Ok(self)
1256     }
1257
1258     fn path_generic_args(
1259         mut self,
1260         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1261         args: &[GenericArg<'tcx>],
1262     ) -> Result<Self::Path, Self::Error> {
1263         self = print_prefix(self)?;
1264
1265         // Don't print `'_` if there's no unerased regions.
1266         let print_regions = args.iter().any(|arg| match arg.unpack() {
1267             GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1268             _ => false,
1269         });
1270         let args = args.iter().cloned().filter(|arg| match arg.unpack() {
1271             GenericArgKind::Lifetime(_) => print_regions,
1272             _ => true,
1273         });
1274
1275         if args.clone().next().is_some() {
1276             if self.in_value {
1277                 write!(self, "::")?;
1278             }
1279             self.generic_delimiters(|cx| cx.comma_sep(args))
1280         } else {
1281             Ok(self)
1282         }
1283     }
1284 }
1285
1286 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1287     fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1288         self.0.name_resolver.as_ref().and_then(|func| func(id))
1289     }
1290
1291     fn print_value_path(
1292         mut self,
1293         def_id: DefId,
1294         substs: &'tcx [GenericArg<'tcx>],
1295     ) -> Result<Self::Path, Self::Error> {
1296         let was_in_value = std::mem::replace(&mut self.in_value, true);
1297         self = self.print_def_path(def_id, substs)?;
1298         self.in_value = was_in_value;
1299
1300         Ok(self)
1301     }
1302
1303     fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1304     where
1305         T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1306     {
1307         self.pretty_in_binder(value)
1308     }
1309
1310     fn generic_delimiters(
1311         mut self,
1312         f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1313     ) -> Result<Self, Self::Error> {
1314         write!(self, "<")?;
1315
1316         let was_in_value = std::mem::replace(&mut self.in_value, false);
1317         let mut inner = f(self)?;
1318         inner.in_value = was_in_value;
1319
1320         write!(inner, ">")?;
1321         Ok(inner)
1322     }
1323
1324     fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool {
1325         let highlight = self.region_highlight_mode;
1326         if highlight.region_highlighted(region).is_some() {
1327             return true;
1328         }
1329
1330         if self.tcx.sess.verbose() {
1331             return true;
1332         }
1333
1334         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1335
1336         match *region {
1337             ty::ReEarlyBound(ref data) => {
1338                 data.name != kw::Invalid && data.name != kw::UnderscoreLifetime
1339             }
1340
1341             ty::ReLateBound(_, br)
1342             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1343             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1344                 if let ty::BrNamed(_, name) = br {
1345                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1346                         return true;
1347                     }
1348                 }
1349
1350                 if let Some((region, _)) = highlight.highlight_bound_region {
1351                     if br == region {
1352                         return true;
1353                     }
1354                 }
1355
1356                 false
1357             }
1358
1359             ty::ReScope(_) | ty::ReVar(_) if identify_regions => true,
1360
1361             ty::ReVar(_) | ty::ReScope(_) | ty::ReErased => false,
1362
1363             ty::ReStatic | ty::ReEmpty | ty::ReClosureBound(_) => true,
1364         }
1365     }
1366 }
1367
1368 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1369 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1370     pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> {
1371         define_scoped_cx!(self);
1372
1373         // Watch out for region highlights.
1374         let highlight = self.region_highlight_mode;
1375         if let Some(n) = highlight.region_highlighted(region) {
1376             p!(write("'{}", n));
1377             return Ok(self);
1378         }
1379
1380         if self.tcx.sess.verbose() {
1381             p!(write("{:?}", region));
1382             return Ok(self);
1383         }
1384
1385         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1386
1387         // These printouts are concise.  They do not contain all the information
1388         // the user might want to diagnose an error, but there is basically no way
1389         // to fit that into a short string.  Hence the recommendation to use
1390         // `explain_region()` or `note_and_explain_region()`.
1391         match *region {
1392             ty::ReEarlyBound(ref data) => {
1393                 if data.name != kw::Invalid {
1394                     p!(write("{}", data.name));
1395                     return Ok(self);
1396                 }
1397             }
1398             ty::ReLateBound(_, br)
1399             | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
1400             | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1401                 if let ty::BrNamed(_, name) = br {
1402                     if name != kw::Invalid && name != kw::UnderscoreLifetime {
1403                         p!(write("{}", name));
1404                         return Ok(self);
1405                     }
1406                 }
1407
1408                 if let Some((region, counter)) = highlight.highlight_bound_region {
1409                     if br == region {
1410                         p!(write("'{}", counter));
1411                         return Ok(self);
1412                     }
1413                 }
1414             }
1415             ty::ReScope(scope) if identify_regions => {
1416                 match scope.data {
1417                     region::ScopeData::Node => p!(write("'{}s", scope.item_local_id().as_usize())),
1418                     region::ScopeData::CallSite => {
1419                         p!(write("'{}cs", scope.item_local_id().as_usize()))
1420                     }
1421                     region::ScopeData::Arguments => {
1422                         p!(write("'{}as", scope.item_local_id().as_usize()))
1423                     }
1424                     region::ScopeData::Destruction => {
1425                         p!(write("'{}ds", scope.item_local_id().as_usize()))
1426                     }
1427                     region::ScopeData::Remainder(first_statement_index) => p!(write(
1428                         "'{}_{}rs",
1429                         scope.item_local_id().as_usize(),
1430                         first_statement_index.index()
1431                     )),
1432                 }
1433                 return Ok(self);
1434             }
1435             ty::ReVar(region_vid) if identify_regions => {
1436                 p!(write("{:?}", region_vid));
1437                 return Ok(self);
1438             }
1439             ty::ReVar(_) => {}
1440             ty::ReScope(_) | ty::ReErased => {}
1441             ty::ReStatic => {
1442                 p!(write("'static"));
1443                 return Ok(self);
1444             }
1445             ty::ReEmpty => {
1446                 p!(write("'<empty>"));
1447                 return Ok(self);
1448             }
1449
1450             // The user should never encounter these in unsubstituted form.
1451             ty::ReClosureBound(vid) => {
1452                 p!(write("{:?}", vid));
1453                 return Ok(self);
1454             }
1455         }
1456
1457         p!(write("'_"));
1458
1459         Ok(self)
1460     }
1461 }
1462
1463 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1464 // `region_index` and `used_region_names`.
1465 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1466     pub fn name_all_regions<T>(
1467         mut self,
1468         value: &ty::Binder<T>,
1469     ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1470     where
1471         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1472     {
1473         fn name_by_region_index(index: usize) -> Symbol {
1474             match index {
1475                 0 => Symbol::intern("'r"),
1476                 1 => Symbol::intern("'s"),
1477                 i => Symbol::intern(&format!("'t{}", i - 2)),
1478             }
1479         }
1480
1481         // Replace any anonymous late-bound regions with named
1482         // variants, using new unique identifiers, so that we can
1483         // clearly differentiate between named and unnamed regions in
1484         // the output. We'll probably want to tweak this over time to
1485         // decide just how much information to give.
1486         if self.binder_depth == 0 {
1487             self.prepare_late_bound_region_info(value);
1488         }
1489
1490         let mut empty = true;
1491         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1492             write!(
1493                 cx,
1494                 "{}",
1495                 if empty {
1496                     empty = false;
1497                     start
1498                 } else {
1499                     cont
1500                 }
1501             )
1502         };
1503
1504         define_scoped_cx!(self);
1505
1506         let mut region_index = self.region_index;
1507         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1508             let _ = start_or_continue(&mut self, "for<", ", ");
1509             let br = match br {
1510                 ty::BrNamed(_, name) => {
1511                     let _ = write!(self, "{}", name);
1512                     br
1513                 }
1514                 ty::BrAnon(_) | ty::BrEnv => {
1515                     let name = loop {
1516                         let name = name_by_region_index(region_index);
1517                         region_index += 1;
1518                         if !self.used_region_names.contains(&name) {
1519                             break name;
1520                         }
1521                     };
1522                     let _ = write!(self, "{}", name);
1523                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1524                 }
1525             };
1526             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1527         });
1528         start_or_continue(&mut self, "", "> ")?;
1529
1530         self.binder_depth += 1;
1531         self.region_index = region_index;
1532         Ok((self, new_value))
1533     }
1534
1535     pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1536     where
1537         T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1538     {
1539         let old_region_index = self.region_index;
1540         let (new, new_value) = self.name_all_regions(value)?;
1541         let mut inner = new_value.0.print(new)?;
1542         inner.region_index = old_region_index;
1543         inner.binder_depth -= 1;
1544         Ok(inner)
1545     }
1546
1547     fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1548     where
1549         T: TypeFoldable<'tcx>,
1550     {
1551         struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1552         impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1553             fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1554                 match *r {
1555                     ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1556                         self.0.insert(name);
1557                     }
1558                     _ => {}
1559                 }
1560                 r.super_visit_with(self)
1561             }
1562         }
1563
1564         self.used_region_names.clear();
1565         let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1566         value.visit_with(&mut collector);
1567         self.region_index = 0;
1568     }
1569 }
1570
1571 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1572 where
1573     T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1574 {
1575     type Output = P;
1576     type Error = P::Error;
1577     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1578         cx.in_binder(self)
1579     }
1580 }
1581
1582 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1583 where
1584     T: Print<'tcx, P, Output = P, Error = P::Error>,
1585     U: Print<'tcx, P, Output = P, Error = P::Error>,
1586 {
1587     type Output = P;
1588     type Error = P::Error;
1589     fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1590         define_scoped_cx!(cx);
1591         p!(print(self.0), write(" : "), print(self.1));
1592         Ok(cx)
1593     }
1594 }
1595
1596 macro_rules! forward_display_to_print {
1597     ($($ty:ty),+) => {
1598         $(impl fmt::Display for $ty {
1599             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1600                 ty::tls::with(|tcx| {
1601                     tcx.lift(self)
1602                         .expect("could not lift for printing")
1603                         .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1604                     Ok(())
1605                 })
1606             }
1607         })+
1608     };
1609 }
1610
1611 macro_rules! define_print_and_forward_display {
1612     (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1613         $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1614             type Output = P;
1615             type Error = fmt::Error;
1616             fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1617                 #[allow(unused_mut)]
1618                 let mut $cx = $cx;
1619                 define_scoped_cx!($cx);
1620                 let _: () = $print;
1621                 #[allow(unreachable_code)]
1622                 Ok($cx)
1623             }
1624         })+
1625
1626         forward_display_to_print!($($ty),+);
1627     };
1628 }
1629
1630 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1631 impl fmt::Display for ty::RegionKind {
1632     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1633         ty::tls::with(|tcx| {
1634             self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1635             Ok(())
1636         })
1637     }
1638 }
1639
1640 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1641 /// the trait path. That is, it will print `Trait<U>` instead of
1642 /// `<T as Trait<U>>`.
1643 #[derive(Copy, Clone, TypeFoldable, Lift)]
1644 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1645
1646 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1647     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648         fmt::Display::fmt(self, f)
1649     }
1650 }
1651
1652 impl ty::TraitRef<'tcx> {
1653     pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1654         TraitRefPrintOnlyTraitPath(self)
1655     }
1656 }
1657
1658 impl ty::Binder<ty::TraitRef<'tcx>> {
1659     pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1660         self.map_bound(|tr| tr.print_only_trait_path())
1661     }
1662 }
1663
1664 forward_display_to_print! {
1665     Ty<'tcx>,
1666     &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1667     &'tcx ty::Const<'tcx>,
1668
1669     // HACK(eddyb) these are exhaustive instead of generic,
1670     // because `for<'tcx>` isn't possible yet.
1671     ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1672     ty::Binder<ty::TraitRef<'tcx>>,
1673     ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1674     ty::Binder<ty::FnSig<'tcx>>,
1675     ty::Binder<ty::TraitPredicate<'tcx>>,
1676     ty::Binder<ty::SubtypePredicate<'tcx>>,
1677     ty::Binder<ty::ProjectionPredicate<'tcx>>,
1678     ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1679     ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1680
1681     ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1682     ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1683 }
1684
1685 define_print_and_forward_display! {
1686     (self, cx):
1687
1688     &'tcx ty::List<Ty<'tcx>> {
1689         p!(write("{{"));
1690         let mut tys = self.iter();
1691         if let Some(&ty) = tys.next() {
1692             p!(print(ty));
1693             for &ty in tys {
1694                 p!(write(", "), print(ty));
1695             }
1696         }
1697         p!(write("}}"))
1698     }
1699
1700     ty::TypeAndMut<'tcx> {
1701         p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1702     }
1703
1704     ty::ExistentialTraitRef<'tcx> {
1705         // Use a type that can't appear in defaults of type parameters.
1706         let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1707         let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1708         p!(print(trait_ref.print_only_trait_path()))
1709     }
1710
1711     ty::ExistentialProjection<'tcx> {
1712         let name = cx.tcx().associated_item(self.item_def_id).ident;
1713         p!(write("{} = ", name), print(self.ty))
1714     }
1715
1716     ty::ExistentialPredicate<'tcx> {
1717         match *self {
1718             ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1719             ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1720             ty::ExistentialPredicate::AutoTrait(def_id) => {
1721                 p!(print_def_path(def_id, &[]));
1722             }
1723         }
1724     }
1725
1726     ty::FnSig<'tcx> {
1727         p!(write("{}", self.unsafety.prefix_str()));
1728
1729         if self.abi != Abi::Rust {
1730             p!(write("extern {} ", self.abi));
1731         }
1732
1733         p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1734     }
1735
1736     ty::InferTy {
1737         if cx.tcx().sess.verbose() {
1738             p!(write("{:?}", self));
1739             return Ok(cx);
1740         }
1741         match *self {
1742             ty::TyVar(_) => p!(write("_")),
1743             ty::IntVar(_) => p!(write("{}", "{integer}")),
1744             ty::FloatVar(_) => p!(write("{}", "{float}")),
1745             ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1746             ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1747             ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1748         }
1749     }
1750
1751     ty::TraitRef<'tcx> {
1752         p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1753     }
1754
1755     TraitRefPrintOnlyTraitPath<'tcx> {
1756         p!(print_def_path(self.0.def_id, self.0.substs));
1757     }
1758
1759     ty::ParamTy {
1760         p!(write("{}", self.name))
1761     }
1762
1763     ty::ParamConst {
1764         p!(write("{}", self.name))
1765     }
1766
1767     ty::SubtypePredicate<'tcx> {
1768         p!(print(self.a), write(" <: "), print(self.b))
1769     }
1770
1771     ty::TraitPredicate<'tcx> {
1772         p!(print(self.trait_ref.self_ty()), write(": "),
1773            print(self.trait_ref.print_only_trait_path()))
1774     }
1775
1776     ty::ProjectionPredicate<'tcx> {
1777         p!(print(self.projection_ty), write(" == "), print(self.ty))
1778     }
1779
1780     ty::ProjectionTy<'tcx> {
1781         p!(print_def_path(self.item_def_id, self.substs));
1782     }
1783
1784     ty::ClosureKind {
1785         match *self {
1786             ty::ClosureKind::Fn => p!(write("Fn")),
1787             ty::ClosureKind::FnMut => p!(write("FnMut")),
1788             ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1789         }
1790     }
1791
1792     ty::Predicate<'tcx> {
1793         match *self {
1794             ty::Predicate::Trait(ref data, constness) => {
1795                 if let ast::Constness::Const = constness {
1796                     p!(write("const "));
1797                 }
1798                 p!(print(data))
1799             }
1800             ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1801             ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1802             ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1803             ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1804             ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1805             ty::Predicate::ObjectSafe(trait_def_id) => {
1806                 p!(write("the trait `"),
1807                    print_def_path(trait_def_id, &[]),
1808                    write("` is object-safe"))
1809             }
1810             ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1811                 p!(write("the closure `"),
1812                    print_value_path(closure_def_id, &[]),
1813                    write("` implements the trait `{}`", kind))
1814             }
1815             ty::Predicate::ConstEvaluatable(def_id, substs) => {
1816                 p!(write("the constant `"),
1817                    print_value_path(def_id, substs),
1818                    write("` can be evaluated"))
1819             }
1820         }
1821     }
1822
1823     GenericArg<'tcx> {
1824         match self.unpack() {
1825             GenericArgKind::Lifetime(lt) => p!(print(lt)),
1826             GenericArgKind::Type(ty) => p!(print(ty)),
1827             GenericArgKind::Const(ct) => p!(print(ct)),
1828         }
1829     }
1830 }