]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
6a7c48ee879400d0462f6c744b61717740136f4e
[rust.git] / src / librustc / ty / print / pretty.rs
1 use crate::hir;
2 use crate::hir::def::Namespace;
3 use crate::hir::map::DefPathData;
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::{Kind, Subst, SubstsRef, UnpackedKind};
9 use crate::mir::interpret::ConstValue;
10 use syntax::symbol::{keywords, Symbol};
11
12 use syntax::symbol::InternedString;
13
14 use std::cell::Cell;
15 use std::fmt::{self, Write as _};
16 use std::iter;
17
18 // `pretty` is a separate module only for organization.
19 use super::*;
20
21 macro_rules! nest {
22     ($closure:expr) => {
23         scoped_cx!() = scoped_cx!().nest($closure)?
24     }
25 }
26 macro_rules! print_inner {
27     (write ($($data:expr),+)) => {
28         write!(scoped_cx!().printer, $($data),+)?
29     };
30     ($kind:ident ($data:expr)) => {
31         nest!(|cx| $data.$kind(cx))
32     };
33 }
34 macro_rules! p {
35     ($($kind:ident $data:tt),+) => {
36         {
37             $(print_inner!($kind $data));+
38         }
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 }
54
55 /// Force us to name impls with just the filename/line number. We
56 /// normally try to use types. But at some points, notably while printing
57 /// cycle errors, this can result in extra or suboptimal error output,
58 /// so this variable disables that check.
59 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
60     FORCE_IMPL_FILENAME_LINE.with(|force| {
61         let old = force.get();
62         force.set(true);
63         let result = f();
64         force.set(old);
65         result
66     })
67 }
68
69 /// Adds the `crate::` prefix to paths where appropriate.
70 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
71     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
72         let old = flag.get();
73         flag.set(true);
74         let result = f();
75         flag.set(old);
76         result
77     })
78 }
79
80 /// The "region highlights" are used to control region printing during
81 /// specific error messages. When a "region highlight" is enabled, it
82 /// gives an alternate way to print specific regions. For now, we
83 /// always print those regions using a number, so something like "`'0`".
84 ///
85 /// Regions not selected by the region highlight mode are presently
86 /// unaffected.
87 #[derive(Copy, Clone, Default)]
88 pub struct RegionHighlightMode {
89     /// If enabled, when we see the selected region, use "`'N`"
90     /// instead of the ordinary behavior.
91     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
92
93     /// If enabled, when printing a "free region" that originated from
94     /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
95     /// have names print as normal.
96     ///
97     /// This is used when you have a signature like `fn foo(x: &u32,
98     /// y: &'a u32)` and we want to give a name to the region of the
99     /// reference `x`.
100     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
101 }
102
103 impl RegionHighlightMode {
104     /// If `region` and `number` are both `Some`, invokes
105     /// `highlighting_region`.
106     pub fn maybe_highlighting_region(
107         &mut self,
108         region: Option<ty::Region<'_>>,
109         number: Option<usize>,
110     ) {
111         if let Some(k) = region {
112             if let Some(n) = number {
113                 self.highlighting_region(k, n);
114             }
115         }
116     }
117
118     /// Highlights the region inference variable `vid` as `'N`.
119     pub fn highlighting_region(
120         &mut self,
121         region: ty::Region<'_>,
122         number: usize,
123     ) {
124         let num_slots = self.highlight_regions.len();
125         let first_avail_slot = self.highlight_regions.iter_mut()
126             .filter(|s| s.is_none())
127             .next()
128             .unwrap_or_else(|| {
129                 bug!(
130                     "can only highlight {} placeholders at a time",
131                     num_slots,
132                 )
133             });
134         *first_avail_slot = Some((*region, number));
135     }
136
137     /// Convenience wrapper for `highlighting_region`.
138     pub fn highlighting_region_vid(
139         &mut self,
140         vid: ty::RegionVid,
141         number: usize,
142     ) {
143         self.highlighting_region(&ty::ReVar(vid), number)
144     }
145
146     /// Returns `Some(n)` with the number to use for the given region, if any.
147     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
148         self
149             .highlight_regions
150             .iter()
151             .filter_map(|h| match h {
152                 Some((r, n)) if r == region => Some(*n),
153                 _ => None,
154             })
155             .next()
156     }
157
158     /// Highlight the given bound region.
159     /// We can only highlight one bound region at a time. See
160     /// the field `highlight_bound_region` for more detailed notes.
161     pub fn highlighting_bound_region(
162         &mut self,
163         br: ty::BoundRegion,
164         number: usize,
165     ) {
166         assert!(self.highlight_bound_region.is_none());
167         self.highlight_bound_region = Some((br, number));
168     }
169 }
170
171 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
172 pub trait PrettyPrinter:
173     Printer<
174         Error = fmt::Error,
175         Path = Self,
176         Region = Self,
177         Type = Self,
178     > +
179     fmt::Write
180 {
181     /// Enter a nested print context, for pretty-printing
182     /// nested components in some larger context.
183     fn nest<'a, 'gcx, 'tcx, E>(
184         self: PrintCx<'a, 'gcx, 'tcx, Self>,
185         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, Self>) -> Result<Self, E>,
186     ) -> Result<PrintCx<'a, 'gcx, 'tcx, Self>, E> {
187         let printer = f(PrintCx {
188             tcx: self.tcx,
189             printer: self.printer,
190             config: self.config,
191         })?;
192         Ok(PrintCx {
193             tcx: self.tcx,
194             printer,
195             config: self.config,
196         })
197     }
198
199     /// Like `print_def_path` but for value paths.
200     fn print_value_path(
201         self: PrintCx<'_, '_, 'tcx, Self>,
202         def_id: DefId,
203         substs: Option<SubstsRef<'tcx>>,
204     ) -> Result<Self::Path, Self::Error> {
205         self.print_def_path(def_id, substs, iter::empty())
206     }
207
208     /// Print `<...>` around what `f` prints.
209     fn generic_delimiters<'gcx, 'tcx>(
210         self: PrintCx<'_, 'gcx, 'tcx, Self>,
211         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, Self>) -> Result<Self, Self::Error>,
212     ) -> Result<Self, Self::Error>;
213
214     /// Return `true` if the region should be printed in path generic args
215     /// even when it's `'_`, such as in e.g. `Foo<'_, '_, '_>`.
216     fn always_print_region_in_paths(
217         self: &PrintCx<'_, '_, '_, Self>,
218         _region: ty::Region<'_>,
219     ) -> bool {
220         false
221     }
222
223     // HACK(eddyb) Trying to print a lifetime might not print anything, which
224     // may need special handling in the caller (of `ty::RegionKind::print`).
225     // To avoid printing to a temporary string (which isn't even supported),
226     // the `print_region_outputs_anything` method can instead be used to
227     // determine this, ahead of time.
228     //
229     // NB: this must be kept in sync with the implementation of `print_region`.
230     fn print_region_outputs_anything(
231         self: &PrintCx<'_, '_, '_, Self>,
232         region: ty::Region<'_>,
233     ) -> bool;
234 }
235
236 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
237     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
238     // (but also some things just print a `DefId` generally so maybe we need this?)
239     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
240         match self.def_key(def_id).disambiguated_data.data {
241             DefPathData::ValueNs(..) |
242             DefPathData::EnumVariant(..) |
243             DefPathData::Field(..) |
244             DefPathData::AnonConst |
245             DefPathData::ConstParam(..) |
246             DefPathData::ClosureExpr |
247             DefPathData::StructCtor => Namespace::ValueNS,
248
249             DefPathData::MacroDef(..) => Namespace::MacroNS,
250
251             _ => Namespace::TypeNS,
252         }
253     }
254
255     /// Returns a string identifying this `DefId. This string is
256     /// suitable for user output.
257     pub fn def_path_str(self, def_id: DefId) -> String {
258         let ns = self.guess_def_namespace(def_id);
259         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
260         let mut s = String::new();
261         let _ = PrintCx::with(self, FmtPrinter::new(&mut s, ns), |cx| {
262             cx.print_def_path(def_id, None, iter::empty())
263         });
264         s
265     }
266 }
267
268 pub struct FmtPrinter<F: fmt::Write> {
269     fmt: F,
270     empty: bool,
271     in_value: bool,
272     pub region_highlight_mode: RegionHighlightMode,
273 }
274
275 impl<F: fmt::Write> FmtPrinter<F> {
276     pub fn new(fmt: F, ns: Namespace) -> Self {
277         FmtPrinter {
278             fmt,
279             empty: true,
280             in_value: ns == Namespace::ValueNS,
281             region_highlight_mode: RegionHighlightMode::default(),
282         }
283     }
284 }
285
286 impl<'gcx, 'tcx, P: PrettyPrinter> PrintCx<'_, 'gcx, 'tcx, P> {
287     /// If possible, this returns a global path resolving to `def_id` that is visible
288     /// from at least one local module and returns true. If the crate defining `def_id` is
289     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
290     fn try_print_visible_def_path(
291         mut self,
292         def_id: DefId,
293     ) -> Result<(P, bool), P::Error> {
294         define_scoped_cx!(self);
295
296         debug!("try_print_visible_def_path: def_id={:?}", def_id);
297
298         // If `def_id` is a direct or injected extern crate, return the
299         // path to the crate followed by the path to the item within the crate.
300         if def_id.index == CRATE_DEF_INDEX {
301             let cnum = def_id.krate;
302
303             if cnum == LOCAL_CRATE {
304                 return Ok((self.path_crate(cnum)?, true));
305             }
306
307             // In local mode, when we encounter a crate other than
308             // LOCAL_CRATE, execution proceeds in one of two ways:
309             //
310             // 1. for a direct dependency, where user added an
311             //    `extern crate` manually, we put the `extern
312             //    crate` as the parent. So you wind up with
313             //    something relative to the current crate.
314             // 2. for an extern inferred from a path or an indirect crate,
315             //    where there is no explicit `extern crate`, we just prepend
316             //    the crate name.
317             match *self.tcx.extern_crate(def_id) {
318                 Some(ExternCrate {
319                     src: ExternCrateSource::Extern(def_id),
320                     direct: true,
321                     span,
322                     ..
323                 }) => {
324                     debug!("try_print_visible_def_path: def_id={:?}", def_id);
325                     return Ok((if !span.is_dummy() {
326                         self.print_def_path(def_id, None, iter::empty())?
327                     } else {
328                         self.path_crate(cnum)?
329                     }, true));
330                 }
331                 None => {
332                     return Ok((self.path_crate(cnum)?, true));
333                 }
334                 _ => {},
335             }
336         }
337
338         if def_id.is_local() {
339             return Ok((self.printer, false));
340         }
341
342         let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
343
344         let mut cur_def_key = self.tcx.def_key(def_id);
345         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
346
347         // For a UnitStruct or TupleStruct we want the name of its parent rather than <unnamed>.
348         if let DefPathData::StructCtor = cur_def_key.disambiguated_data.data {
349             let parent = DefId {
350                 krate: def_id.krate,
351                 index: cur_def_key.parent.expect("DefPathData::StructCtor missing a parent"),
352             };
353
354             cur_def_key = self.tcx.def_key(parent);
355         }
356
357         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
358             Some(parent) => parent,
359             None => return Ok((self.printer, false)),
360         };
361         // HACK(eddyb) this uses `nest` to avoid knowing ahead of time whether
362         // the entire path will succeed or not. To support printers that do not
363         // implement `PrettyPrinter`, a `Vec` or linked list on the stack would
364         // need to be built, before starting to print anything.
365         let mut prefix_success = false;
366         nest!(|cx| {
367             let (printer, success) = cx.try_print_visible_def_path(visible_parent)?;
368             prefix_success = success;
369             Ok(printer)
370         });
371         if !prefix_success {
372             return Ok((self.printer, false));
373         };
374         let actual_parent = self.tcx.parent(def_id);
375         debug!(
376             "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
377             visible_parent, actual_parent,
378         );
379
380         let data = cur_def_key.disambiguated_data.data;
381         debug!(
382             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
383             data, visible_parent, actual_parent,
384         );
385
386         let symbol = match data {
387             // In order to output a path that could actually be imported (valid and visible),
388             // we need to handle re-exports correctly.
389             //
390             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
391             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
392             //
393             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
394             // private so the "true" path to `CommandExt` isn't accessible.
395             //
396             // In this case, the `visible_parent_map` will look something like this:
397             //
398             // (child) -> (parent)
399             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
400             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
401             // `std::sys::unix::ext` -> `std::os`
402             //
403             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
404             // `std::os`.
405             //
406             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
407             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
408             // to the parent - resulting in a mangled path like
409             // `std::os::ext::process::CommandExt`.
410             //
411             // Instead, we must detect that there was a re-export and instead print `unix`
412             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
413             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
414             // the visible parent (`std::os`). If these do not match, then we iterate over
415             // the children of the visible parent (as was done when computing
416             // `visible_parent_map`), looking for the specific child we currently have and then
417             // have access to the re-exported name.
418             DefPathData::Module(actual_name) |
419             DefPathData::TypeNs(actual_name) if Some(visible_parent) != actual_parent => {
420                 self.tcx.item_children(visible_parent)
421                     .iter()
422                     .find(|child| child.def.def_id() == def_id)
423                     .map(|child| child.ident.as_str())
424                     .unwrap_or_else(|| actual_name.as_str())
425             }
426             _ => {
427                 data.get_opt_name().map(|n| n.as_str()).unwrap_or_else(|| {
428                     // Re-exported `extern crate` (#43189).
429                     if let DefPathData::CrateRoot = data {
430                         self.tcx.original_crate_name(def_id.krate).as_str()
431                     } else {
432                         Symbol::intern("<unnamed>").as_str()
433                     }
434                 })
435             },
436         };
437         debug!("try_print_visible_def_path: symbol={:?}", symbol);
438         Ok((self.path_append(|cx| Ok(cx.printer), &symbol)?, true))
439     }
440
441     pub fn pretty_path_qualified(
442         self,
443         self_ty: Ty<'tcx>,
444         trait_ref: Option<ty::TraitRef<'tcx>>,
445     ) -> Result<P::Path, P::Error> {
446         if trait_ref.is_none() {
447             // Inherent impls. Try to print `Foo::bar` for an inherent
448             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
449             // anything other than a simple path.
450             match self_ty.sty {
451                 ty::Adt(..) | ty::Foreign(_) |
452                 ty::Bool | ty::Char | ty::Str |
453                 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
454                     return self_ty.print(self);
455                 }
456
457                 _ => {}
458             }
459         }
460
461         self.generic_delimiters(|mut cx| {
462             define_scoped_cx!(cx);
463
464             p!(print(self_ty));
465             if let Some(trait_ref) = trait_ref {
466                 p!(write(" as "), print(trait_ref));
467             }
468             Ok(cx.printer)
469         })
470     }
471
472     pub fn pretty_path_append_impl(
473         mut self,
474         print_prefix: impl FnOnce(
475             PrintCx<'_, 'gcx, 'tcx, P>,
476         ) -> Result<P::Path, P::Error>,
477         self_ty: Ty<'tcx>,
478         trait_ref: Option<ty::TraitRef<'tcx>>,
479     ) -> Result<P::Path, P::Error> {
480         self = self.nest(print_prefix)?;
481
482         self.generic_delimiters(|mut cx| {
483             define_scoped_cx!(cx);
484
485             p!(write("impl "));
486             if let Some(trait_ref) = trait_ref {
487                 p!(print(trait_ref), write(" for "));
488             }
489             p!(print(self_ty));
490
491             Ok(cx.printer)
492         })
493     }
494
495     pub fn pretty_path_generic_args(
496         mut self,
497         print_prefix: impl FnOnce(
498             PrintCx<'_, 'gcx, 'tcx, P>,
499         ) -> Result<P::Path, P::Error>,
500         params: &[ty::GenericParamDef],
501         substs: SubstsRef<'tcx>,
502         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
503     ) -> Result<P::Path, P::Error> {
504         self = self.nest(print_prefix)?;
505
506         // Don't print `'_` if there's no printed region.
507         let print_regions = params.iter().any(|param| {
508             match substs[param.index as usize].unpack() {
509                 UnpackedKind::Lifetime(r) => {
510                     self.always_print_region_in_paths(r) ||
511                     self.print_region_outputs_anything(r)
512                 }
513                 _ => false,
514             }
515         });
516
517         // Don't print args that are the defaults of their respective parameters.
518         let num_supplied_defaults = if self.tcx.sess.verbose() {
519             0
520         } else {
521             params.iter().rev().take_while(|param| {
522                 match param.kind {
523                     ty::GenericParamDefKind::Lifetime => false,
524                     ty::GenericParamDefKind::Type { has_default, .. } => {
525                         has_default && substs[param.index as usize] == Kind::from(
526                             self.tcx.type_of(param.def_id).subst(self.tcx, substs)
527                         )
528                     }
529                     ty::GenericParamDefKind::Const => false, // FIXME(const_generics:defaults)
530                 }
531             }).count()
532         };
533
534         let params = &params[..params.len() - num_supplied_defaults];
535         let mut args = params.iter().map(|param| {
536             substs[param.index as usize]
537         }).filter(|arg| {
538             match arg.unpack() {
539                 UnpackedKind::Lifetime(_) => print_regions,
540                 _ => true,
541             }
542         });
543         let arg0 = args.next();
544
545         let mut projections = projections;
546         let projection0 = projections.next();
547
548         if arg0.is_none() && projection0.is_none() {
549             return Ok(self.printer);
550         }
551
552         self.generic_delimiters(|mut cx| {
553             define_scoped_cx!(cx);
554
555             let mut empty = true;
556             let mut maybe_comma = |cx: &mut Self| {
557                 if empty {
558                     empty = false;
559                     Ok(())
560                 } else {
561                     write!(cx.printer, ", ")
562                 }
563             };
564
565             for arg in arg0.into_iter().chain(args) {
566                 maybe_comma(&mut cx)?;
567
568                 if let UnpackedKind::Lifetime(region) = arg.unpack() {
569                     if !cx.print_region_outputs_anything(region) {
570                         // This happens when the value of the region
571                         // parameter is not easily serialized. This may be
572                         // because the user omitted it in the first place,
573                         // or because it refers to some block in the code,
574                         // etc. I'm not sure how best to serialize this.
575                         p!(write("'_"));
576
577                         continue;
578                     }
579                 }
580
581                 p!(print(arg));
582             }
583
584             for projection in projection0.into_iter().chain(projections) {
585                 maybe_comma(&mut cx)?;
586
587                 p!(write("{}=", cx.tcx.associated_item(projection.item_def_id).ident),
588                    print(projection.ty));
589             }
590
591             Ok(cx.printer)
592         })
593     }
594 }
595
596 impl<F: fmt::Write> fmt::Write for FmtPrinter<F> {
597     fn write_str(&mut self, s: &str) -> fmt::Result {
598         self.empty &= s.is_empty();
599         self.fmt.write_str(s)
600     }
601 }
602
603 impl<F: fmt::Write> Printer for FmtPrinter<F> {
604     type Error = fmt::Error;
605
606     type Path = Self;
607     type Region = Self;
608     type Type = Self;
609
610     fn print_def_path(
611         mut self: PrintCx<'_, '_, 'tcx, Self>,
612         def_id: DefId,
613         substs: Option<SubstsRef<'tcx>>,
614         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
615     ) -> Result<Self::Path, Self::Error> {
616         // FIXME(eddyb) avoid querying `tcx.generics_of` and `tcx.def_key`
617         // both here and in `default_print_def_path`.
618         let generics = substs.map(|_| self.tcx.generics_of(def_id));
619         if generics.as_ref().and_then(|g| g.parent).is_none() {
620             let mut visible_path_success = false;
621             self = self.nest(|cx| {
622                 let (printer, success) = cx.try_print_visible_def_path(def_id)?;
623                 visible_path_success = success;
624                 Ok(printer)
625             })?;
626             if visible_path_success {
627                 return if let (Some(generics), Some(substs)) = (generics, substs) {
628                     let has_own_self = generics.has_self && generics.parent_count == 0;
629                     let params = &generics.params[has_own_self as usize..];
630                     self.path_generic_args(|cx| Ok(cx.printer), params, substs, projections)
631                 } else {
632                     Ok(self.printer)
633                 };
634             }
635         }
636
637         let key = self.tcx.def_key(def_id);
638         if let DefPathData::Impl = key.disambiguated_data.data {
639             // Always use types for non-local impls, where types are always
640             // available, and filename/line-number is mostly uninteresting.
641             let use_types =
642                 !def_id.is_local() || {
643                     // Otherwise, use filename/line-number if forced.
644                     let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
645                     !force_no_types
646                 };
647
648             if !use_types {
649                 // If no type info is available, fall back to
650                 // pretty printing some span information. This should
651                 // only occur very early in the compiler pipeline.
652                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
653                 let span = self.tcx.def_span(def_id);
654                 return self.path_append(
655                     |cx| cx.print_def_path(parent_def_id, None, iter::empty()),
656                     &format!("<impl at {:?}>", span),
657                 );
658             }
659         }
660
661         self.default_print_def_path(def_id, substs, projections)
662     }
663
664     fn print_region(
665         self: PrintCx<'_, '_, '_, Self>,
666         region: ty::Region<'_>,
667     ) -> Result<Self::Region, Self::Error> {
668         self.pretty_print_region(region)
669     }
670
671     fn print_type(
672         self: PrintCx<'_, '_, 'tcx, Self>,
673         ty: Ty<'tcx>,
674     ) -> Result<Self::Type, Self::Error> {
675         self.pretty_print_type(ty)
676     }
677
678     fn path_crate(
679         mut self: PrintCx<'_, '_, '_, Self>,
680         cnum: CrateNum,
681     ) -> Result<Self::Path, Self::Error> {
682         if cnum == LOCAL_CRATE {
683             if self.tcx.sess.rust_2018() {
684                 // We add the `crate::` keyword on Rust 2018, only when desired.
685                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
686                     write!(self.printer, "{}", keywords::Crate.name())?;
687                 }
688             }
689             Ok(self.printer)
690         } else {
691             write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
692             Ok(self.printer)
693         }
694     }
695     fn path_qualified(
696         self: PrintCx<'_, '_, 'tcx, Self>,
697         self_ty: Ty<'tcx>,
698         trait_ref: Option<ty::TraitRef<'tcx>>,
699     ) -> Result<Self::Path, Self::Error> {
700         self.pretty_path_qualified(self_ty, trait_ref)
701     }
702
703     fn path_append_impl<'gcx, 'tcx>(
704         self: PrintCx<'_, 'gcx, 'tcx, Self>,
705         print_prefix: impl FnOnce(
706             PrintCx<'_, 'gcx, 'tcx, Self>,
707         ) -> Result<Self::Path, Self::Error>,
708         self_ty: Ty<'tcx>,
709         trait_ref: Option<ty::TraitRef<'tcx>>,
710     ) -> Result<Self::Path, Self::Error> {
711         self.pretty_path_append_impl(|cx| {
712             let mut printer = print_prefix(cx)?;
713
714             // HACK(eddyb) this accounts for `generic_delimiters`
715             // printing `::<` instead of `<` if `in_value` is set.
716             if !printer.empty && !printer.in_value {
717                 write!(printer, "::")?;
718             }
719
720             Ok(printer)
721         }, self_ty, trait_ref)
722     }
723     fn path_append<'gcx, 'tcx>(
724         self: PrintCx<'_, 'gcx, 'tcx, Self>,
725         print_prefix: impl FnOnce(
726             PrintCx<'_, 'gcx, 'tcx, Self>,
727         ) -> Result<Self::Path, Self::Error>,
728         text: &str,
729     ) -> Result<Self::Path, Self::Error> {
730         let mut printer = print_prefix(self)?;
731
732         // FIXME(eddyb) `text` should never be empty, but it
733         // currently is for `extern { ... }` "foreign modules".
734         if !text.is_empty() {
735             if !printer.empty {
736                 write!(printer, "::")?;
737             }
738             write!(printer, "{}", text)?;
739         }
740
741         Ok(printer)
742     }
743     fn path_generic_args<'gcx, 'tcx>(
744         self: PrintCx<'_, 'gcx, 'tcx, Self>,
745         print_prefix: impl FnOnce(
746             PrintCx<'_, 'gcx, 'tcx, Self>,
747         ) -> Result<Self::Path, Self::Error>,
748         params: &[ty::GenericParamDef],
749         substs: SubstsRef<'tcx>,
750         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
751     ) -> Result<Self::Path, Self::Error> {
752         self.pretty_path_generic_args(print_prefix, params, substs, projections)
753     }
754 }
755
756 impl<F: fmt::Write> PrettyPrinter for FmtPrinter<F> {
757     fn nest<'a, 'gcx, 'tcx, E>(
758         mut self: PrintCx<'a, 'gcx, 'tcx, Self>,
759         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, Self>) -> Result<Self, E>,
760     ) -> Result<PrintCx<'a, 'gcx, 'tcx, Self>, E> {
761         let was_empty = std::mem::replace(&mut self.printer.empty, true);
762         let mut printer = f(PrintCx {
763             tcx: self.tcx,
764             printer: self.printer,
765             config: self.config,
766         })?;
767         printer.empty &= was_empty;
768         Ok(PrintCx {
769             tcx: self.tcx,
770             printer,
771             config: self.config,
772         })
773     }
774
775     fn print_value_path(
776         mut self: PrintCx<'_, '_, 'tcx, Self>,
777         def_id: DefId,
778         substs: Option<SubstsRef<'tcx>>,
779     ) -> Result<Self::Path, Self::Error> {
780         let was_in_value = std::mem::replace(&mut self.printer.in_value, true);
781         let mut printer = self.print_def_path(def_id, substs, iter::empty())?;
782         printer.in_value = was_in_value;
783
784         Ok(printer)
785     }
786
787     fn generic_delimiters<'gcx, 'tcx>(
788         mut self: PrintCx<'_, 'gcx, 'tcx, Self>,
789         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, Self>) -> Result<Self, Self::Error>,
790     ) -> Result<Self, Self::Error> {
791         if !self.printer.empty && self.printer.in_value {
792             write!(self.printer, "::<")?;
793         } else {
794             write!(self.printer, "<")?;
795         }
796
797         let was_in_value = std::mem::replace(&mut self.printer.in_value, false);
798         let mut printer = f(self)?;
799         printer.in_value = was_in_value;
800
801         write!(printer, ">")?;
802         Ok(printer)
803     }
804
805     fn always_print_region_in_paths(
806         self: &PrintCx<'_, '_, '_, Self>,
807         region: ty::Region<'_>,
808     ) -> bool {
809         *region != ty::ReErased
810     }
811
812     fn print_region_outputs_anything(
813         self: &PrintCx<'_, '_, '_, Self>,
814         region: ty::Region<'_>,
815     ) -> bool {
816         let highlight = self.printer.region_highlight_mode;
817         if highlight.region_highlighted(region).is_some() {
818             return true;
819         }
820
821         if self.tcx.sess.verbose() {
822             return true;
823         }
824
825         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
826
827         match *region {
828             ty::ReEarlyBound(ref data) => {
829                 data.name != "" && data.name != "'_"
830             }
831
832             ty::ReLateBound(_, br) |
833             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
834             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
835                 if let ty::BrNamed(_, name) = br {
836                     if name != "" && name != "'_" {
837                         return true;
838                     }
839                 }
840
841                 if let Some((region, _)) = highlight.highlight_bound_region {
842                     if br == region {
843                         return true;
844                     }
845                 }
846
847                 false
848             }
849
850             ty::ReScope(_) |
851             ty::ReVar(_) if identify_regions => true,
852
853             ty::ReVar(_) |
854             ty::ReScope(_) |
855             ty::ReErased => false,
856
857             ty::ReStatic |
858             ty::ReEmpty |
859             ty::ReClosureBound(_) => true,
860         }
861     }
862 }
863
864 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
865 impl<F: fmt::Write> FmtPrinter<F> {
866     pub fn pretty_print_region(
867         mut self: PrintCx<'_, '_, '_, Self>,
868         region: ty::Region<'_>,
869     ) -> Result<Self, fmt::Error> {
870         define_scoped_cx!(self);
871
872         // Watch out for region highlights.
873         let highlight = self.printer.region_highlight_mode;
874         if let Some(n) = highlight.region_highlighted(region) {
875             p!(write("'{}", n));
876             return Ok(self.printer);
877         }
878
879         if self.tcx.sess.verbose() {
880             p!(write("{:?}", region));
881             return Ok(self.printer);
882         }
883
884         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
885
886         // These printouts are concise.  They do not contain all the information
887         // the user might want to diagnose an error, but there is basically no way
888         // to fit that into a short string.  Hence the recommendation to use
889         // `explain_region()` or `note_and_explain_region()`.
890         match *region {
891             ty::ReEarlyBound(ref data) => {
892                 if data.name != "'_" {
893                     p!(write("{}", data.name));
894                 }
895             }
896             ty::ReLateBound(_, br) |
897             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
898             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
899                 if let ty::BrNamed(_, name) = br {
900                     if name != "" && name != "'_" {
901                         p!(write("{}", name));
902                         return Ok(self.printer);
903                     }
904                 }
905
906                 if let Some((region, counter)) = highlight.highlight_bound_region {
907                     if br == region {
908                         p!(write("'{}", counter));
909                     }
910                 }
911             }
912             ty::ReScope(scope) if identify_regions => {
913                 match scope.data {
914                     region::ScopeData::Node =>
915                         p!(write("'{}s", scope.item_local_id().as_usize())),
916                     region::ScopeData::CallSite =>
917                         p!(write("'{}cs", scope.item_local_id().as_usize())),
918                     region::ScopeData::Arguments =>
919                         p!(write("'{}as", scope.item_local_id().as_usize())),
920                     region::ScopeData::Destruction =>
921                         p!(write("'{}ds", scope.item_local_id().as_usize())),
922                     region::ScopeData::Remainder(first_statement_index) => p!(write(
923                         "'{}_{}rs",
924                         scope.item_local_id().as_usize(),
925                         first_statement_index.index()
926                     )),
927                 }
928             }
929             ty::ReVar(region_vid) if identify_regions => {
930                 p!(write("{:?}", region_vid));
931             }
932             ty::ReVar(_) => {}
933             ty::ReScope(_) |
934             ty::ReErased => {}
935             ty::ReStatic => p!(write("'static")),
936             ty::ReEmpty => p!(write("'<empty>")),
937
938             // The user should never encounter these in unsubstituted form.
939             ty::ReClosureBound(vid) => p!(write("{:?}", vid)),
940         }
941
942         Ok(self.printer)
943     }
944 }
945
946 impl<'gcx, 'tcx, P: PrettyPrinter> PrintCx<'_, 'gcx, 'tcx, P> {
947     pub fn pretty_print_type(
948         mut self,
949         ty: Ty<'tcx>,
950     ) -> Result<P::Type, P::Error> {
951         define_scoped_cx!(self);
952
953         match ty.sty {
954             ty::Bool => p!(write("bool")),
955             ty::Char => p!(write("char")),
956             ty::Int(t) => p!(write("{}", t.ty_to_string())),
957             ty::Uint(t) => p!(write("{}", t.ty_to_string())),
958             ty::Float(t) => p!(write("{}", t.ty_to_string())),
959             ty::RawPtr(ref tm) => {
960                 p!(write("*{} ", match tm.mutbl {
961                     hir::MutMutable => "mut",
962                     hir::MutImmutable => "const",
963                 }));
964                 p!(print(tm.ty))
965             }
966             ty::Ref(r, ty, mutbl) => {
967                 p!(write("&"));
968                 if self.print_region_outputs_anything(r) {
969                     p!(print(r), write(" "));
970                 }
971                 p!(print(ty::TypeAndMut { ty, mutbl }))
972             }
973             ty::Never => p!(write("!")),
974             ty::Tuple(ref tys) => {
975                 p!(write("("));
976                 let mut tys = tys.iter();
977                 if let Some(&ty) = tys.next() {
978                     p!(print(ty), write(","));
979                     if let Some(&ty) = tys.next() {
980                         p!(write(" "), print(ty));
981                         for &ty in tys {
982                             p!(write(", "), print(ty));
983                         }
984                     }
985                 }
986                 p!(write(")"))
987             }
988             ty::FnDef(def_id, substs) => {
989                 let sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
990                 p!(print(sig), write(" {{"));
991                 nest!(|cx| cx.print_value_path(def_id, Some(substs)));
992                 p!(write("}}"))
993             }
994             ty::FnPtr(ref bare_fn) => {
995                 p!(print(bare_fn))
996             }
997             ty::Infer(infer_ty) => p!(write("{}", infer_ty)),
998             ty::Error => p!(write("[type error]")),
999             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
1000             ty::Bound(debruijn, bound_ty) => {
1001                 match bound_ty.kind {
1002                     ty::BoundTyKind::Anon => {
1003                         if debruijn == ty::INNERMOST {
1004                             p!(write("^{}", bound_ty.var.index()))
1005                         } else {
1006                             p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
1007                         }
1008                     }
1009
1010                     ty::BoundTyKind::Param(p) => p!(write("{}", p)),
1011                 }
1012             }
1013             ty::Adt(def, substs) => {
1014                 nest!(|cx| cx.print_def_path(def.did, Some(substs), iter::empty()));
1015             }
1016             ty::Dynamic(data, r) => {
1017                 let print_r = self.print_region_outputs_anything(r);
1018                 if print_r {
1019                     p!(write("("));
1020                 }
1021                 p!(write("dyn "), print(data));
1022                 if print_r {
1023                     p!(write(" + "), print(r), write(")"));
1024                 }
1025             }
1026             ty::Foreign(def_id) => {
1027                 nest!(|cx| cx.print_def_path(def_id, None, iter::empty()));
1028             }
1029             ty::Projection(ref data) => p!(print(data)),
1030             ty::UnnormalizedProjection(ref data) => {
1031                 p!(write("Unnormalized("), print(data), write(")"))
1032             }
1033             ty::Placeholder(placeholder) => {
1034                 p!(write("Placeholder({:?})", placeholder))
1035             }
1036             ty::Opaque(def_id, substs) => {
1037                 // FIXME(eddyb) print this with `print_def_path`.
1038                 if self.tcx.sess.verbose() {
1039                     p!(write("Opaque({:?}, {:?})", def_id, substs));
1040                     return Ok(self.printer);
1041                 }
1042
1043                 let def_key = self.tcx.def_key(def_id);
1044                 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1045                     p!(write("{}", name));
1046                     let mut substs = substs.iter();
1047                     // FIXME(eddyb) print this with `print_def_path`.
1048                     if let Some(first) = substs.next() {
1049                         p!(write("::<"));
1050                         p!(print(first));
1051                         for subst in substs {
1052                             p!(write(", "), print(subst));
1053                         }
1054                         p!(write(">"));
1055                     }
1056                     return Ok(self.printer);
1057                 }
1058                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1059                 // by looking up the projections associated with the def_id.
1060                 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
1061
1062                 let mut first = true;
1063                 let mut is_sized = false;
1064                 p!(write("impl"));
1065                 for predicate in bounds.predicates {
1066                     if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1067                         // Don't print +Sized, but rather +?Sized if absent.
1068                         if Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() {
1069                             is_sized = true;
1070                             continue;
1071                         }
1072
1073                         p!(
1074                                 write("{}", if first { " " } else { "+" }),
1075                                 print(trait_ref));
1076                         first = false;
1077                     }
1078                 }
1079                 if !is_sized {
1080                     p!(write("{}?Sized", if first { " " } else { "+" }));
1081                 } else if first {
1082                     p!(write(" Sized"));
1083                 }
1084             }
1085             ty::Str => p!(write("str")),
1086             ty::Generator(did, substs, movability) => {
1087                 let upvar_tys = substs.upvar_tys(did, self.tcx);
1088                 let witness = substs.witness(did, self.tcx);
1089                 if movability == hir::GeneratorMovability::Movable {
1090                     p!(write("[generator"));
1091                 } else {
1092                     p!(write("[static generator"));
1093                 }
1094
1095                 // FIXME(eddyb) should use `def_span`.
1096                 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1097                     p!(write("@{:?}", self.tcx.hir().span_by_hir_id(hir_id)));
1098                     let mut sep = " ";
1099                     for (freevar, upvar_ty) in self.tcx.freevars(did)
1100                         .as_ref()
1101                         .map_or(&[][..], |fv| &fv[..])
1102                         .iter()
1103                         .zip(upvar_tys)
1104                     {
1105                         p!(
1106                             write("{}{}:",
1107                                     sep,
1108                                     self.tcx.hir().name(freevar.var_id())),
1109                             print(upvar_ty));
1110                         sep = ", ";
1111                     }
1112                 } else {
1113                     // cross-crate closure types should only be
1114                     // visible in codegen bug reports, I imagine.
1115                     p!(write("@{:?}", did));
1116                     let mut sep = " ";
1117                     for (index, upvar_ty) in upvar_tys.enumerate() {
1118                         p!(
1119                                 write("{}{}:", sep, index),
1120                                 print(upvar_ty));
1121                         sep = ", ";
1122                     }
1123                 }
1124
1125                 p!(write(" "), print(witness), write("]"))
1126             },
1127             ty::GeneratorWitness(types) => {
1128                 nest!(|cx| cx.pretty_in_binder(&types))
1129             }
1130             ty::Closure(did, substs) => {
1131                 let upvar_tys = substs.upvar_tys(did, self.tcx);
1132                 p!(write("[closure"));
1133
1134                 // FIXME(eddyb) should use `def_span`.
1135                 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1136                     if self.tcx.sess.opts.debugging_opts.span_free_formats {
1137                         p!(write("@{:?}", hir_id));
1138                     } else {
1139                         p!(write("@{:?}", self.tcx.hir().span_by_hir_id(hir_id)));
1140                     }
1141                     let mut sep = " ";
1142                     for (freevar, upvar_ty) in self.tcx.freevars(did)
1143                         .as_ref()
1144                         .map_or(&[][..], |fv| &fv[..])
1145                         .iter()
1146                         .zip(upvar_tys)
1147                     {
1148                         p!(
1149                             write("{}{}:",
1150                                     sep,
1151                                     self.tcx.hir().name(freevar.var_id())),
1152                             print(upvar_ty));
1153                         sep = ", ";
1154                     }
1155                 } else {
1156                     // cross-crate closure types should only be
1157                     // visible in codegen bug reports, I imagine.
1158                     p!(write("@{:?}", did));
1159                     let mut sep = " ";
1160                     for (index, upvar_ty) in upvar_tys.enumerate() {
1161                         p!(
1162                                 write("{}{}:", sep, index),
1163                                 print(upvar_ty));
1164                         sep = ", ";
1165                     }
1166                 }
1167
1168                 if self.tcx.sess.verbose() {
1169                     p!(write(
1170                         " closure_kind_ty={:?} closure_sig_ty={:?}",
1171                         substs.closure_kind_ty(did, self.tcx),
1172                         substs.closure_sig_ty(did, self.tcx)
1173                     ));
1174                 }
1175
1176                 p!(write("]"))
1177             },
1178             ty::Array(ty, sz) => {
1179                 p!(write("["), print(ty), write("; "));
1180                 match sz {
1181                     ty::LazyConst::Unevaluated(_def_id, _substs) => {
1182                         p!(write("_"));
1183                     }
1184                     ty::LazyConst::Evaluated(c) => {
1185                         match c.val {
1186                             ConstValue::Infer(..) => p!(write("_")),
1187                             ConstValue::Param(ParamConst { name, .. }) =>
1188                                 p!(write("{}", name)),
1189                             _ => p!(write("{}", c.unwrap_usize(self.tcx))),
1190                         }
1191                     }
1192                 }
1193                 p!(write("]"))
1194             }
1195             ty::Slice(ty) => {
1196                 p!(write("["), print(ty), write("]"))
1197             }
1198         }
1199
1200         Ok(self.printer)
1201     }
1202
1203     pub fn pretty_fn_sig(
1204         mut self,
1205         inputs: &[Ty<'tcx>],
1206         c_variadic: bool,
1207         output: Ty<'tcx>,
1208     ) -> Result<P, fmt::Error> {
1209         define_scoped_cx!(self);
1210
1211         p!(write("("));
1212         let mut inputs = inputs.iter();
1213         if let Some(&ty) = inputs.next() {
1214             p!(print(ty));
1215             for &ty in inputs {
1216                 p!(write(", "), print(ty));
1217             }
1218             if c_variadic {
1219                 p!(write(", ..."));
1220             }
1221         }
1222         p!(write(")"));
1223         if !output.is_unit() {
1224             p!(write(" -> "), print(output));
1225         }
1226
1227         Ok(self.printer)
1228     }
1229
1230     pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<P, fmt::Error>
1231         where T: Print<'tcx, P, Output = P, Error = fmt::Error> + TypeFoldable<'tcx>
1232     {
1233         fn name_by_region_index(index: usize) -> InternedString {
1234             match index {
1235                 0 => Symbol::intern("'r"),
1236                 1 => Symbol::intern("'s"),
1237                 i => Symbol::intern(&format!("'t{}", i-2)),
1238             }.as_interned_str()
1239         }
1240
1241         // Replace any anonymous late-bound regions with named
1242         // variants, using gensym'd identifiers, so that we can
1243         // clearly differentiate between named and unnamed regions in
1244         // the output. We'll probably want to tweak this over time to
1245         // decide just how much information to give.
1246         if self.config.binder_depth == 0 {
1247             self.prepare_late_bound_region_info(value);
1248         }
1249
1250         let mut empty = true;
1251         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1252             write!(cx.printer, "{}", if empty {
1253                 empty = false;
1254                 start
1255             } else {
1256                 cont
1257             })
1258         };
1259
1260         // NOTE(eddyb) this must be below `start_or_continue`'s definition
1261         // as that also has a `define_scoped_cx` and that kind of shadowing
1262         // is disallowed (name resolution thinks `scoped_cx!` is ambiguous).
1263         define_scoped_cx!(self);
1264
1265         let old_region_index = self.config.region_index;
1266         let mut region_index = old_region_index;
1267         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1268             let _ = start_or_continue(&mut self, "for<", ", ");
1269             let br = match br {
1270                 ty::BrNamed(_, name) => {
1271                     let _ = write!(self.printer, "{}", name);
1272                     br
1273                 }
1274                 ty::BrAnon(_) |
1275                 ty::BrFresh(_) |
1276                 ty::BrEnv => {
1277                     let name = loop {
1278                         let name = name_by_region_index(region_index);
1279                         region_index += 1;
1280                         if !self.is_name_used(&name) {
1281                             break name;
1282                         }
1283                     };
1284                     let _ = write!(self.printer, "{}", name);
1285                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1286                 }
1287             };
1288             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1289         }).0;
1290         start_or_continue(&mut self, "", "> ")?;
1291
1292         // Push current state to gcx, and restore after writing new_value.
1293         self.config.binder_depth += 1;
1294         self.config.region_index = region_index;
1295         let result = new_value.print(PrintCx {
1296             tcx: self.tcx,
1297             printer: self.printer,
1298             config: self.config,
1299         });
1300         self.config.region_index = old_region_index;
1301         self.config.binder_depth -= 1;
1302         result
1303     }
1304
1305     fn is_name_used(&self, name: &InternedString) -> bool {
1306         match self.config.used_region_names {
1307             Some(ref names) => names.contains(name),
1308             None => false,
1309         }
1310     }
1311 }