2 use crate::hir::def::Namespace;
3 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
6 use crate::middle::region;
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
8 use crate::ty::subst::{Kind, Subst, UnpackedKind};
9 use crate::mir::interpret::ConstValue;
10 use syntax::symbol::{keywords, Symbol};
12 use rustc_target::spec::abi::Abi;
13 use syntax::symbol::InternedString;
16 use std::fmt::{self, Write as _};
17 use std::ops::{Deref, DerefMut};
19 // `pretty` is a separate module only for organization.
23 (@write($($data:expr),+)) => {
24 write!(scoped_cx!(), $($data),+)?
26 (@print($x:expr)) => {
27 scoped_cx!() = $x.print(scoped_cx!())?
29 (@$method:ident($($arg:expr),*)) => {
30 scoped_cx!() = scoped_cx!().$method($($arg),*)?
32 ($($kind:ident $data:tt),+) => {{
36 macro_rules! define_scoped_cx {
38 #[allow(unused_macros)]
39 macro_rules! scoped_cx {
46 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
47 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
50 /// Force us to name impls with just the filename/line number. We
51 /// normally try to use types. But at some points, notably while printing
52 /// cycle errors, this can result in extra or suboptimal error output,
53 /// so this variable disables that check.
54 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
55 FORCE_IMPL_FILENAME_LINE.with(|force| {
56 let old = force.get();
64 /// Adds the `crate::` prefix to paths where appropriate.
65 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
66 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
75 /// The "region highlights" are used to control region printing during
76 /// specific error messages. When a "region highlight" is enabled, it
77 /// gives an alternate way to print specific regions. For now, we
78 /// always print those regions using a number, so something like "`'0`".
80 /// Regions not selected by the region highlight mode are presently
82 #[derive(Copy, Clone, Default)]
83 pub struct RegionHighlightMode {
84 /// If enabled, when we see the selected region, use "`'N`"
85 /// instead of the ordinary behavior.
86 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
88 /// If enabled, when printing a "free region" that originated from
89 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
90 /// have names print as normal.
92 /// This is used when you have a signature like `fn foo(x: &u32,
93 /// y: &'a u32)` and we want to give a name to the region of the
95 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
98 impl RegionHighlightMode {
99 /// If `region` and `number` are both `Some`, invokes
100 /// `highlighting_region`.
101 pub fn maybe_highlighting_region(
103 region: Option<ty::Region<'_>>,
104 number: Option<usize>,
106 if let Some(k) = region {
107 if let Some(n) = number {
108 self.highlighting_region(k, n);
113 /// Highlights the region inference variable `vid` as `'N`.
114 pub fn highlighting_region(
116 region: ty::Region<'_>,
119 let num_slots = self.highlight_regions.len();
120 let first_avail_slot = self.highlight_regions.iter_mut()
121 .filter(|s| s.is_none())
125 "can only highlight {} placeholders at a time",
129 *first_avail_slot = Some((*region, number));
132 /// Convenience wrapper for `highlighting_region`.
133 pub fn highlighting_region_vid(
138 self.highlighting_region(&ty::ReVar(vid), number)
141 /// Returns `Some(n)` with the number to use for the given region, if any.
142 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
146 .filter_map(|h| match h {
147 Some((r, n)) if r == region => Some(*n),
153 /// Highlight the given bound region.
154 /// We can only highlight one bound region at a time. See
155 /// the field `highlight_bound_region` for more detailed notes.
156 pub fn highlighting_bound_region(
161 assert!(self.highlight_bound_region.is_none());
162 self.highlight_bound_region = Some((br, number));
166 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
167 pub trait PrettyPrinter<'gcx: 'tcx, 'tcx>:
173 DynExistential = Self,
177 /// Like `print_def_path` but for value paths.
181 substs: &'tcx [Kind<'tcx>],
182 ) -> Result<Self::Path, Self::Error> {
183 self.print_def_path(def_id, substs)
188 value: &ty::Binder<T>,
189 ) -> Result<Self, Self::Error>
190 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
192 value.skip_binder().print(self)
195 /// Print comma-separated elements.
198 mut elems: impl Iterator<Item = T>,
199 ) -> Result<Self, Self::Error>
200 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error>
202 if let Some(first) = elems.next() {
203 self = first.print(self)?;
205 self.write_str(", ")?;
206 self = elem.print(self)?;
212 /// Print `<...>` around what `f` prints.
213 fn generic_delimiters(
215 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
216 ) -> Result<Self, Self::Error>;
218 /// Return `true` if the region should be printed in
219 /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
220 /// This is typically the case for all non-`'_` regions.
221 fn region_should_not_be_omitted(
223 region: ty::Region<'_>,
226 // Defaults (should not be overriden):
228 /// If possible, this returns a global path resolving to `def_id` that is visible
229 /// from at least one local module and returns true. If the crate defining `def_id` is
230 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
231 fn try_print_visible_def_path(
234 ) -> Result<(Self, bool), Self::Error> {
235 define_scoped_cx!(self);
237 debug!("try_print_visible_def_path: def_id={:?}", def_id);
239 // If `def_id` is a direct or injected extern crate, return the
240 // path to the crate followed by the path to the item within the crate.
241 if def_id.index == CRATE_DEF_INDEX {
242 let cnum = def_id.krate;
244 if cnum == LOCAL_CRATE {
245 return Ok((self.path_crate(cnum)?, true));
248 // In local mode, when we encounter a crate other than
249 // LOCAL_CRATE, execution proceeds in one of two ways:
251 // 1. for a direct dependency, where user added an
252 // `extern crate` manually, we put the `extern
253 // crate` as the parent. So you wind up with
254 // something relative to the current crate.
255 // 2. for an extern inferred from a path or an indirect crate,
256 // where there is no explicit `extern crate`, we just prepend
258 match *self.tcx().extern_crate(def_id) {
260 src: ExternCrateSource::Extern(def_id),
265 debug!("try_print_visible_def_path: def_id={:?}", def_id);
266 return Ok((if !span.is_dummy() {
267 self.print_def_path(def_id, &[])?
269 self.path_crate(cnum)?
273 return Ok((self.path_crate(cnum)?, true));
279 if def_id.is_local() {
280 return Ok((self, false));
283 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
285 let mut cur_def_key = self.tcx().def_key(def_id);
286 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
288 // For a constructor we want the name of its parent rather than <unnamed>.
289 match cur_def_key.disambiguated_data.data {
290 DefPathData::Ctor => {
293 index: cur_def_key.parent
294 .expect("DefPathData::Ctor/VariantData missing a parent"),
297 cur_def_key = self.tcx().def_key(parent);
302 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
303 Some(parent) => parent,
304 None => return Ok((self, false)),
306 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
307 // knowing ahead of time whether the entire path will succeed or not.
308 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
309 // linked list on the stack would need to be built, before any printing.
310 match self.try_print_visible_def_path(visible_parent)? {
311 (cx, false) => return Ok((cx, false)),
312 (cx, true) => self = cx,
314 let actual_parent = self.tcx().parent(def_id);
316 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
317 visible_parent, actual_parent,
320 let mut data = cur_def_key.disambiguated_data.data;
322 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
323 data, visible_parent, actual_parent,
327 // In order to output a path that could actually be imported (valid and visible),
328 // we need to handle re-exports correctly.
330 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
331 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
333 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
334 // private so the "true" path to `CommandExt` isn't accessible.
336 // In this case, the `visible_parent_map` will look something like this:
338 // (child) -> (parent)
339 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
340 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
341 // `std::sys::unix::ext` -> `std::os`
343 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
346 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
347 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
348 // to the parent - resulting in a mangled path like
349 // `std::os::ext::process::CommandExt`.
351 // Instead, we must detect that there was a re-export and instead print `unix`
352 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
353 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
354 // the visible parent (`std::os`). If these do not match, then we iterate over
355 // the children of the visible parent (as was done when computing
356 // `visible_parent_map`), looking for the specific child we currently have and then
357 // have access to the re-exported name.
358 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
359 let reexport = self.tcx().item_children(visible_parent)
361 .find(|child| child.res.def_id() == def_id)
362 .map(|child| child.ident.as_interned_str());
363 if let Some(reexport) = reexport {
367 // Re-exported `extern crate` (#43189).
368 DefPathData::CrateRoot => {
369 data = DefPathData::TypeNs(
370 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
375 debug!("try_print_visible_def_path: data={:?}", data);
377 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
383 fn pretty_path_qualified(
386 trait_ref: Option<ty::TraitRef<'tcx>>,
387 ) -> Result<Self::Path, Self::Error> {
388 if trait_ref.is_none() {
389 // Inherent impls. Try to print `Foo::bar` for an inherent
390 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
391 // anything other than a simple path.
393 ty::Adt(..) | ty::Foreign(_) |
394 ty::Bool | ty::Char | ty::Str |
395 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
396 return self_ty.print(self);
403 self.generic_delimiters(|mut cx| {
404 define_scoped_cx!(cx);
407 if let Some(trait_ref) = trait_ref {
408 p!(write(" as "), print(trait_ref));
414 fn pretty_path_append_impl(
416 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
418 trait_ref: Option<ty::TraitRef<'tcx>>,
419 ) -> Result<Self::Path, Self::Error> {
420 self = print_prefix(self)?;
422 self.generic_delimiters(|mut cx| {
423 define_scoped_cx!(cx);
426 if let Some(trait_ref) = trait_ref {
427 p!(print(trait_ref), write(" for "));
435 fn pretty_print_type(
438 ) -> Result<Self::Type, Self::Error> {
439 define_scoped_cx!(self);
442 ty::Bool => p!(write("bool")),
443 ty::Char => p!(write("char")),
444 ty::Int(t) => p!(write("{}", t.ty_to_string())),
445 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
446 ty::Float(t) => p!(write("{}", t.ty_to_string())),
447 ty::RawPtr(ref tm) => {
448 p!(write("*{} ", match tm.mutbl {
449 hir::MutMutable => "mut",
450 hir::MutImmutable => "const",
454 ty::Ref(r, ty, mutbl) => {
456 if self.region_should_not_be_omitted(r) {
457 p!(print(r), write(" "));
459 p!(print(ty::TypeAndMut { ty, mutbl }))
461 ty::Never => p!(write("!")),
462 ty::Tuple(ref tys) => {
464 let mut tys = tys.iter();
465 if let Some(&ty) = tys.next() {
466 p!(print(ty), write(","));
467 if let Some(&ty) = tys.next() {
468 p!(write(" "), print(ty));
470 p!(write(", "), print(ty));
476 ty::FnDef(def_id, substs) => {
477 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
478 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
480 ty::FnPtr(ref bare_fn) => {
483 ty::Infer(infer_ty) => p!(write("{}", infer_ty)),
484 ty::Error => p!(write("[type error]")),
485 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
486 ty::Bound(debruijn, bound_ty) => {
487 match bound_ty.kind {
488 ty::BoundTyKind::Anon => {
489 if debruijn == ty::INNERMOST {
490 p!(write("^{}", bound_ty.var.index()))
492 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
496 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
499 ty::Adt(def, substs) => {
500 p!(print_def_path(def.did, substs));
502 ty::Dynamic(data, r) => {
503 let print_r = self.region_should_not_be_omitted(r);
507 p!(write("dyn "), print(data));
509 p!(write(" + "), print(r), write(")"));
512 ty::Foreign(def_id) => {
513 p!(print_def_path(def_id, &[]));
515 ty::Projection(ref data) => p!(print(data)),
516 ty::UnnormalizedProjection(ref data) => {
517 p!(write("Unnormalized("), print(data), write(")"))
519 ty::Placeholder(placeholder) => {
520 p!(write("Placeholder({:?})", placeholder))
522 ty::Opaque(def_id, substs) => {
523 // FIXME(eddyb) print this with `print_def_path`.
524 if self.tcx().sess.verbose() {
525 p!(write("Opaque({:?}, {:?})", def_id, substs));
529 let def_key = self.tcx().def_key(def_id);
530 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
531 p!(write("{}", name));
532 let mut substs = substs.iter();
533 // FIXME(eddyb) print this with `print_def_path`.
534 if let Some(first) = substs.next() {
537 for subst in substs {
538 p!(write(", "), print(subst));
544 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
545 // by looking up the projections associated with the def_id.
546 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
548 let mut first = true;
549 let mut is_sized = false;
551 for predicate in bounds.predicates {
552 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
553 // Don't print +Sized, but rather +?Sized if absent.
554 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
560 write("{}", if first { " " } else { "+" }),
566 p!(write("{}?Sized", if first { " " } else { "+" }));
571 ty::Str => p!(write("str")),
572 ty::Generator(did, substs, movability) => {
573 let upvar_tys = substs.upvar_tys(did, self.tcx());
574 let witness = substs.witness(did, self.tcx());
575 if movability == hir::GeneratorMovability::Movable {
576 p!(write("[generator"));
578 p!(write("[static generator"));
581 // FIXME(eddyb) should use `def_span`.
582 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
583 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
585 for (upvar, upvar_ty) in self.tcx().upvars(did)
587 .map_or(&[][..], |v| &v[..])
594 self.tcx().hir().name_by_hir_id(upvar.var_id())),
599 // cross-crate closure types should only be
600 // visible in codegen bug reports, I imagine.
601 p!(write("@{:?}", did));
603 for (index, upvar_ty) in upvar_tys.enumerate() {
605 write("{}{}:", sep, index),
611 p!(write(" "), print(witness), write("]"))
613 ty::GeneratorWitness(types) => {
614 p!(in_binder(&types));
616 ty::Closure(did, substs) => {
617 let upvar_tys = substs.upvar_tys(did, self.tcx());
618 p!(write("[closure"));
620 // FIXME(eddyb) should use `def_span`.
621 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
622 if self.tcx().sess.opts.debugging_opts.span_free_formats {
623 p!(write("@{:?}", hir_id));
625 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
628 for (upvar, upvar_ty) in self.tcx().upvars(did)
630 .map_or(&[][..], |v| &v[..])
637 self.tcx().hir().name_by_hir_id(upvar.var_id())),
642 // cross-crate closure types should only be
643 // visible in codegen bug reports, I imagine.
644 p!(write("@{:?}", did));
646 for (index, upvar_ty) in upvar_tys.enumerate() {
648 write("{}{}:", sep, index),
654 if self.tcx().sess.verbose() {
656 " closure_kind_ty={:?} closure_sig_ty={:?}",
657 substs.closure_kind_ty(did, self.tcx()),
658 substs.closure_sig_ty(did, self.tcx())
664 ty::Array(ty, sz) => {
665 p!(write("["), print(ty), write("; "));
667 ConstValue::Unevaluated(..) |
668 ConstValue::Infer(..) => p!(write("_")),
669 ConstValue::Param(ParamConst { name, .. }) =>
670 p!(write("{}", name)),
671 _ => p!(write("{}", sz.unwrap_usize(self.tcx()))),
676 p!(write("["), print(ty), write("]"))
683 fn pretty_print_dyn_existential(
685 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
686 ) -> Result<Self::DynExistential, Self::Error> {
687 define_scoped_cx!(self);
689 // Generate the main trait ref, including associated types.
690 let mut first = true;
692 if let Some(principal) = predicates.principal() {
693 p!(print_def_path(principal.def_id, &[]));
695 let mut resugared = false;
697 // Special-case `Fn(...) -> ...` and resugar it.
698 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
699 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
700 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
701 let mut projections = predicates.projection_bounds();
702 if let (Some(proj), None) = (projections.next(), projections.next()) {
703 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
704 p!(pretty_fn_sig(&tys, false, proj.ty));
710 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
711 // in order to place the projections inside the `<...>`.
713 // Use a type that can't appear in defaults of type parameters.
714 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
715 let principal = principal.with_self_ty(self.tcx(), dummy_self);
717 let args = self.generic_args_to_print(
718 self.tcx().generics_of(principal.def_id),
722 // Don't print `'_` if there's no unerased regions.
723 let print_regions = args.iter().any(|arg| {
725 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
729 let mut args = args.iter().cloned().filter(|arg| {
731 UnpackedKind::Lifetime(_) => print_regions,
735 let mut projections = predicates.projection_bounds();
737 let arg0 = args.next();
738 let projection0 = projections.next();
739 if arg0.is_some() || projection0.is_some() {
740 let args = arg0.into_iter().chain(args);
741 let projections = projection0.into_iter().chain(projections);
743 p!(generic_delimiters(|mut cx| {
744 cx = cx.comma_sep(args)?;
745 if arg0.is_some() && projection0.is_some() {
748 cx.comma_sep(projections)
756 // FIXME(eddyb) avoid printing twice (needed to ensure
757 // that the auto traits are sorted *and* printed via cx).
758 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
759 (self.tcx().def_path_str(did), did)
762 // The auto traits come ordered by `DefPathHash`. While
763 // `DefPathHash` is *stable* in the sense that it depends on
764 // neither the host nor the phase of the moon, it depends
765 // "pseudorandomly" on the compiler version and the target.
767 // To avoid that causing instabilities in compiletest
768 // output, sort the auto-traits alphabetically.
771 for (_, def_id) in auto_traits {
777 p!(print_def_path(def_id, &[]));
788 ) -> Result<Self, Self::Error> {
789 define_scoped_cx!(self);
792 let mut inputs = inputs.iter();
793 if let Some(&ty) = inputs.next() {
796 p!(write(", "), print(ty));
803 if !output.is_unit() {
804 p!(write(" -> "), print(output));
811 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
812 pub struct FmtPrinter<'a, 'gcx, 'tcx, F>(Box<FmtPrinterData<'a, 'gcx, 'tcx, F>>);
814 pub struct FmtPrinterData<'a, 'gcx, 'tcx, F> {
815 tcx: TyCtxt<'a, 'gcx, 'tcx>,
821 used_region_names: FxHashSet<InternedString>,
825 pub region_highlight_mode: RegionHighlightMode,
828 impl<F> Deref for FmtPrinter<'a, 'gcx, 'tcx, F> {
829 type Target = FmtPrinterData<'a, 'gcx, 'tcx, F>;
830 fn deref(&self) -> &Self::Target {
835 impl<F> DerefMut for FmtPrinter<'_, '_, '_, F> {
836 fn deref_mut(&mut self) -> &mut Self::Target {
841 impl<F> FmtPrinter<'a, 'gcx, 'tcx, F> {
842 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, fmt: F, ns: Namespace) -> Self {
843 FmtPrinter(Box::new(FmtPrinterData {
847 in_value: ns == Namespace::ValueNS,
848 used_region_names: Default::default(),
851 region_highlight_mode: RegionHighlightMode::default(),
856 impl TyCtxt<'_, '_, '_> {
857 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
858 // (but also some things just print a `DefId` generally so maybe we need this?)
859 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
860 match self.def_key(def_id).disambiguated_data.data {
861 DefPathData::TypeNs(..)
862 | DefPathData::CrateRoot
863 | DefPathData::ImplTrait => Namespace::TypeNS,
865 DefPathData::ValueNs(..)
866 | DefPathData::AnonConst
867 | DefPathData::ClosureExpr
868 | DefPathData::Ctor => Namespace::ValueNS,
870 DefPathData::MacroNs(..) => Namespace::MacroNS,
872 _ => Namespace::TypeNS,
876 /// Returns a string identifying this `DefId`. This string is
877 /// suitable for user output.
878 pub fn def_path_str(self, def_id: DefId) -> String {
879 let ns = self.guess_def_namespace(def_id);
880 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
881 let mut s = String::new();
882 let _ = FmtPrinter::new(self, &mut s, ns)
883 .print_def_path(def_id, &[]);
888 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, '_, F> {
889 fn write_str(&mut self, s: &str) -> fmt::Result {
890 self.fmt.write_str(s)
894 impl<F: fmt::Write> Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
895 type Error = fmt::Error;
900 type DynExistential = Self;
902 fn tcx(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
909 substs: &'tcx [Kind<'tcx>],
910 ) -> Result<Self::Path, Self::Error> {
911 define_scoped_cx!(self);
913 if substs.is_empty() {
914 match self.try_print_visible_def_path(def_id)? {
915 (cx, true) => return Ok(cx),
916 (cx, false) => self = cx,
920 let key = self.tcx.def_key(def_id);
921 if let DefPathData::Impl = key.disambiguated_data.data {
922 // Always use types for non-local impls, where types are always
923 // available, and filename/line-number is mostly uninteresting.
925 !def_id.is_local() || {
926 // Otherwise, use filename/line-number if forced.
927 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
932 // If no type info is available, fall back to
933 // pretty printing some span information. This should
934 // only occur very early in the compiler pipeline.
935 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
936 let span = self.tcx.def_span(def_id);
938 self = self.print_def_path(parent_def_id, &[])?;
940 // HACK(eddyb) copy of `path_append` to avoid
941 // constructing a `DisambiguatedDefPathData`.
942 if !self.empty_path {
945 write!(self, "<impl at {:?}>", span)?;
946 self.empty_path = false;
952 self.default_print_def_path(def_id, substs)
957 region: ty::Region<'_>,
958 ) -> Result<Self::Region, Self::Error> {
959 self.pretty_print_region(region)
965 ) -> Result<Self::Type, Self::Error> {
966 self.pretty_print_type(ty)
969 fn print_dyn_existential(
971 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
972 ) -> Result<Self::DynExistential, Self::Error> {
973 self.pretty_print_dyn_existential(predicates)
979 ) -> Result<Self::Path, Self::Error> {
980 self.empty_path = true;
981 if cnum == LOCAL_CRATE {
982 if self.tcx.sess.rust_2018() {
983 // We add the `crate::` keyword on Rust 2018, only when desired.
984 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
985 write!(self, "{}", keywords::Crate.name())?;
986 self.empty_path = false;
990 write!(self, "{}", self.tcx.crate_name(cnum))?;
991 self.empty_path = false;
998 trait_ref: Option<ty::TraitRef<'tcx>>,
999 ) -> Result<Self::Path, Self::Error> {
1000 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1001 self.empty_path = false;
1005 fn path_append_impl(
1007 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1008 _disambiguated_data: &DisambiguatedDefPathData,
1010 trait_ref: Option<ty::TraitRef<'tcx>>,
1011 ) -> Result<Self::Path, Self::Error> {
1012 self = self.pretty_path_append_impl(|mut cx| {
1013 cx = print_prefix(cx)?;
1019 }, self_ty, trait_ref)?;
1020 self.empty_path = false;
1025 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1026 disambiguated_data: &DisambiguatedDefPathData,
1027 ) -> Result<Self::Path, Self::Error> {
1028 self = print_prefix(self)?;
1030 // Skip `::{{constructor}}` on tuple/unit structs.
1031 match disambiguated_data.data {
1032 DefPathData::Ctor => return Ok(self),
1036 // FIXME(eddyb) `name` should never be empty, but it
1037 // currently is for `extern { ... }` "foreign modules".
1038 let name = disambiguated_data.data.as_interned_str().as_str();
1039 if !name.is_empty() {
1040 if !self.empty_path {
1041 write!(self, "::")?;
1043 write!(self, "{}", name)?;
1045 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1046 // might be nicer to use something else, e.g. `{closure#3}`.
1047 let dis = disambiguated_data.disambiguator;
1049 disambiguated_data.data.get_opt_name().is_none() ||
1050 dis != 0 && self.tcx.sess.verbose();
1052 write!(self, "#{}", dis)?;
1055 self.empty_path = false;
1060 fn path_generic_args(
1062 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1063 args: &[Kind<'tcx>],
1064 ) -> Result<Self::Path, Self::Error> {
1065 self = print_prefix(self)?;
1067 // Don't print `'_` if there's no unerased regions.
1068 let print_regions = args.iter().any(|arg| {
1069 match arg.unpack() {
1070 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1074 let args = args.iter().cloned().filter(|arg| {
1075 match arg.unpack() {
1076 UnpackedKind::Lifetime(_) => print_regions,
1081 if args.clone().next().is_some() {
1083 write!(self, "::")?;
1085 self.generic_delimiters(|cx| cx.comma_sep(args))
1092 impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1093 fn print_value_path(
1096 substs: &'tcx [Kind<'tcx>],
1097 ) -> Result<Self::Path, Self::Error> {
1098 let was_in_value = std::mem::replace(&mut self.in_value, true);
1099 self = self.print_def_path(def_id, substs)?;
1100 self.in_value = was_in_value;
1107 value: &ty::Binder<T>,
1108 ) -> Result<Self, Self::Error>
1109 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
1111 self.pretty_in_binder(value)
1114 fn generic_delimiters(
1116 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1117 ) -> Result<Self, Self::Error> {
1120 let was_in_value = std::mem::replace(&mut self.in_value, false);
1121 let mut inner = f(self)?;
1122 inner.in_value = was_in_value;
1124 write!(inner, ">")?;
1128 fn region_should_not_be_omitted(
1130 region: ty::Region<'_>,
1132 let highlight = self.region_highlight_mode;
1133 if highlight.region_highlighted(region).is_some() {
1137 if self.tcx.sess.verbose() {
1141 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1144 ty::ReEarlyBound(ref data) => {
1145 data.name != "" && data.name != "'_"
1148 ty::ReLateBound(_, br) |
1149 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1150 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1151 if let ty::BrNamed(_, name) = br {
1152 if name != "" && name != "'_" {
1157 if let Some((region, _)) = highlight.highlight_bound_region {
1167 ty::ReVar(_) if identify_regions => true,
1171 ty::ReErased => false,
1175 ty::ReClosureBound(_) => true,
1180 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1181 impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
1182 pub fn pretty_print_region(
1184 region: ty::Region<'_>,
1185 ) -> Result<Self, fmt::Error> {
1186 define_scoped_cx!(self);
1188 // Watch out for region highlights.
1189 let highlight = self.region_highlight_mode;
1190 if let Some(n) = highlight.region_highlighted(region) {
1191 p!(write("'{}", n));
1195 if self.tcx.sess.verbose() {
1196 p!(write("{:?}", region));
1200 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1202 // These printouts are concise. They do not contain all the information
1203 // the user might want to diagnose an error, but there is basically no way
1204 // to fit that into a short string. Hence the recommendation to use
1205 // `explain_region()` or `note_and_explain_region()`.
1207 ty::ReEarlyBound(ref data) => {
1208 if data.name != "" {
1209 p!(write("{}", data.name));
1213 ty::ReLateBound(_, br) |
1214 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1215 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1216 if let ty::BrNamed(_, name) = br {
1217 if name != "" && name != "'_" {
1218 p!(write("{}", name));
1223 if let Some((region, counter)) = highlight.highlight_bound_region {
1225 p!(write("'{}", counter));
1230 ty::ReScope(scope) if identify_regions => {
1232 region::ScopeData::Node =>
1233 p!(write("'{}s", scope.item_local_id().as_usize())),
1234 region::ScopeData::CallSite =>
1235 p!(write("'{}cs", scope.item_local_id().as_usize())),
1236 region::ScopeData::Arguments =>
1237 p!(write("'{}as", scope.item_local_id().as_usize())),
1238 region::ScopeData::Destruction =>
1239 p!(write("'{}ds", scope.item_local_id().as_usize())),
1240 region::ScopeData::Remainder(first_statement_index) => p!(write(
1242 scope.item_local_id().as_usize(),
1243 first_statement_index.index()
1248 ty::ReVar(region_vid) if identify_regions => {
1249 p!(write("{:?}", region_vid));
1256 p!(write("'static"));
1260 p!(write("'<empty>"));
1264 // The user should never encounter these in unsubstituted form.
1265 ty::ReClosureBound(vid) => {
1266 p!(write("{:?}", vid));
1277 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1278 // `region_index` and `used_region_names`.
1279 impl<F: fmt::Write> FmtPrinter<'_, 'gcx, 'tcx, F> {
1280 pub fn pretty_in_binder<T>(
1282 value: &ty::Binder<T>,
1283 ) -> Result<Self, fmt::Error>
1284 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>
1286 fn name_by_region_index(index: usize) -> InternedString {
1288 0 => Symbol::intern("'r"),
1289 1 => Symbol::intern("'s"),
1290 i => Symbol::intern(&format!("'t{}", i-2)),
1294 // Replace any anonymous late-bound regions with named
1295 // variants, using gensym'd identifiers, so that we can
1296 // clearly differentiate between named and unnamed regions in
1297 // the output. We'll probably want to tweak this over time to
1298 // decide just how much information to give.
1299 if self.binder_depth == 0 {
1300 self.prepare_late_bound_region_info(value);
1303 let mut empty = true;
1304 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1305 write!(cx, "{}", if empty {
1313 define_scoped_cx!(self);
1315 let old_region_index = self.region_index;
1316 let mut region_index = old_region_index;
1317 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1318 let _ = start_or_continue(&mut self, "for<", ", ");
1320 ty::BrNamed(_, name) => {
1321 let _ = write!(self, "{}", name);
1328 let name = name_by_region_index(region_index);
1330 if !self.used_region_names.contains(&name) {
1334 let _ = write!(self, "{}", name);
1335 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1338 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1340 start_or_continue(&mut self, "", "> ")?;
1342 self.binder_depth += 1;
1343 self.region_index = region_index;
1344 let mut inner = new_value.print(self)?;
1345 inner.region_index = old_region_index;
1346 inner.binder_depth -= 1;
1350 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1351 where T: TypeFoldable<'tcx>
1354 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1355 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1356 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1358 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1359 self.0.insert(name);
1363 r.super_visit_with(self)
1367 self.used_region_names.clear();
1368 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1369 value.visit_with(&mut collector);
1370 self.region_index = 0;
1374 impl<'gcx: 'tcx, 'tcx, T, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1376 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>
1379 type Error = P::Error;
1380 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1385 impl<'gcx: 'tcx, 'tcx, T, U, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1386 for ty::OutlivesPredicate<T, U>
1387 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1388 U: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1391 type Error = P::Error;
1392 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1393 define_scoped_cx!(cx);
1394 p!(print(self.0), write(" : "), print(self.1));
1399 macro_rules! forward_display_to_print {
1401 $(impl fmt::Display for $ty {
1402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1403 ty::tls::with(|tcx| {
1405 .expect("could not lift for printing")
1406 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1414 macro_rules! define_print_and_forward_display {
1415 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1416 $(impl<'gcx: 'tcx, 'tcx, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P> for $ty {
1418 type Error = fmt::Error;
1419 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1420 #[allow(unused_mut)]
1422 define_scoped_cx!($cx);
1424 #[allow(unreachable_code)]
1429 forward_display_to_print!($($ty),+);
1433 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1434 impl fmt::Display for ty::RegionKind {
1435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436 ty::tls::with(|tcx| {
1437 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1443 forward_display_to_print! {
1445 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1447 // HACK(eddyb) these are exhaustive instead of generic,
1448 // because `for<'gcx: 'tcx, 'tcx>` isn't possible yet.
1449 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1450 ty::Binder<ty::TraitRef<'tcx>>,
1451 ty::Binder<ty::FnSig<'tcx>>,
1452 ty::Binder<ty::TraitPredicate<'tcx>>,
1453 ty::Binder<ty::SubtypePredicate<'tcx>>,
1454 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1455 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1456 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1458 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1459 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1462 define_print_and_forward_display! {
1465 &'tcx ty::List<Ty<'tcx>> {
1467 let mut tys = self.iter();
1468 if let Some(&ty) = tys.next() {
1471 p!(write(", "), print(ty));
1477 ty::TypeAndMut<'tcx> {
1478 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1482 ty::ExistentialTraitRef<'tcx> {
1483 // Use a type that can't appear in defaults of type parameters.
1484 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1485 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1486 p!(print(trait_ref))
1489 ty::ExistentialProjection<'tcx> {
1490 let name = cx.tcx().associated_item(self.item_def_id).ident;
1491 p!(write("{} = ", name), print(self.ty))
1494 ty::ExistentialPredicate<'tcx> {
1496 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1497 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1498 ty::ExistentialPredicate::AutoTrait(def_id) => {
1499 p!(print_def_path(def_id, &[]));
1505 if self.unsafety == hir::Unsafety::Unsafe {
1506 p!(write("unsafe "));
1509 if self.abi != Abi::Rust {
1510 p!(write("extern {} ", self.abi));
1513 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1517 if cx.tcx().sess.verbose() {
1518 p!(write("{:?}", self));
1522 ty::TyVar(_) => p!(write("_")),
1523 ty::IntVar(_) => p!(write("{}", "{integer}")),
1524 ty::FloatVar(_) => p!(write("{}", "{float}")),
1525 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1526 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1527 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1531 ty::TraitRef<'tcx> {
1532 p!(print_def_path(self.def_id, self.substs));
1535 &'tcx ty::Const<'tcx> {
1537 ConstValue::Unevaluated(..) |
1538 ConstValue::Infer(..) => p!(write("_")),
1539 ConstValue::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1540 _ => p!(write("{:?}", self)),
1545 p!(write("{}", self.name))
1549 p!(write("{}", self.name))
1552 ty::SubtypePredicate<'tcx> {
1553 p!(print(self.a), write(" <: "), print(self.b))
1556 ty::TraitPredicate<'tcx> {
1557 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1560 ty::ProjectionPredicate<'tcx> {
1561 p!(print(self.projection_ty), write(" == "), print(self.ty))
1564 ty::ProjectionTy<'tcx> {
1565 p!(print_def_path(self.item_def_id, self.substs));
1570 ty::ClosureKind::Fn => p!(write("Fn")),
1571 ty::ClosureKind::FnMut => p!(write("FnMut")),
1572 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1576 ty::Predicate<'tcx> {
1578 ty::Predicate::Trait(ref data) => p!(print(data)),
1579 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1580 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1581 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1582 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1583 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1584 ty::Predicate::ObjectSafe(trait_def_id) => {
1585 p!(write("the trait `"),
1586 print_def_path(trait_def_id, &[]),
1587 write("` is object-safe"))
1589 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1590 p!(write("the closure `"),
1591 print_value_path(closure_def_id, &[]),
1592 write("` implements the trait `{}`", kind))
1594 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1595 p!(write("the constant `"),
1596 print_value_path(def_id, substs),
1597 write("` can be evaluated"))
1603 match self.unpack() {
1604 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1605 UnpackedKind::Type(ty) => p!(print(ty)),
1606 UnpackedKind::Const(ct) => p!(print(ct)),