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 rustc_target::spec::abi::Abi;
11 use syntax::symbol::{keywords, InternedString};
14 use std::fmt::{self, Write as _};
15 use std::ops::{Deref, DerefMut};
17 // `pretty` is a separate module only for organization.
21 (@write($($data:expr),+)) => {
22 write!(scoped_cx!(), $($data),+)?
24 (@print($x:expr)) => {
25 scoped_cx!() = $x.print(scoped_cx!())?
27 (@$method:ident($($arg:expr),*)) => {
28 scoped_cx!() = scoped_cx!().$method($($arg),*)?
30 ($($kind:ident $data:tt),+) => {{
34 macro_rules! define_scoped_cx {
36 #[allow(unused_macros)]
37 macro_rules! scoped_cx {
44 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
45 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
48 /// Force us to name impls with just the filename/line number. We
49 /// normally try to use types. But at some points, notably while printing
50 /// cycle errors, this can result in extra or suboptimal error output,
51 /// so this variable disables that check.
52 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
53 FORCE_IMPL_FILENAME_LINE.with(|force| {
54 let old = force.get();
62 /// Adds the `crate::` prefix to paths where appropriate.
63 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
64 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
73 /// The "region highlights" are used to control region printing during
74 /// specific error messages. When a "region highlight" is enabled, it
75 /// gives an alternate way to print specific regions. For now, we
76 /// always print those regions using a number, so something like "`'0`".
78 /// Regions not selected by the region highlight mode are presently
80 #[derive(Copy, Clone, Default)]
81 pub struct RegionHighlightMode {
82 /// If enabled, when we see the selected region, use "`'N`"
83 /// instead of the ordinary behavior.
84 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
86 /// If enabled, when printing a "free region" that originated from
87 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
88 /// have names print as normal.
90 /// This is used when you have a signature like `fn foo(x: &u32,
91 /// y: &'a u32)` and we want to give a name to the region of the
93 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
96 impl RegionHighlightMode {
97 /// If `region` and `number` are both `Some`, invokes
98 /// `highlighting_region`.
99 pub fn maybe_highlighting_region(
101 region: Option<ty::Region<'_>>,
102 number: Option<usize>,
104 if let Some(k) = region {
105 if let Some(n) = number {
106 self.highlighting_region(k, n);
111 /// Highlights the region inference variable `vid` as `'N`.
112 pub fn highlighting_region(
114 region: ty::Region<'_>,
117 let num_slots = self.highlight_regions.len();
118 let first_avail_slot = self.highlight_regions.iter_mut()
119 .filter(|s| s.is_none())
123 "can only highlight {} placeholders at a time",
127 *first_avail_slot = Some((*region, number));
130 /// Convenience wrapper for `highlighting_region`.
131 pub fn highlighting_region_vid(
136 self.highlighting_region(&ty::ReVar(vid), number)
139 /// Returns `Some(n)` with the number to use for the given region, if any.
140 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
144 .filter_map(|h| match h {
145 Some((r, n)) if r == region => Some(*n),
151 /// Highlight the given bound region.
152 /// We can only highlight one bound region at a time. See
153 /// the field `highlight_bound_region` for more detailed notes.
154 pub fn highlighting_bound_region(
159 assert!(self.highlight_bound_region.is_none());
160 self.highlight_bound_region = Some((br, number));
164 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
165 pub trait PrettyPrinter<'gcx: 'tcx, 'tcx>:
171 DynExistential = Self,
175 /// Like `print_def_path` but for value paths.
179 substs: &'tcx [Kind<'tcx>],
180 ) -> Result<Self::Path, Self::Error> {
181 self.print_def_path(def_id, substs)
186 value: &ty::Binder<T>,
187 ) -> Result<Self, Self::Error>
188 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
190 value.skip_binder().print(self)
193 /// Print comma-separated elements.
196 mut elems: impl Iterator<Item = T>,
197 ) -> Result<Self, Self::Error>
198 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error>
200 if let Some(first) = elems.next() {
201 self = first.print(self)?;
203 self.write_str(", ")?;
204 self = elem.print(self)?;
210 /// Print `<...>` around what `f` prints.
211 fn generic_delimiters(
213 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
214 ) -> Result<Self, Self::Error>;
216 /// Return `true` if the region should be printed in
217 /// optional positions, e.g. `&'a T` or `dyn Tr + 'b`.
218 /// This is typically the case for all non-`'_` regions.
219 fn region_should_not_be_omitted(
221 region: ty::Region<'_>,
224 // Defaults (should not be overriden):
226 /// If possible, this returns a global path resolving to `def_id` that is visible
227 /// from at least one local module and returns true. If the crate defining `def_id` is
228 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
229 fn try_print_visible_def_path(
232 ) -> Result<(Self, bool), Self::Error> {
233 define_scoped_cx!(self);
235 debug!("try_print_visible_def_path: def_id={:?}", def_id);
237 // If `def_id` is a direct or injected extern crate, return the
238 // path to the crate followed by the path to the item within the crate.
239 if def_id.index == CRATE_DEF_INDEX {
240 let cnum = def_id.krate;
242 if cnum == LOCAL_CRATE {
243 return Ok((self.path_crate(cnum)?, true));
246 // In local mode, when we encounter a crate other than
247 // LOCAL_CRATE, execution proceeds in one of two ways:
249 // 1. for a direct dependency, where user added an
250 // `extern crate` manually, we put the `extern
251 // crate` as the parent. So you wind up with
252 // something relative to the current crate.
253 // 2. for an extern inferred from a path or an indirect crate,
254 // where there is no explicit `extern crate`, we just prepend
256 match *self.tcx().extern_crate(def_id) {
258 src: ExternCrateSource::Extern(def_id),
263 debug!("try_print_visible_def_path: def_id={:?}", def_id);
264 return Ok((if !span.is_dummy() {
265 self.print_def_path(def_id, &[])?
267 self.path_crate(cnum)?
271 return Ok((self.path_crate(cnum)?, true));
277 if def_id.is_local() {
278 return Ok((self, false));
281 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
283 let mut cur_def_key = self.tcx().def_key(def_id);
284 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
286 // For a constructor we want the name of its parent rather than <unnamed>.
287 match cur_def_key.disambiguated_data.data {
288 DefPathData::Ctor => {
291 index: cur_def_key.parent
292 .expect("DefPathData::Ctor/VariantData missing a parent"),
295 cur_def_key = self.tcx().def_key(parent);
300 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
301 Some(parent) => parent,
302 None => return Ok((self, false)),
304 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
305 // knowing ahead of time whether the entire path will succeed or not.
306 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
307 // linked list on the stack would need to be built, before any printing.
308 match self.try_print_visible_def_path(visible_parent)? {
309 (cx, false) => return Ok((cx, false)),
310 (cx, true) => self = cx,
312 let actual_parent = self.tcx().parent(def_id);
314 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
315 visible_parent, actual_parent,
318 let mut data = cur_def_key.disambiguated_data.data;
320 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
321 data, visible_parent, actual_parent,
325 // In order to output a path that could actually be imported (valid and visible),
326 // we need to handle re-exports correctly.
328 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
329 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
331 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
332 // private so the "true" path to `CommandExt` isn't accessible.
334 // In this case, the `visible_parent_map` will look something like this:
336 // (child) -> (parent)
337 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
338 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
339 // `std::sys::unix::ext` -> `std::os`
341 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
344 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
345 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
346 // to the parent - resulting in a mangled path like
347 // `std::os::ext::process::CommandExt`.
349 // Instead, we must detect that there was a re-export and instead print `unix`
350 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
351 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
352 // the visible parent (`std::os`). If these do not match, then we iterate over
353 // the children of the visible parent (as was done when computing
354 // `visible_parent_map`), looking for the specific child we currently have and then
355 // have access to the re-exported name.
356 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
357 let reexport = self.tcx().item_children(visible_parent)
359 .find(|child| child.res.def_id() == def_id)
360 .map(|child| child.ident.as_interned_str());
361 if let Some(reexport) = reexport {
365 // Re-exported `extern crate` (#43189).
366 DefPathData::CrateRoot => {
367 data = DefPathData::TypeNs(
368 self.tcx().original_crate_name(def_id.krate).as_interned_str(),
373 debug!("try_print_visible_def_path: data={:?}", data);
375 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
381 fn pretty_path_qualified(
384 trait_ref: Option<ty::TraitRef<'tcx>>,
385 ) -> Result<Self::Path, Self::Error> {
386 if trait_ref.is_none() {
387 // Inherent impls. Try to print `Foo::bar` for an inherent
388 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
389 // anything other than a simple path.
391 ty::Adt(..) | ty::Foreign(_) |
392 ty::Bool | ty::Char | ty::Str |
393 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
394 return self_ty.print(self);
401 self.generic_delimiters(|mut cx| {
402 define_scoped_cx!(cx);
405 if let Some(trait_ref) = trait_ref {
406 p!(write(" as "), print(trait_ref));
412 fn pretty_path_append_impl(
414 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
416 trait_ref: Option<ty::TraitRef<'tcx>>,
417 ) -> Result<Self::Path, Self::Error> {
418 self = print_prefix(self)?;
420 self.generic_delimiters(|mut cx| {
421 define_scoped_cx!(cx);
424 if let Some(trait_ref) = trait_ref {
425 p!(print(trait_ref), write(" for "));
433 fn pretty_print_type(
436 ) -> Result<Self::Type, Self::Error> {
437 define_scoped_cx!(self);
440 ty::Bool => p!(write("bool")),
441 ty::Char => p!(write("char")),
442 ty::Int(t) => p!(write("{}", t.ty_to_string())),
443 ty::Uint(t) => p!(write("{}", t.ty_to_string())),
444 ty::Float(t) => p!(write("{}", t.ty_to_string())),
445 ty::RawPtr(ref tm) => {
446 p!(write("*{} ", match tm.mutbl {
447 hir::MutMutable => "mut",
448 hir::MutImmutable => "const",
452 ty::Ref(r, ty, mutbl) => {
454 if self.region_should_not_be_omitted(r) {
455 p!(print(r), write(" "));
457 p!(print(ty::TypeAndMut { ty, mutbl }))
459 ty::Never => p!(write("!")),
460 ty::Tuple(ref tys) => {
462 let mut tys = tys.iter();
463 if let Some(&ty) = tys.next() {
464 p!(print(ty), write(","));
465 if let Some(&ty) = tys.next() {
466 p!(write(" "), print(ty));
468 p!(write(", "), print(ty));
474 ty::FnDef(def_id, substs) => {
475 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
476 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
478 ty::FnPtr(ref bare_fn) => {
481 ty::Infer(infer_ty) => p!(write("{}", infer_ty)),
482 ty::Error => p!(write("[type error]")),
483 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
484 ty::Bound(debruijn, bound_ty) => {
485 match bound_ty.kind {
486 ty::BoundTyKind::Anon => {
487 if debruijn == ty::INNERMOST {
488 p!(write("^{}", bound_ty.var.index()))
490 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
494 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
497 ty::Adt(def, substs) => {
498 p!(print_def_path(def.did, substs));
500 ty::Dynamic(data, r) => {
501 let print_r = self.region_should_not_be_omitted(r);
505 p!(write("dyn "), print(data));
507 p!(write(" + "), print(r), write(")"));
510 ty::Foreign(def_id) => {
511 p!(print_def_path(def_id, &[]));
513 ty::Projection(ref data) => p!(print(data)),
514 ty::UnnormalizedProjection(ref data) => {
515 p!(write("Unnormalized("), print(data), write(")"))
517 ty::Placeholder(placeholder) => {
518 p!(write("Placeholder({:?})", placeholder))
520 ty::Opaque(def_id, substs) => {
521 // FIXME(eddyb) print this with `print_def_path`.
522 if self.tcx().sess.verbose() {
523 p!(write("Opaque({:?}, {:?})", def_id, substs));
527 let def_key = self.tcx().def_key(def_id);
528 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
529 p!(write("{}", name));
530 let mut substs = substs.iter();
531 // FIXME(eddyb) print this with `print_def_path`.
532 if let Some(first) = substs.next() {
535 for subst in substs {
536 p!(write(", "), print(subst));
542 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
543 // by looking up the projections associated with the def_id.
544 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
546 let mut first = true;
547 let mut is_sized = false;
549 for predicate in bounds.predicates {
550 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
551 // Don't print +Sized, but rather +?Sized if absent.
552 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
558 write("{}", if first { " " } else { "+" }),
564 p!(write("{}?Sized", if first { " " } else { "+" }));
569 ty::Str => p!(write("str")),
570 ty::Generator(did, substs, movability) => {
571 let upvar_tys = substs.upvar_tys(did, self.tcx());
572 let witness = substs.witness(did, self.tcx());
573 if movability == hir::GeneratorMovability::Movable {
574 p!(write("[generator"));
576 p!(write("[static generator"));
579 // FIXME(eddyb) should use `def_span`.
580 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
581 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
583 for (upvar, upvar_ty) in self.tcx().upvars(did)
585 .map_or(&[][..], |v| &v[..])
592 self.tcx().hir().name_by_hir_id(upvar.var_id())),
597 // cross-crate closure types should only be
598 // visible in codegen bug reports, I imagine.
599 p!(write("@{:?}", did));
601 for (index, upvar_ty) in upvar_tys.enumerate() {
603 write("{}{}:", sep, index),
609 p!(write(" "), print(witness), write("]"))
611 ty::GeneratorWitness(types) => {
612 p!(in_binder(&types));
614 ty::Closure(did, substs) => {
615 let upvar_tys = substs.upvar_tys(did, self.tcx());
616 p!(write("[closure"));
618 // FIXME(eddyb) should use `def_span`.
619 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
620 if self.tcx().sess.opts.debugging_opts.span_free_formats {
621 p!(write("@{:?}", hir_id));
623 p!(write("@{:?}", self.tcx().hir().span_by_hir_id(hir_id)));
626 for (upvar, upvar_ty) in self.tcx().upvars(did)
628 .map_or(&[][..], |v| &v[..])
635 self.tcx().hir().name_by_hir_id(upvar.var_id())),
640 // cross-crate closure types should only be
641 // visible in codegen bug reports, I imagine.
642 p!(write("@{:?}", did));
644 for (index, upvar_ty) in upvar_tys.enumerate() {
646 write("{}{}:", sep, index),
652 if self.tcx().sess.verbose() {
654 " closure_kind_ty={:?} closure_sig_ty={:?}",
655 substs.closure_kind_ty(did, self.tcx()),
656 substs.closure_sig_ty(did, self.tcx())
662 ty::Array(ty, sz) => {
663 p!(write("["), print(ty), write("; "));
665 ConstValue::Unevaluated(..) |
666 ConstValue::Infer(..) => p!(write("_")),
667 ConstValue::Param(ParamConst { name, .. }) =>
668 p!(write("{}", name)),
669 _ => p!(write("{}", sz.unwrap_usize(self.tcx()))),
674 p!(write("["), print(ty), write("]"))
681 fn pretty_print_dyn_existential(
683 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
684 ) -> Result<Self::DynExistential, Self::Error> {
685 define_scoped_cx!(self);
687 // Generate the main trait ref, including associated types.
688 let mut first = true;
690 if let Some(principal) = predicates.principal() {
691 p!(print_def_path(principal.def_id, &[]));
693 let mut resugared = false;
695 // Special-case `Fn(...) -> ...` and resugar it.
696 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
697 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
698 if let ty::Tuple(ref args) = principal.substs.type_at(0).sty {
699 let mut projections = predicates.projection_bounds();
700 if let (Some(proj), None) = (projections.next(), projections.next()) {
701 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
702 p!(pretty_fn_sig(&tys, false, proj.ty));
708 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
709 // in order to place the projections inside the `<...>`.
711 // Use a type that can't appear in defaults of type parameters.
712 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
713 let principal = principal.with_self_ty(self.tcx(), dummy_self);
715 let args = self.generic_args_to_print(
716 self.tcx().generics_of(principal.def_id),
720 // Don't print `'_` if there's no unerased regions.
721 let print_regions = args.iter().any(|arg| {
723 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
727 let mut args = args.iter().cloned().filter(|arg| {
729 UnpackedKind::Lifetime(_) => print_regions,
733 let mut projections = predicates.projection_bounds();
735 let arg0 = args.next();
736 let projection0 = projections.next();
737 if arg0.is_some() || projection0.is_some() {
738 let args = arg0.into_iter().chain(args);
739 let projections = projection0.into_iter().chain(projections);
741 p!(generic_delimiters(|mut cx| {
742 cx = cx.comma_sep(args)?;
743 if arg0.is_some() && projection0.is_some() {
746 cx.comma_sep(projections)
754 // FIXME(eddyb) avoid printing twice (needed to ensure
755 // that the auto traits are sorted *and* printed via cx).
756 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
757 (self.tcx().def_path_str(did), did)
760 // The auto traits come ordered by `DefPathHash`. While
761 // `DefPathHash` is *stable* in the sense that it depends on
762 // neither the host nor the phase of the moon, it depends
763 // "pseudorandomly" on the compiler version and the target.
765 // To avoid that causing instabilities in compiletest
766 // output, sort the auto-traits alphabetically.
769 for (_, def_id) in auto_traits {
775 p!(print_def_path(def_id, &[]));
786 ) -> Result<Self, Self::Error> {
787 define_scoped_cx!(self);
790 let mut inputs = inputs.iter();
791 if let Some(&ty) = inputs.next() {
794 p!(write(", "), print(ty));
801 if !output.is_unit() {
802 p!(write(" -> "), print(output));
809 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
810 pub struct FmtPrinter<'a, 'gcx, 'tcx, F>(Box<FmtPrinterData<'a, 'gcx, 'tcx, F>>);
812 pub struct FmtPrinterData<'a, 'gcx, 'tcx, F> {
813 tcx: TyCtxt<'a, 'gcx, 'tcx>,
819 used_region_names: FxHashSet<InternedString>,
823 pub region_highlight_mode: RegionHighlightMode,
826 impl<F> Deref for FmtPrinter<'a, 'gcx, 'tcx, F> {
827 type Target = FmtPrinterData<'a, 'gcx, 'tcx, F>;
828 fn deref(&self) -> &Self::Target {
833 impl<F> DerefMut for FmtPrinter<'_, '_, '_, F> {
834 fn deref_mut(&mut self) -> &mut Self::Target {
839 impl<F> FmtPrinter<'a, 'gcx, 'tcx, F> {
840 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, fmt: F, ns: Namespace) -> Self {
841 FmtPrinter(Box::new(FmtPrinterData {
845 in_value: ns == Namespace::ValueNS,
846 used_region_names: Default::default(),
849 region_highlight_mode: RegionHighlightMode::default(),
854 impl TyCtxt<'_, '_, '_> {
855 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
856 // (but also some things just print a `DefId` generally so maybe we need this?)
857 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
858 match self.def_key(def_id).disambiguated_data.data {
859 DefPathData::TypeNs(..)
860 | DefPathData::CrateRoot
861 | DefPathData::ImplTrait => Namespace::TypeNS,
863 DefPathData::ValueNs(..)
864 | DefPathData::AnonConst
865 | DefPathData::ClosureExpr
866 | DefPathData::Ctor => Namespace::ValueNS,
868 DefPathData::MacroNs(..) => Namespace::MacroNS,
870 _ => Namespace::TypeNS,
874 /// Returns a string identifying this `DefId`. This string is
875 /// suitable for user output.
876 pub fn def_path_str(self, def_id: DefId) -> String {
877 let ns = self.guess_def_namespace(def_id);
878 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
879 let mut s = String::new();
880 let _ = FmtPrinter::new(self, &mut s, ns)
881 .print_def_path(def_id, &[]);
886 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, '_, F> {
887 fn write_str(&mut self, s: &str) -> fmt::Result {
888 self.fmt.write_str(s)
892 impl<F: fmt::Write> Printer<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
893 type Error = fmt::Error;
898 type DynExistential = Self;
900 fn tcx(&'a self) -> TyCtxt<'a, 'gcx, 'tcx> {
907 substs: &'tcx [Kind<'tcx>],
908 ) -> Result<Self::Path, Self::Error> {
909 define_scoped_cx!(self);
911 if substs.is_empty() {
912 match self.try_print_visible_def_path(def_id)? {
913 (cx, true) => return Ok(cx),
914 (cx, false) => self = cx,
918 let key = self.tcx.def_key(def_id);
919 if let DefPathData::Impl = key.disambiguated_data.data {
920 // Always use types for non-local impls, where types are always
921 // available, and filename/line-number is mostly uninteresting.
923 !def_id.is_local() || {
924 // Otherwise, use filename/line-number if forced.
925 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
930 // If no type info is available, fall back to
931 // pretty printing some span information. This should
932 // only occur very early in the compiler pipeline.
933 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
934 let span = self.tcx.def_span(def_id);
936 self = self.print_def_path(parent_def_id, &[])?;
938 // HACK(eddyb) copy of `path_append` to avoid
939 // constructing a `DisambiguatedDefPathData`.
940 if !self.empty_path {
943 write!(self, "<impl at {:?}>", span)?;
944 self.empty_path = false;
950 self.default_print_def_path(def_id, substs)
955 region: ty::Region<'_>,
956 ) -> Result<Self::Region, Self::Error> {
957 self.pretty_print_region(region)
963 ) -> Result<Self::Type, Self::Error> {
964 self.pretty_print_type(ty)
967 fn print_dyn_existential(
969 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
970 ) -> Result<Self::DynExistential, Self::Error> {
971 self.pretty_print_dyn_existential(predicates)
977 ) -> Result<Self::Path, Self::Error> {
978 self.empty_path = true;
979 if cnum == LOCAL_CRATE {
980 if self.tcx.sess.rust_2018() {
981 // We add the `crate::` keyword on Rust 2018, only when desired.
982 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
983 write!(self, "{}", keywords::Crate.name())?;
984 self.empty_path = false;
988 write!(self, "{}", self.tcx.crate_name(cnum))?;
989 self.empty_path = false;
996 trait_ref: Option<ty::TraitRef<'tcx>>,
997 ) -> Result<Self::Path, Self::Error> {
998 self = self.pretty_path_qualified(self_ty, trait_ref)?;
999 self.empty_path = false;
1003 fn path_append_impl(
1005 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1006 _disambiguated_data: &DisambiguatedDefPathData,
1008 trait_ref: Option<ty::TraitRef<'tcx>>,
1009 ) -> Result<Self::Path, Self::Error> {
1010 self = self.pretty_path_append_impl(|mut cx| {
1011 cx = print_prefix(cx)?;
1017 }, self_ty, trait_ref)?;
1018 self.empty_path = false;
1023 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1024 disambiguated_data: &DisambiguatedDefPathData,
1025 ) -> Result<Self::Path, Self::Error> {
1026 self = print_prefix(self)?;
1028 // Skip `::{{constructor}}` on tuple/unit structs.
1029 match disambiguated_data.data {
1030 DefPathData::Ctor => return Ok(self),
1034 // FIXME(eddyb) `name` should never be empty, but it
1035 // currently is for `extern { ... }` "foreign modules".
1036 let name = disambiguated_data.data.as_interned_str().as_str();
1037 if !name.is_empty() {
1038 if !self.empty_path {
1039 write!(self, "::")?;
1041 write!(self, "{}", name)?;
1043 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1044 // might be nicer to use something else, e.g. `{closure#3}`.
1045 let dis = disambiguated_data.disambiguator;
1047 disambiguated_data.data.get_opt_name().is_none() ||
1048 dis != 0 && self.tcx.sess.verbose();
1050 write!(self, "#{}", dis)?;
1053 self.empty_path = false;
1058 fn path_generic_args(
1060 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1061 args: &[Kind<'tcx>],
1062 ) -> Result<Self::Path, Self::Error> {
1063 self = print_prefix(self)?;
1065 // Don't print `'_` if there's no unerased regions.
1066 let print_regions = args.iter().any(|arg| {
1067 match arg.unpack() {
1068 UnpackedKind::Lifetime(r) => *r != ty::ReErased,
1072 let args = args.iter().cloned().filter(|arg| {
1073 match arg.unpack() {
1074 UnpackedKind::Lifetime(_) => print_regions,
1079 if args.clone().next().is_some() {
1081 write!(self, "::")?;
1083 self.generic_delimiters(|cx| cx.comma_sep(args))
1090 impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F> {
1091 fn print_value_path(
1094 substs: &'tcx [Kind<'tcx>],
1095 ) -> Result<Self::Path, Self::Error> {
1096 let was_in_value = std::mem::replace(&mut self.in_value, true);
1097 self = self.print_def_path(def_id, substs)?;
1098 self.in_value = was_in_value;
1105 value: &ty::Binder<T>,
1106 ) -> Result<Self, Self::Error>
1107 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>
1109 self.pretty_in_binder(value)
1112 fn generic_delimiters(
1114 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1115 ) -> Result<Self, Self::Error> {
1118 let was_in_value = std::mem::replace(&mut self.in_value, false);
1119 let mut inner = f(self)?;
1120 inner.in_value = was_in_value;
1122 write!(inner, ">")?;
1126 fn region_should_not_be_omitted(
1128 region: ty::Region<'_>,
1130 let highlight = self.region_highlight_mode;
1131 if highlight.region_highlighted(region).is_some() {
1135 if self.tcx.sess.verbose() {
1139 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1142 ty::ReEarlyBound(ref data) => {
1143 data.name != "" && data.name != "'_"
1146 ty::ReLateBound(_, br) |
1147 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1148 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1149 if let ty::BrNamed(_, name) = br {
1150 if name != "" && name != "'_" {
1155 if let Some((region, _)) = highlight.highlight_bound_region {
1165 ty::ReVar(_) if identify_regions => true,
1169 ty::ReErased => false,
1173 ty::ReClosureBound(_) => true,
1178 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1179 impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
1180 pub fn pretty_print_region(
1182 region: ty::Region<'_>,
1183 ) -> Result<Self, fmt::Error> {
1184 define_scoped_cx!(self);
1186 // Watch out for region highlights.
1187 let highlight = self.region_highlight_mode;
1188 if let Some(n) = highlight.region_highlighted(region) {
1189 p!(write("'{}", n));
1193 if self.tcx.sess.verbose() {
1194 p!(write("{:?}", region));
1198 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1200 // These printouts are concise. They do not contain all the information
1201 // the user might want to diagnose an error, but there is basically no way
1202 // to fit that into a short string. Hence the recommendation to use
1203 // `explain_region()` or `note_and_explain_region()`.
1205 ty::ReEarlyBound(ref data) => {
1206 if data.name != "" {
1207 p!(write("{}", data.name));
1211 ty::ReLateBound(_, br) |
1212 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1213 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1214 if let ty::BrNamed(_, name) = br {
1215 if name != "" && name != "'_" {
1216 p!(write("{}", name));
1221 if let Some((region, counter)) = highlight.highlight_bound_region {
1223 p!(write("'{}", counter));
1228 ty::ReScope(scope) if identify_regions => {
1230 region::ScopeData::Node =>
1231 p!(write("'{}s", scope.item_local_id().as_usize())),
1232 region::ScopeData::CallSite =>
1233 p!(write("'{}cs", scope.item_local_id().as_usize())),
1234 region::ScopeData::Arguments =>
1235 p!(write("'{}as", scope.item_local_id().as_usize())),
1236 region::ScopeData::Destruction =>
1237 p!(write("'{}ds", scope.item_local_id().as_usize())),
1238 region::ScopeData::Remainder(first_statement_index) => p!(write(
1240 scope.item_local_id().as_usize(),
1241 first_statement_index.index()
1246 ty::ReVar(region_vid) if identify_regions => {
1247 p!(write("{:?}", region_vid));
1254 p!(write("'static"));
1258 p!(write("'<empty>"));
1262 // The user should never encounter these in unsubstituted form.
1263 ty::ReClosureBound(vid) => {
1264 p!(write("{:?}", vid));
1275 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1276 // `region_index` and `used_region_names`.
1277 impl<F: fmt::Write> FmtPrinter<'_, 'gcx, 'tcx, F> {
1278 pub fn pretty_in_binder<T>(
1280 value: &ty::Binder<T>,
1281 ) -> Result<Self, fmt::Error>
1282 where T: Print<'gcx, 'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>
1284 fn name_by_region_index(index: usize) -> InternedString {
1286 0 => InternedString::intern("'r"),
1287 1 => InternedString::intern("'s"),
1288 i => InternedString::intern(&format!("'t{}", i-2)),
1292 // Replace any anonymous late-bound regions with named
1293 // variants, using gensym'd identifiers, so that we can
1294 // clearly differentiate between named and unnamed regions in
1295 // the output. We'll probably want to tweak this over time to
1296 // decide just how much information to give.
1297 if self.binder_depth == 0 {
1298 self.prepare_late_bound_region_info(value);
1301 let mut empty = true;
1302 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1303 write!(cx, "{}", if empty {
1311 define_scoped_cx!(self);
1313 let old_region_index = self.region_index;
1314 let mut region_index = old_region_index;
1315 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1316 let _ = start_or_continue(&mut self, "for<", ", ");
1318 ty::BrNamed(_, name) => {
1319 let _ = write!(self, "{}", name);
1326 let name = name_by_region_index(region_index);
1328 if !self.used_region_names.contains(&name) {
1332 let _ = write!(self, "{}", name);
1333 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1336 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1338 start_or_continue(&mut self, "", "> ")?;
1340 self.binder_depth += 1;
1341 self.region_index = region_index;
1342 let mut inner = new_value.print(self)?;
1343 inner.region_index = old_region_index;
1344 inner.binder_depth -= 1;
1348 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1349 where T: TypeFoldable<'tcx>
1352 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<InternedString>);
1353 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1354 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1356 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1357 self.0.insert(name);
1361 r.super_visit_with(self)
1365 self.used_region_names.clear();
1366 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1367 value.visit_with(&mut collector);
1368 self.region_index = 0;
1372 impl<'gcx: 'tcx, 'tcx, T, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1374 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>
1377 type Error = P::Error;
1378 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1383 impl<'gcx: 'tcx, 'tcx, T, U, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P>
1384 for ty::OutlivesPredicate<T, U>
1385 where T: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1386 U: Print<'gcx, 'tcx, P, Output = P, Error = P::Error>,
1389 type Error = P::Error;
1390 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1391 define_scoped_cx!(cx);
1392 p!(print(self.0), write(" : "), print(self.1));
1397 macro_rules! forward_display_to_print {
1399 $(impl fmt::Display for $ty {
1400 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1401 ty::tls::with(|tcx| {
1403 .expect("could not lift for printing")
1404 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1412 macro_rules! define_print_and_forward_display {
1413 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1414 $(impl<'gcx: 'tcx, 'tcx, P: PrettyPrinter<'gcx, 'tcx>> Print<'gcx, 'tcx, P> for $ty {
1416 type Error = fmt::Error;
1417 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1418 #[allow(unused_mut)]
1420 define_scoped_cx!($cx);
1422 #[allow(unreachable_code)]
1427 forward_display_to_print!($($ty),+);
1431 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1432 impl fmt::Display for ty::RegionKind {
1433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1434 ty::tls::with(|tcx| {
1435 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1441 forward_display_to_print! {
1443 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1445 // HACK(eddyb) these are exhaustive instead of generic,
1446 // because `for<'gcx: 'tcx, 'tcx>` isn't possible yet.
1447 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1448 ty::Binder<ty::TraitRef<'tcx>>,
1449 ty::Binder<ty::FnSig<'tcx>>,
1450 ty::Binder<ty::TraitPredicate<'tcx>>,
1451 ty::Binder<ty::SubtypePredicate<'tcx>>,
1452 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1453 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1454 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1456 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1457 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1460 define_print_and_forward_display! {
1463 &'tcx ty::List<Ty<'tcx>> {
1465 let mut tys = self.iter();
1466 if let Some(&ty) = tys.next() {
1469 p!(write(", "), print(ty));
1475 ty::TypeAndMut<'tcx> {
1476 p!(write("{}", if self.mutbl == hir::MutMutable { "mut " } else { "" }),
1480 ty::ExistentialTraitRef<'tcx> {
1481 // Use a type that can't appear in defaults of type parameters.
1482 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1483 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1484 p!(print(trait_ref))
1487 ty::ExistentialProjection<'tcx> {
1488 let name = cx.tcx().associated_item(self.item_def_id).ident;
1489 p!(write("{} = ", name), print(self.ty))
1492 ty::ExistentialPredicate<'tcx> {
1494 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1495 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1496 ty::ExistentialPredicate::AutoTrait(def_id) => {
1497 p!(print_def_path(def_id, &[]));
1503 if self.unsafety == hir::Unsafety::Unsafe {
1504 p!(write("unsafe "));
1507 if self.abi != Abi::Rust {
1508 p!(write("extern {} ", self.abi));
1511 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1515 if cx.tcx().sess.verbose() {
1516 p!(write("{:?}", self));
1520 ty::TyVar(_) => p!(write("_")),
1521 ty::IntVar(_) => p!(write("{}", "{integer}")),
1522 ty::FloatVar(_) => p!(write("{}", "{float}")),
1523 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1524 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1525 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1529 ty::TraitRef<'tcx> {
1530 p!(print_def_path(self.def_id, self.substs));
1533 &'tcx ty::Const<'tcx> {
1535 ConstValue::Unevaluated(..) |
1536 ConstValue::Infer(..) => p!(write("_")),
1537 ConstValue::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1538 _ => p!(write("{:?}", self)),
1543 p!(write("{}", self.name))
1547 p!(write("{}", self.name))
1550 ty::SubtypePredicate<'tcx> {
1551 p!(print(self.a), write(" <: "), print(self.b))
1554 ty::TraitPredicate<'tcx> {
1555 p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref))
1558 ty::ProjectionPredicate<'tcx> {
1559 p!(print(self.projection_ty), write(" == "), print(self.ty))
1562 ty::ProjectionTy<'tcx> {
1563 p!(print_def_path(self.item_def_id, self.substs));
1568 ty::ClosureKind::Fn => p!(write("Fn")),
1569 ty::ClosureKind::FnMut => p!(write("FnMut")),
1570 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1574 ty::Predicate<'tcx> {
1576 ty::Predicate::Trait(ref data) => p!(print(data)),
1577 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1578 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1579 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1580 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1581 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1582 ty::Predicate::ObjectSafe(trait_def_id) => {
1583 p!(write("the trait `"),
1584 print_def_path(trait_def_id, &[]),
1585 write("` is object-safe"))
1587 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1588 p!(write("the closure `"),
1589 print_value_path(closure_def_id, &[]),
1590 write("` implements the trait `{}`", kind))
1592 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1593 p!(write("the constant `"),
1594 print_value_path(def_id, substs),
1595 write("` can be evaluated"))
1601 match self.unpack() {
1602 UnpackedKind::Lifetime(lt) => p!(print(lt)),
1603 UnpackedKind::Type(ty) => p!(print(ty)),
1604 UnpackedKind::Const(ct) => p!(print(ct)),