]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print/pretty.rs
rustc: remove fields from ty::print::PrintConfig available from tcx.
[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_display(self);
455                 }
456
457                 _ => {}
458             }
459         }
460
461         self.generic_delimiters(|mut cx| {
462             define_scoped_cx!(cx);
463
464             p!(print_display(self_ty));
465             if let Some(trait_ref) = trait_ref {
466                 p!(write(" as "), print_display(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_display(trait_ref), write(" for "));
488             }
489             p!(print_display(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_display(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_display(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             return region.print_debug(self);
881         }
882
883         let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
884
885         // These printouts are concise.  They do not contain all the information
886         // the user might want to diagnose an error, but there is basically no way
887         // to fit that into a short string.  Hence the recommendation to use
888         // `explain_region()` or `note_and_explain_region()`.
889         match *region {
890             ty::ReEarlyBound(ref data) => {
891                 if data.name != "'_" {
892                     p!(write("{}", data.name));
893                 }
894             }
895             ty::ReLateBound(_, br) |
896             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
897             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
898                 if let ty::BrNamed(_, name) = br {
899                     if name != "" && name != "'_" {
900                         p!(write("{}", name));
901                         return Ok(self.printer);
902                     }
903                 }
904
905                 if let Some((region, counter)) = highlight.highlight_bound_region {
906                     if br == region {
907                         p!(write("'{}", counter));
908                     }
909                 }
910             }
911             ty::ReScope(scope) if identify_regions => {
912                 match scope.data {
913                     region::ScopeData::Node =>
914                         p!(write("'{}s", scope.item_local_id().as_usize())),
915                     region::ScopeData::CallSite =>
916                         p!(write("'{}cs", scope.item_local_id().as_usize())),
917                     region::ScopeData::Arguments =>
918                         p!(write("'{}as", scope.item_local_id().as_usize())),
919                     region::ScopeData::Destruction =>
920                         p!(write("'{}ds", scope.item_local_id().as_usize())),
921                     region::ScopeData::Remainder(first_statement_index) => p!(write(
922                         "'{}_{}rs",
923                         scope.item_local_id().as_usize(),
924                         first_statement_index.index()
925                     )),
926                 }
927             }
928             ty::ReVar(region_vid) if identify_regions => {
929                 p!(write("{:?}", region_vid));
930             }
931             ty::ReVar(_) => {}
932             ty::ReScope(_) |
933             ty::ReErased => {}
934             ty::ReStatic => p!(write("'static")),
935             ty::ReEmpty => p!(write("'<empty>")),
936
937             // The user should never encounter these in unsubstituted form.
938             ty::ReClosureBound(vid) => p!(write("{:?}", vid)),
939         }
940
941         Ok(self.printer)
942     }
943 }
944
945 impl<'gcx, 'tcx, P: PrettyPrinter> PrintCx<'_, 'gcx, 'tcx, P> {
946     pub fn pretty_print_type(
947         mut self,
948         ty: Ty<'tcx>,
949     ) -> Result<P::Type, P::Error> {
950         define_scoped_cx!(self);
951
952         match ty.sty {
953             ty::Bool => p!(write("bool")),
954             ty::Char => p!(write("char")),
955             ty::Int(t) => p!(write("{}", t.ty_to_string())),
956             ty::Uint(t) => p!(write("{}", t.ty_to_string())),
957             ty::Float(t) => p!(write("{}", t.ty_to_string())),
958             ty::RawPtr(ref tm) => {
959                 p!(write("*{} ", match tm.mutbl {
960                     hir::MutMutable => "mut",
961                     hir::MutImmutable => "const",
962                 }));
963                 p!(print(tm.ty))
964             }
965             ty::Ref(r, ty, mutbl) => {
966                 p!(write("&"));
967                 if self.print_region_outputs_anything(r) {
968                     p!(print_display(r), write(" "));
969                 }
970                 p!(print(ty::TypeAndMut { ty, mutbl }))
971             }
972             ty::Never => p!(write("!")),
973             ty::Tuple(ref tys) => {
974                 p!(write("("));
975                 let mut tys = tys.iter();
976                 if let Some(&ty) = tys.next() {
977                     p!(print(ty), write(","));
978                     if let Some(&ty) = tys.next() {
979                         p!(write(" "), print(ty));
980                         for &ty in tys {
981                             p!(write(", "), print(ty));
982                         }
983                     }
984                 }
985                 p!(write(")"))
986             }
987             ty::FnDef(def_id, substs) => {
988                 let sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
989                 p!(print(sig), write(" {{"));
990                 nest!(|cx| cx.print_value_path(def_id, Some(substs)));
991                 p!(write("}}"))
992             }
993             ty::FnPtr(ref bare_fn) => {
994                 p!(print(bare_fn))
995             }
996             ty::Infer(infer_ty) => p!(write("{}", infer_ty)),
997             ty::Error => p!(write("[type error]")),
998             ty::Param(ref param_ty) => p!(write("{}", param_ty)),
999             ty::Bound(debruijn, bound_ty) => {
1000                 match bound_ty.kind {
1001                     ty::BoundTyKind::Anon => {
1002                         if debruijn == ty::INNERMOST {
1003                             p!(write("^{}", bound_ty.var.index()))
1004                         } else {
1005                             p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
1006                         }
1007                     }
1008
1009                     ty::BoundTyKind::Param(p) => p!(write("{}", p)),
1010                 }
1011             }
1012             ty::Adt(def, substs) => {
1013                 nest!(|cx| cx.print_def_path(def.did, Some(substs), iter::empty()));
1014             }
1015             ty::Dynamic(data, r) => {
1016                 let print_r = self.print_region_outputs_anything(r);
1017                 if print_r {
1018                     p!(write("("));
1019                 }
1020                 p!(write("dyn "), print(data));
1021                 if print_r {
1022                     p!(write(" + "), print_display(r), write(")"));
1023                 }
1024             }
1025             ty::Foreign(def_id) => {
1026                 nest!(|cx| cx.print_def_path(def_id, None, iter::empty()));
1027             }
1028             ty::Projection(ref data) => p!(print(data)),
1029             ty::UnnormalizedProjection(ref data) => {
1030                 p!(write("Unnormalized("), print(data), write(")"))
1031             }
1032             ty::Placeholder(placeholder) => {
1033                 p!(write("Placeholder({:?})", placeholder))
1034             }
1035             ty::Opaque(def_id, substs) => {
1036                 if self.tcx.sess.verbose() {
1037                     p!(write("Opaque({:?}, {:?})", def_id, substs));
1038                     return Ok(self.printer);
1039                 }
1040
1041                 let def_key = self.tcx.def_key(def_id);
1042                 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
1043                     p!(write("{}", name));
1044                     let mut substs = substs.iter();
1045                     // FIXME(eddyb) print this with `print_def_path`.
1046                     if let Some(first) = substs.next() {
1047                         p!(write("::<"));
1048                         p!(print_display(first));
1049                         for subst in substs {
1050                             p!(write(", "), print_display(subst));
1051                         }
1052                         p!(write(">"));
1053                     }
1054                     return Ok(self.printer);
1055                 }
1056                 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
1057                 // by looking up the projections associated with the def_id.
1058                 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
1059
1060                 let mut first = true;
1061                 let mut is_sized = false;
1062                 p!(write("impl"));
1063                 for predicate in bounds.predicates {
1064                     if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
1065                         // Don't print +Sized, but rather +?Sized if absent.
1066                         if Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() {
1067                             is_sized = true;
1068                             continue;
1069                         }
1070
1071                         p!(
1072                                 write("{}", if first { " " } else { "+" }),
1073                                 print(trait_ref));
1074                         first = false;
1075                     }
1076                 }
1077                 if !is_sized {
1078                     p!(write("{}?Sized", if first { " " } else { "+" }));
1079                 } else if first {
1080                     p!(write(" Sized"));
1081                 }
1082             }
1083             ty::Str => p!(write("str")),
1084             ty::Generator(did, substs, movability) => {
1085                 let upvar_tys = substs.upvar_tys(did, self.tcx);
1086                 let witness = substs.witness(did, self.tcx);
1087                 if movability == hir::GeneratorMovability::Movable {
1088                     p!(write("[generator"));
1089                 } else {
1090                     p!(write("[static generator"));
1091                 }
1092
1093                 // FIXME(eddyb) should use `def_span`.
1094                 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1095                     p!(write("@{:?}", self.tcx.hir().span_by_hir_id(hir_id)));
1096                     let mut sep = " ";
1097                     for (freevar, upvar_ty) in self.tcx.freevars(did)
1098                         .as_ref()
1099                         .map_or(&[][..], |fv| &fv[..])
1100                         .iter()
1101                         .zip(upvar_tys)
1102                     {
1103                         p!(
1104                             write("{}{}:",
1105                                     sep,
1106                                     self.tcx.hir().name(freevar.var_id())),
1107                             print(upvar_ty));
1108                         sep = ", ";
1109                     }
1110                 } else {
1111                     // cross-crate closure types should only be
1112                     // visible in codegen bug reports, I imagine.
1113                     p!(write("@{:?}", did));
1114                     let mut sep = " ";
1115                     for (index, upvar_ty) in upvar_tys.enumerate() {
1116                         p!(
1117                                 write("{}{}:", sep, index),
1118                                 print(upvar_ty));
1119                         sep = ", ";
1120                     }
1121                 }
1122
1123                 p!(write(" "), print(witness), write("]"))
1124             },
1125             ty::GeneratorWitness(types) => {
1126                 nest!(|cx| cx.pretty_in_binder(&types))
1127             }
1128             ty::Closure(did, substs) => {
1129                 let upvar_tys = substs.upvar_tys(did, self.tcx);
1130                 p!(write("[closure"));
1131
1132                 // FIXME(eddyb) should use `def_span`.
1133                 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1134                     if self.tcx.sess.opts.debugging_opts.span_free_formats {
1135                         p!(write("@{:?}", hir_id));
1136                     } else {
1137                         p!(write("@{:?}", self.tcx.hir().span_by_hir_id(hir_id)));
1138                     }
1139                     let mut sep = " ";
1140                     for (freevar, upvar_ty) in self.tcx.freevars(did)
1141                         .as_ref()
1142                         .map_or(&[][..], |fv| &fv[..])
1143                         .iter()
1144                         .zip(upvar_tys)
1145                     {
1146                         p!(
1147                             write("{}{}:",
1148                                     sep,
1149                                     self.tcx.hir().name(freevar.var_id())),
1150                             print(upvar_ty));
1151                         sep = ", ";
1152                     }
1153                 } else {
1154                     // cross-crate closure types should only be
1155                     // visible in codegen bug reports, I imagine.
1156                     p!(write("@{:?}", did));
1157                     let mut sep = " ";
1158                     for (index, upvar_ty) in upvar_tys.enumerate() {
1159                         p!(
1160                                 write("{}{}:", sep, index),
1161                                 print(upvar_ty));
1162                         sep = ", ";
1163                     }
1164                 }
1165
1166                 if self.config.is_verbose {
1167                     p!(write(
1168                         " closure_kind_ty={:?} closure_sig_ty={:?}",
1169                         substs.closure_kind_ty(did, self.tcx),
1170                         substs.closure_sig_ty(did, self.tcx)
1171                     ));
1172                 }
1173
1174                 p!(write("]"))
1175             },
1176             ty::Array(ty, sz) => {
1177                 p!(write("["), print(ty), write("; "));
1178                 match sz {
1179                     ty::LazyConst::Unevaluated(_def_id, _substs) => {
1180                         p!(write("_"));
1181                     }
1182                     ty::LazyConst::Evaluated(c) => {
1183                         match c.val {
1184                             ConstValue::Infer(..) => p!(write("_")),
1185                             ConstValue::Param(ParamConst { name, .. }) =>
1186                                 p!(write("{}", name)),
1187                             _ => p!(write("{}", c.unwrap_usize(self.tcx))),
1188                         }
1189                     }
1190                 }
1191                 p!(write("]"))
1192             }
1193             ty::Slice(ty) => {
1194                 p!(write("["), print(ty), write("]"))
1195             }
1196         }
1197
1198         Ok(self.printer)
1199     }
1200
1201     pub fn pretty_fn_sig(
1202         mut self,
1203         inputs: &[Ty<'tcx>],
1204         c_variadic: bool,
1205         output: Ty<'tcx>,
1206     ) -> Result<P, fmt::Error> {
1207         define_scoped_cx!(self);
1208
1209         p!(write("("));
1210         let mut inputs = inputs.iter();
1211         if let Some(&ty) = inputs.next() {
1212             p!(print_display(ty));
1213             for &ty in inputs {
1214                 p!(write(", "), print_display(ty));
1215             }
1216             if c_variadic {
1217                 p!(write(", ..."));
1218             }
1219         }
1220         p!(write(")"));
1221         if !output.is_unit() {
1222             p!(write(" -> "), print_display(output));
1223         }
1224
1225         Ok(self.printer)
1226     }
1227
1228     pub fn pretty_in_binder<T>(mut self, value: &ty::Binder<T>) -> Result<P, fmt::Error>
1229         where T: Print<'tcx, P, Output = P, Error = fmt::Error> + TypeFoldable<'tcx>
1230     {
1231         fn name_by_region_index(index: usize) -> InternedString {
1232             match index {
1233                 0 => Symbol::intern("'r"),
1234                 1 => Symbol::intern("'s"),
1235                 i => Symbol::intern(&format!("'t{}", i-2)),
1236             }.as_interned_str()
1237         }
1238
1239         // Replace any anonymous late-bound regions with named
1240         // variants, using gensym'd identifiers, so that we can
1241         // clearly differentiate between named and unnamed regions in
1242         // the output. We'll probably want to tweak this over time to
1243         // decide just how much information to give.
1244         if self.config.binder_depth == 0 {
1245             self.prepare_late_bound_region_info(value);
1246         }
1247
1248         let mut empty = true;
1249         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1250             write!(cx.printer, "{}", if empty {
1251                 empty = false;
1252                 start
1253             } else {
1254                 cont
1255             })
1256         };
1257
1258         // NOTE(eddyb) this must be below `start_or_continue`'s definition
1259         // as that also has a `define_scoped_cx` and that kind of shadowing
1260         // is disallowed (name resolution thinks `scoped_cx!` is ambiguous).
1261         define_scoped_cx!(self);
1262
1263         let old_region_index = self.config.region_index;
1264         let mut region_index = old_region_index;
1265         let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1266             let _ = start_or_continue(&mut self, "for<", ", ");
1267             let br = match br {
1268                 ty::BrNamed(_, name) => {
1269                     let _ = write!(self.printer, "{}", name);
1270                     br
1271                 }
1272                 ty::BrAnon(_) |
1273                 ty::BrFresh(_) |
1274                 ty::BrEnv => {
1275                     let name = loop {
1276                         let name = name_by_region_index(region_index);
1277                         region_index += 1;
1278                         if !self.is_name_used(&name) {
1279                             break name;
1280                         }
1281                     };
1282                     let _ = write!(self.printer, "{}", name);
1283                     ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1284                 }
1285             };
1286             self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1287         }).0;
1288         start_or_continue(&mut self, "", "> ")?;
1289
1290         // Push current state to gcx, and restore after writing new_value.
1291         self.config.binder_depth += 1;
1292         self.config.region_index = region_index;
1293         let result = new_value.print_display(PrintCx {
1294             tcx: self.tcx,
1295             printer: self.printer,
1296             config: self.config,
1297         });
1298         self.config.region_index = old_region_index;
1299         self.config.binder_depth -= 1;
1300         result
1301     }
1302
1303     fn is_name_used(&self, name: &InternedString) -> bool {
1304         match self.config.used_region_names {
1305             Some(ref names) => names.contains(name),
1306             None => false,
1307         }
1308     }
1309 }