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};
12 use syntax::symbol::InternedString;
15 use std::fmt::{self, Write as _};
18 // `pretty` is a separate module only for organization.
23 scoped_cx!() = scoped_cx!().nest($closure)?
26 macro_rules! print_inner {
27 (write ($($data:expr),+)) => {
28 write!(scoped_cx!().printer, $($data),+)?
30 ($kind:ident ($data:expr)) => {
31 nest!(|cx| $data.$kind(cx))
35 ($($kind:ident $data:tt),+) => {
37 $(print_inner!($kind $data));+
41 macro_rules! define_scoped_cx {
43 #[allow(unused_macros)]
44 macro_rules! scoped_cx {
51 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
52 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
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();
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| {
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`".
85 /// Regions not selected by the region highlight mode are presently
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],
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.
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
100 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
103 impl RegionHighlightMode {
104 /// If `region` and `number` are both `Some`, invokes
105 /// `highlighting_region`.
106 pub fn maybe_highlighting_region(
108 region: Option<ty::Region<'_>>,
109 number: Option<usize>,
111 if let Some(k) = region {
112 if let Some(n) = number {
113 self.highlighting_region(k, n);
118 /// Highlights the region inference variable `vid` as `'N`.
119 pub fn highlighting_region(
121 region: ty::Region<'_>,
124 let num_slots = self.highlight_regions.len();
125 let first_avail_slot = self.highlight_regions.iter_mut()
126 .filter(|s| s.is_none())
130 "can only highlight {} placeholders at a time",
134 *first_avail_slot = Some((*region, number));
137 /// Convenience wrapper for `highlighting_region`.
138 pub fn highlighting_region_vid(
143 self.highlighting_region(&ty::ReVar(vid), number)
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> {
151 .filter_map(|h| match h {
152 Some((r, n)) if r == region => Some(*n),
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(
166 assert!(self.highlight_bound_region.is_none());
167 self.highlight_bound_region = Some((br, number));
171 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
172 pub trait PrettyPrinter:
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 {
189 printer: self.printer,
199 /// Like `print_def_path` but for value paths.
201 self: PrintCx<'_, '_, 'tcx, Self>,
203 substs: Option<SubstsRef<'tcx>>,
204 ) -> Result<Self::Path, Self::Error> {
205 self.print_def_path(def_id, substs, iter::empty())
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>;
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<'_>,
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.
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<'_>,
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,
249 DefPathData::MacroDef(..) => Namespace::MacroNS,
251 _ => Namespace::TypeNS,
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())
268 pub struct FmtPrinter<F: fmt::Write> {
272 pub region_highlight_mode: RegionHighlightMode,
275 impl<F: fmt::Write> FmtPrinter<F> {
276 pub fn new(fmt: F, ns: Namespace) -> Self {
280 in_value: ns == Namespace::ValueNS,
281 region_highlight_mode: RegionHighlightMode::default(),
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(
293 ) -> Result<(P, bool), P::Error> {
294 define_scoped_cx!(self);
296 debug!("try_print_visible_def_path: def_id={:?}", def_id);
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;
303 if cnum == LOCAL_CRATE {
304 return Ok((self.path_crate(cnum)?, true));
307 // In local mode, when we encounter a crate other than
308 // LOCAL_CRATE, execution proceeds in one of two ways:
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
317 match *self.tcx.extern_crate(def_id) {
319 src: ExternCrateSource::Extern(def_id),
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())?
328 self.path_crate(cnum)?
332 return Ok((self.path_crate(cnum)?, true));
338 if def_id.is_local() {
339 return Ok((self.printer, false));
342 let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
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);
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 {
351 index: cur_def_key.parent.expect("DefPathData::StructCtor missing a parent"),
354 cur_def_key = self.tcx.def_key(parent);
357 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
358 Some(parent) => parent,
359 None => return Ok((self.printer, false)),
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;
367 let (printer, success) = cx.try_print_visible_def_path(visible_parent)?;
368 prefix_success = success;
372 return Ok((self.printer, false));
374 let actual_parent = self.tcx.parent(def_id);
376 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
377 visible_parent, actual_parent,
380 let data = cur_def_key.disambiguated_data.data;
382 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
383 data, visible_parent, actual_parent,
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.
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).
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.
396 // In this case, the `visible_parent_map` will look something like this:
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`
403 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
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`.
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)
422 .find(|child| child.def.def_id() == def_id)
423 .map(|child| child.ident.as_str())
424 .unwrap_or_else(|| actual_name.as_str())
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()
432 Symbol::intern("<unnamed>").as_str()
437 debug!("try_print_visible_def_path: symbol={:?}", symbol);
438 Ok((self.path_append(|cx| Ok(cx.printer), &symbol)?, true))
441 pub fn pretty_path_qualified(
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.
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);
461 self.generic_delimiters(|mut cx| {
462 define_scoped_cx!(cx);
465 if let Some(trait_ref) = trait_ref {
466 p!(write(" as "), print(trait_ref));
472 pub fn pretty_path_append_impl(
474 print_prefix: impl FnOnce(
475 PrintCx<'_, 'gcx, 'tcx, P>,
476 ) -> Result<P::Path, P::Error>,
478 trait_ref: Option<ty::TraitRef<'tcx>>,
479 ) -> Result<P::Path, P::Error> {
480 self = self.nest(print_prefix)?;
482 self.generic_delimiters(|mut cx| {
483 define_scoped_cx!(cx);
486 if let Some(trait_ref) = trait_ref {
487 p!(print(trait_ref), write(" for "));
495 pub fn pretty_path_generic_args(
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)?;
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)
517 // Don't print args that are the defaults of their respective parameters.
518 let num_supplied_defaults = if self.tcx.sess.verbose() {
521 params.iter().rev().take_while(|param| {
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)
529 ty::GenericParamDefKind::Const => false, // FIXME(const_generics:defaults)
534 let params = ¶ms[..params.len() - num_supplied_defaults];
535 let mut args = params.iter().map(|param| {
536 substs[param.index as usize]
539 UnpackedKind::Lifetime(_) => print_regions,
543 let arg0 = args.next();
545 let mut projections = projections;
546 let projection0 = projections.next();
548 if arg0.is_none() && projection0.is_none() {
549 return Ok(self.printer);
552 self.generic_delimiters(|mut cx| {
553 define_scoped_cx!(cx);
555 let mut empty = true;
556 let mut maybe_comma = |cx: &mut Self| {
561 write!(cx.printer, ", ")
565 for arg in arg0.into_iter().chain(args) {
566 maybe_comma(&mut cx)?;
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.
584 for projection in projection0.into_iter().chain(projections) {
585 maybe_comma(&mut cx)?;
587 p!(write("{}=", cx.tcx.associated_item(projection.item_def_id).ident),
588 print(projection.ty));
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)
603 impl<F: fmt::Write> Printer for FmtPrinter<F> {
604 type Error = fmt::Error;
611 mut self: PrintCx<'_, '_, 'tcx, Self>,
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;
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)
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.
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());
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),
661 self.default_print_def_path(def_id, substs, projections)
665 self: PrintCx<'_, '_, '_, Self>,
666 region: ty::Region<'_>,
667 ) -> Result<Self::Region, Self::Error> {
668 self.pretty_print_region(region)
672 self: PrintCx<'_, '_, 'tcx, Self>,
674 ) -> Result<Self::Type, Self::Error> {
675 self.pretty_print_type(ty)
679 mut self: PrintCx<'_, '_, '_, Self>,
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())?;
691 write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
696 self: PrintCx<'_, '_, 'tcx, Self>,
698 trait_ref: Option<ty::TraitRef<'tcx>>,
699 ) -> Result<Self::Path, Self::Error> {
700 self.pretty_path_qualified(self_ty, trait_ref)
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>,
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)?;
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, "::")?;
721 }, self_ty, trait_ref)
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>,
729 ) -> Result<Self::Path, Self::Error> {
730 let mut printer = print_prefix(self)?;
732 // FIXME(eddyb) `text` should never be empty, but it
733 // currently is for `extern { ... }` "foreign modules".
734 if !text.is_empty() {
736 write!(printer, "::")?;
738 write!(printer, "{}", text)?;
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)
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 {
764 printer: self.printer,
767 printer.empty &= was_empty;
776 mut self: PrintCx<'_, '_, 'tcx, Self>,
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;
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, "::<")?;
794 write!(self.printer, "<")?;
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;
801 write!(printer, ">")?;
805 fn always_print_region_in_paths(
806 self: &PrintCx<'_, '_, '_, Self>,
807 region: ty::Region<'_>,
809 *region != ty::ReErased
812 fn print_region_outputs_anything(
813 self: &PrintCx<'_, '_, '_, Self>,
814 region: ty::Region<'_>,
816 let highlight = self.printer.region_highlight_mode;
817 if highlight.region_highlighted(region).is_some() {
821 if self.tcx.sess.verbose() {
825 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
828 ty::ReEarlyBound(ref data) => {
829 data.name != "" && data.name != "'_"
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 != "'_" {
841 if let Some((region, _)) = highlight.highlight_bound_region {
851 ty::ReVar(_) if identify_regions => true,
855 ty::ReErased => false,
859 ty::ReClosureBound(_) => true,
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);
872 // Watch out for region highlights.
873 let highlight = self.printer.region_highlight_mode;
874 if let Some(n) = highlight.region_highlighted(region) {
876 return Ok(self.printer);
879 if self.tcx.sess.verbose() {
880 p!(write("{:?}", region));
881 return Ok(self.printer);
884 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
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()`.
891 ty::ReEarlyBound(ref data) => {
892 if data.name != "'_" {
893 p!(write("{}", data.name));
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);
906 if let Some((region, counter)) = highlight.highlight_bound_region {
908 p!(write("'{}", counter));
912 ty::ReScope(scope) if identify_regions => {
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(
924 scope.item_local_id().as_usize(),
925 first_statement_index.index()
929 ty::ReVar(region_vid) if identify_regions => {
930 p!(write("{:?}", region_vid));
935 ty::ReStatic => p!(write("'static")),
936 ty::ReEmpty => p!(write("'<empty>")),
938 // The user should never encounter these in unsubstituted form.
939 ty::ReClosureBound(vid) => p!(write("{:?}", vid)),
946 impl<'gcx, 'tcx, P: PrettyPrinter> PrintCx<'_, 'gcx, 'tcx, P> {
947 pub fn pretty_print_type(
950 ) -> Result<P::Type, P::Error> {
951 define_scoped_cx!(self);
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",
966 ty::Ref(r, ty, mutbl) => {
968 if self.print_region_outputs_anything(r) {
969 p!(print(r), write(" "));
971 p!(print(ty::TypeAndMut { ty, mutbl }))
973 ty::Never => p!(write("!")),
974 ty::Tuple(ref tys) => {
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));
982 p!(write(", "), print(ty));
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)));
994 ty::FnPtr(ref bare_fn) => {
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()))
1006 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
1010 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
1013 ty::Adt(def, substs) => {
1014 nest!(|cx| cx.print_def_path(def.did, Some(substs), iter::empty()));
1016 ty::Dynamic(data, r) => {
1017 let print_r = self.print_region_outputs_anything(r);
1021 p!(write("dyn "), print(data));
1023 p!(write(" + "), print(r), write(")"));
1026 ty::Foreign(def_id) => {
1027 nest!(|cx| cx.print_def_path(def_id, None, iter::empty()));
1029 ty::Projection(ref data) => p!(print(data)),
1030 ty::UnnormalizedProjection(ref data) => {
1031 p!(write("Unnormalized("), print(data), write(")"))
1033 ty::Placeholder(placeholder) => {
1034 p!(write("Placeholder({:?})", placeholder))
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);
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() {
1051 for subst in substs {
1052 p!(write(", "), print(subst));
1056 return Ok(self.printer);
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);
1062 let mut first = true;
1063 let mut is_sized = false;
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() {
1074 write("{}", if first { " " } else { "+" }),
1080 p!(write("{}?Sized", if first { " " } else { "+" }));
1082 p!(write(" Sized"));
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"));
1092 p!(write("[static generator"));
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)));
1099 for (freevar, upvar_ty) in self.tcx.freevars(did)
1101 .map_or(&[][..], |fv| &fv[..])
1108 self.tcx.hir().name(freevar.var_id())),
1113 // cross-crate closure types should only be
1114 // visible in codegen bug reports, I imagine.
1115 p!(write("@{:?}", did));
1117 for (index, upvar_ty) in upvar_tys.enumerate() {
1119 write("{}{}:", sep, index),
1125 p!(write(" "), print(witness), write("]"))
1127 ty::GeneratorWitness(types) => {
1128 nest!(|cx| cx.pretty_in_binder(&types))
1130 ty::Closure(did, substs) => {
1131 let upvar_tys = substs.upvar_tys(did, self.tcx);
1132 p!(write("[closure"));
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));
1139 p!(write("@{:?}", self.tcx.hir().span_by_hir_id(hir_id)));
1142 for (freevar, upvar_ty) in self.tcx.freevars(did)
1144 .map_or(&[][..], |fv| &fv[..])
1151 self.tcx.hir().name(freevar.var_id())),
1156 // cross-crate closure types should only be
1157 // visible in codegen bug reports, I imagine.
1158 p!(write("@{:?}", did));
1160 for (index, upvar_ty) in upvar_tys.enumerate() {
1162 write("{}{}:", sep, index),
1168 if self.tcx.sess.verbose() {
1170 " closure_kind_ty={:?} closure_sig_ty={:?}",
1171 substs.closure_kind_ty(did, self.tcx),
1172 substs.closure_sig_ty(did, self.tcx)
1178 ty::Array(ty, sz) => {
1179 p!(write("["), print(ty), write("; "));
1181 ty::LazyConst::Unevaluated(_def_id, _substs) => {
1184 ty::LazyConst::Evaluated(c) => {
1186 ConstValue::Infer(..) => p!(write("_")),
1187 ConstValue::Param(ParamConst { name, .. }) =>
1188 p!(write("{}", name)),
1189 _ => p!(write("{}", c.unwrap_usize(self.tcx))),
1196 p!(write("["), print(ty), write("]"))
1203 pub fn pretty_fn_sig(
1205 inputs: &[Ty<'tcx>],
1208 ) -> Result<P, fmt::Error> {
1209 define_scoped_cx!(self);
1212 let mut inputs = inputs.iter();
1213 if let Some(&ty) = inputs.next() {
1216 p!(write(", "), print(ty));
1223 if !output.is_unit() {
1224 p!(write(" -> "), print(output));
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>
1233 fn name_by_region_index(index: usize) -> InternedString {
1235 0 => Symbol::intern("'r"),
1236 1 => Symbol::intern("'s"),
1237 i => Symbol::intern(&format!("'t{}", i-2)),
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);
1250 let mut empty = true;
1251 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1252 write!(cx.printer, "{}", if empty {
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);
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<", ", ");
1270 ty::BrNamed(_, name) => {
1271 let _ = write!(self.printer, "{}", name);
1278 let name = name_by_region_index(region_index);
1280 if !self.is_name_used(&name) {
1284 let _ = write!(self.printer, "{}", name);
1285 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1288 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1290 start_or_continue(&mut self, "", "> ")?;
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 {
1297 printer: self.printer,
1298 config: self.config,
1300 self.config.region_index = old_region_index;
1301 self.config.binder_depth -= 1;
1305 fn is_name_used(&self, name: &InternedString) -> bool {
1306 match self.config.used_region_names {
1307 Some(ref names) => names.contains(name),