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