1 use crate::hir::def::Namespace;
2 use crate::hir::map::DefPathData;
3 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
4 use crate::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
5 use crate::ty::subst::{Subst, SubstsRef};
6 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
8 use syntax::symbol::{keywords, Symbol};
10 use rustc_data_structures::fx::FxHashSet;
11 use syntax::symbol::InternedString;
14 use std::fmt::{self, Write as _};
18 static FORCE_ABSOLUTE: Cell<bool> = Cell::new(false);
19 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
20 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
23 /// Enforces that def_path_str always returns an absolute path and
24 /// also enables "type-based" impl paths. This is used when building
25 /// symbols that contain types, where we want the crate name to be
26 /// part of the symbol.
27 pub fn with_forced_absolute_paths<F: FnOnce() -> R, R>(f: F) -> R {
28 FORCE_ABSOLUTE.with(|force| {
29 let old = force.get();
37 /// Force us to name impls with just the filename/line number. We
38 /// normally try to use types. But at some points, notably while printing
39 /// cycle errors, this can result in extra or suboptimal error output,
40 /// so this variable disables that check.
41 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
42 FORCE_IMPL_FILENAME_LINE.with(|force| {
43 let old = force.get();
51 /// Adds the `crate::` prefix to paths where appropriate.
52 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
53 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
62 // FIXME(eddyb) this module uses `pub(crate)` for things used only
63 // from `ppaux` - when that is removed, they can be re-privatized.
65 struct LateBoundRegionNameCollector(FxHashSet<InternedString>);
66 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector {
67 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
69 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
74 r.super_visit_with(self)
78 pub struct PrintCx<'a, 'gcx, 'tcx, P> {
79 pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
81 pub(crate) is_debug: bool,
82 pub(crate) is_verbose: bool,
83 pub(crate) identify_regions: bool,
84 pub(crate) used_region_names: Option<FxHashSet<InternedString>>,
85 pub(crate) region_index: usize,
86 pub(crate) binder_depth: usize,
89 // HACK(eddyb) this is solely for `self: &mut PrintCx<Self>`, e.g. to
90 // implement traits on the printer and call the methods on the context.
91 impl<P> Deref for PrintCx<'_, '_, '_, P> {
93 fn deref(&self) -> &P {
98 impl<P> PrintCx<'a, 'gcx, 'tcx, P> {
99 pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, printer: P) -> Self {
104 is_verbose: tcx.sess.verbose(),
105 identify_regions: tcx.sess.opts.debugging_opts.identify_regions,
106 used_region_names: None,
112 pub(crate) fn with<R>(printer: P, f: impl FnOnce(PrintCx<'_, '_, '_, P>) -> R) -> R {
113 ty::tls::with(|tcx| f(PrintCx::new(tcx, printer)))
115 pub(crate) fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
116 where T: TypeFoldable<'tcx>
118 let mut collector = LateBoundRegionNameCollector(Default::default());
119 value.visit_with(&mut collector);
120 self.used_region_names = Some(collector.0);
121 self.region_index = 0;
125 pub trait Print<'tcx, P> {
128 fn print(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output;
129 fn print_display(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output {
130 let old_debug = cx.is_debug;
132 let result = self.print(cx);
133 cx.is_debug = old_debug;
136 fn print_debug(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output {
137 let old_debug = cx.is_debug;
139 let result = self.print(cx);
140 cx.is_debug = old_debug;
145 pub trait Printer: Sized {
150 self: &mut PrintCx<'_, '_, 'tcx, Self>,
152 substs: Option<SubstsRef<'tcx>>,
155 self.default_print_def_path(def_id, substs, ns)
159 self: &mut PrintCx<'_, '_, 'tcx, Self>,
161 substs: Option<SubstsRef<'tcx>>,
164 self.default_print_impl_path(impl_def_id, substs, ns)
168 fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path;
170 fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path;
173 self: &mut PrintCx<'_, '_, '_, Self>,
180 pub struct PrettyPath {
184 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
185 pub trait PrettyPrinter: Printer<Path = Result<PrettyPath, fmt::Error>> + fmt::Write {}
187 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
188 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
189 // (but also some things just print a `DefId` generally so maybe we need this?)
190 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
191 match self.def_key(def_id).disambiguated_data.data {
192 DefPathData::ValueNs(..) |
193 DefPathData::EnumVariant(..) |
194 DefPathData::Field(..) |
195 DefPathData::AnonConst |
196 DefPathData::ClosureExpr |
197 DefPathData::StructCtor => Namespace::ValueNS,
199 DefPathData::MacroDef(..) => Namespace::MacroNS,
201 _ => Namespace::TypeNS,
205 /// Returns a string identifying this `DefId`. This string is
206 /// suitable for user output. It is relative to the current crate
207 /// root, unless with_forced_absolute_paths was used.
208 pub fn def_path_str_with_substs_and_ns(
211 substs: Option<SubstsRef<'tcx>>,
214 debug!("def_path_str: def_id={:?}, substs={:?}, ns={:?}", def_id, substs, ns);
215 if FORCE_ABSOLUTE.with(|force| force.get()) {
216 PrintCx::new(self, AbsolutePathPrinter).print_def_path(def_id, substs, ns)
218 let mut s = String::new();
219 let _ = PrintCx::new(self, FmtPrinter { fmt: &mut s })
220 .print_def_path(def_id, substs, ns);
225 /// Returns a string identifying this `DefId`. This string is
226 /// suitable for user output. It is relative to the current crate
227 /// root, unless with_forced_absolute_paths was used.
228 pub fn def_path_str(self, def_id: DefId) -> String {
229 let ns = self.guess_def_namespace(def_id);
230 self.def_path_str_with_substs_and_ns(def_id, None, ns)
233 /// Returns a string identifying this local node-id.
234 // FIXME(eddyb) remove in favor of calling `def_path_str` directly.
235 pub fn node_path_str(self, id: ast::NodeId) -> String {
236 self.def_path_str(self.hir().local_def_id(id))
239 /// Returns a string identifying this `DefId`. This string is
240 /// suitable for user output. It always begins with a crate identifier.
241 pub fn absolute_def_path_str(self, def_id: DefId) -> String {
242 debug!("absolute_def_path_str: def_id={:?}", def_id);
243 let ns = self.guess_def_namespace(def_id);
244 PrintCx::new(self, AbsolutePathPrinter).print_def_path(def_id, None, ns)
248 impl<P: Printer> PrintCx<'a, 'gcx, 'tcx, P> {
249 pub fn default_print_def_path(
252 substs: Option<SubstsRef<'tcx>>,
255 debug!("default_print_def_path: def_id={:?}, substs={:?}, ns={:?}", def_id, substs, ns);
256 let key = self.tcx.def_key(def_id);
257 debug!("default_print_def_path: key={:?}", key);
258 match key.disambiguated_data.data {
259 DefPathData::CrateRoot => {
260 assert!(key.parent.is_none());
261 self.path_crate(def_id.krate)
264 DefPathData::Impl => {
265 self.print_impl_path(def_id, substs, ns)
268 // Unclear if there is any value in distinguishing these.
269 // Probably eventually (and maybe we would even want
270 // finer-grained distinctions, e.g., between enum/struct).
271 data @ DefPathData::Misc |
272 data @ DefPathData::TypeNs(..) |
273 data @ DefPathData::Trait(..) |
274 data @ DefPathData::TraitAlias(..) |
275 data @ DefPathData::AssocTypeInTrait(..) |
276 data @ DefPathData::AssocTypeInImpl(..) |
277 data @ DefPathData::AssocExistentialInImpl(..) |
278 data @ DefPathData::ValueNs(..) |
279 data @ DefPathData::Module(..) |
280 data @ DefPathData::TypeParam(..) |
281 data @ DefPathData::LifetimeParam(..) |
282 data @ DefPathData::ConstParam(..) |
283 data @ DefPathData::EnumVariant(..) |
284 data @ DefPathData::Field(..) |
285 data @ DefPathData::AnonConst |
286 data @ DefPathData::MacroDef(..) |
287 data @ DefPathData::ClosureExpr |
288 data @ DefPathData::ImplTrait |
289 data @ DefPathData::GlobalMetaData(..) => {
290 let parent_did = self.tcx.parent(def_id).unwrap();
291 let path = self.print_def_path(parent_did, None, ns);
292 self.path_append(path, &data.as_interned_str().as_symbol().as_str())
295 DefPathData::StructCtor => { // present `X` instead of `X::{{constructor}}`
296 let parent_def_id = self.tcx.parent(def_id).unwrap();
297 self.print_def_path(parent_def_id, substs, ns)
302 fn default_print_impl_path(
305 substs: Option<SubstsRef<'tcx>>,
308 debug!("default_print_impl_path: impl_def_id={:?}", impl_def_id);
309 let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
311 // Decide whether to print the parent path for the impl.
312 // Logically, since impls are global, it's never needed, but
313 // users may find it useful. Currently, we omit the parent if
314 // the impl is either in the same module as the self-type or
316 let mut self_ty = self.tcx.type_of(impl_def_id);
317 if let Some(substs) = substs {
318 self_ty = self_ty.subst(self.tcx, substs);
320 let in_self_mod = match characteristic_def_id_of_type(self_ty) {
322 Some(ty_def_id) => self.tcx.parent(ty_def_id) == Some(parent_def_id),
325 let mut impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
326 if let Some(substs) = substs {
327 impl_trait_ref = impl_trait_ref.subst(self.tcx, substs);
329 let in_trait_mod = match impl_trait_ref {
331 Some(trait_ref) => self.tcx.parent(trait_ref.def_id) == Some(parent_def_id),
334 if !in_self_mod && !in_trait_mod {
335 // If the impl is not co-located with either self-type or
336 // trait-type, then fallback to a format that identifies
337 // the module more clearly.
338 let path = self.print_def_path(parent_def_id, None, ns);
339 if let Some(trait_ref) = impl_trait_ref {
340 return self.path_append(path, &format!("<impl {} for {}>", trait_ref, self_ty));
342 return self.path_append(path, &format!("<impl {}>", self_ty));
346 // Otherwise, try to give a good form that would be valid language
347 // syntax. Preferably using associated item notation.
349 if let Some(trait_ref) = impl_trait_ref {
351 return self.path_impl(&format!("<{} as {}>", self_ty, trait_ref));
354 // Inherent impls. Try to print `Foo::bar` for an inherent
355 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
356 // anything other than a simple path.
358 ty::Adt(adt_def, substs) => {
359 // FIXME(eddyb) this should recurse to build the path piecewise.
360 // self.print_def_path(adt_def.did, Some(substs), ns)
361 let mut s = String::new();
362 crate::util::ppaux::parameterized(&mut s, adt_def.did, substs, ns).unwrap();
366 ty::Foreign(did) => self.print_def_path(did, None, ns),
374 self.path_impl(&self_ty.to_string())
378 self.path_impl(&format!("<{}>", self_ty))
384 /// As a heuristic, when we see an impl, if we see that the
385 /// 'self type' is a type defined in the same module as the impl,
386 /// we can omit including the path to the impl itself. This
387 /// function tries to find a "characteristic `DefId`" for a
388 /// type. It's just a heuristic so it makes some questionable
389 /// decisions and we may want to adjust it later.
390 pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
392 ty::Adt(adt_def, _) => Some(adt_def.did),
394 ty::Dynamic(data, ..) => data.principal_def_id(),
396 ty::Array(subty, _) |
397 ty::Slice(subty) => characteristic_def_id_of_type(subty),
399 ty::RawPtr(mt) => characteristic_def_id_of_type(mt.ty),
401 ty::Ref(_, ty, _) => characteristic_def_id_of_type(ty),
403 ty::Tuple(ref tys) => tys.iter()
404 .filter_map(|ty| characteristic_def_id_of_type(ty))
407 ty::FnDef(def_id, _) |
408 ty::Closure(def_id, _) |
409 ty::Generator(def_id, _, _) |
410 ty::Foreign(def_id) => Some(def_id),
419 ty::Placeholder(..) |
420 ty::UnnormalizedProjection(..) |
426 ty::GeneratorWitness(..) |
428 ty::Float(_) => None,
432 // FIXME(eddyb) remove, alongside `FORCE_ABSOLUTE` and `absolute_def_path_str`.
433 struct AbsolutePathPrinter;
435 impl Printer for AbsolutePathPrinter {
438 fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path {
439 self.tcx.original_crate_name(cnum).to_string()
441 fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path {
445 self: &mut PrintCx<'_, '_, '_, Self>,
446 mut path: Self::Path,
449 if !path.is_empty() {
457 pub struct FmtPrinter<F: fmt::Write> {
461 impl<F: fmt::Write> FmtPrinter<F> {
462 /// If possible, this returns a global path resolving to `def_id` that is visible
463 /// from at least one local module and returns true. If the crate defining `def_id` is
464 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
465 fn try_print_visible_def_path(
466 self: &mut PrintCx<'_, '_, '_, Self>,
469 ) -> Option<<Self as Printer>::Path> {
470 debug!("try_print_visible_def_path: def_id={:?}", def_id);
472 // If `def_id` is a direct or injected extern crate, return the
473 // path to the crate followed by the path to the item within the crate.
474 if def_id.index == CRATE_DEF_INDEX {
475 let cnum = def_id.krate;
477 if cnum == LOCAL_CRATE {
478 return Some(self.path_crate(cnum));
481 // In local mode, when we encounter a crate other than
482 // LOCAL_CRATE, execution proceeds in one of two ways:
484 // 1. for a direct dependency, where user added an
485 // `extern crate` manually, we put the `extern
486 // crate` as the parent. So you wind up with
487 // something relative to the current crate.
488 // 2. for an extern inferred from a path or an indirect crate,
489 // where there is no explicit `extern crate`, we just prepend
491 match *self.tcx.extern_crate(def_id) {
493 src: ExternCrateSource::Extern(def_id),
498 debug!("try_print_visible_def_path: def_id={:?}", def_id);
499 let path = if !span.is_dummy() {
500 self.print_def_path(def_id, None, ns)
502 self.path_crate(cnum)
507 return Some(self.path_crate(cnum));
513 if def_id.is_local() {
517 let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
519 let mut cur_def_key = self.tcx.def_key(def_id);
520 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
522 // For a UnitStruct or TupleStruct we want the name of its parent rather than <unnamed>.
523 if let DefPathData::StructCtor = cur_def_key.disambiguated_data.data {
526 index: cur_def_key.parent.expect("DefPathData::StructCtor missing a parent"),
529 cur_def_key = self.tcx.def_key(parent);
532 let visible_parent = visible_parent_map.get(&def_id).cloned()?;
533 let path = self.try_print_visible_def_path(visible_parent, ns)?;
534 let actual_parent = self.tcx.parent(def_id);
536 let data = cur_def_key.disambiguated_data.data;
538 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
539 data, visible_parent, actual_parent,
542 let symbol = match data {
543 // In order to output a path that could actually be imported (valid and visible),
544 // we need to handle re-exports correctly.
546 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
547 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
549 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
550 // private so the "true" path to `CommandExt` isn't accessible.
552 // In this case, the `visible_parent_map` will look something like this:
554 // (child) -> (parent)
555 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
556 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
557 // `std::sys::unix::ext` -> `std::os`
559 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
562 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
563 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
564 // to the parent - resulting in a mangled path like
565 // `std::os::ext::process::CommandExt`.
567 // Instead, we must detect that there was a re-export and instead print `unix`
568 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
569 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
570 // the visible parent (`std::os`). If these do not match, then we iterate over
571 // the children of the visible parent (as was done when computing
572 // `visible_parent_map`), looking for the specific child we currently have and then
573 // have access to the re-exported name.
574 DefPathData::Module(actual_name) |
575 DefPathData::TypeNs(actual_name) if Some(visible_parent) != actual_parent => {
576 self.tcx.item_children(visible_parent)
578 .find(|child| child.def.def_id() == def_id)
579 .map(|child| child.ident.as_str())
580 .unwrap_or_else(|| actual_name.as_str())
583 data.get_opt_name().map(|n| n.as_str()).unwrap_or_else(|| {
584 // Re-exported `extern crate` (#43189).
585 if let DefPathData::CrateRoot = data {
586 self.tcx.original_crate_name(def_id.krate).as_str()
588 Symbol::intern("<unnamed>").as_str()
593 debug!("try_print_visible_def_path: symbol={:?}", symbol);
594 Some(self.path_append(path, &symbol))
598 impl<F: fmt::Write> fmt::Write for FmtPrinter<F> {
599 fn write_str(&mut self, s: &str) -> fmt::Result {
600 self.fmt.write_str(s)
604 impl<F: fmt::Write> Printer for FmtPrinter<F> {
605 type Path = Result<PrettyPath, fmt::Error>;
608 self: &mut PrintCx<'_, '_, 'tcx, Self>,
610 substs: Option<SubstsRef<'tcx>>,
613 self.try_print_visible_def_path(def_id, ns)
614 .unwrap_or_else(|| self.default_print_def_path(def_id, substs, ns))
617 self: &mut PrintCx<'_, '_, 'tcx, Self>,
619 substs: Option<SubstsRef<'tcx>>,
622 // Always use types for non-local impls, where types are always
623 // available, and filename/line-number is mostly uninteresting.
624 let use_types = !impl_def_id.is_local() || {
625 // Otherwise, use filename/line-number if forced.
626 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
631 // If no type info is available, fall back to
632 // pretty printing some span information. This should
633 // only occur very early in the compiler pipeline.
634 let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
635 let path = self.print_def_path(parent_def_id, None, ns);
636 let span = self.tcx.def_span(impl_def_id);
637 return self.path_append(path, &format!("<impl at {:?}>", span));
640 self.default_print_impl_path(impl_def_id, substs, ns)
643 fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path {
644 if cnum == LOCAL_CRATE {
645 if self.tcx.sess.rust_2018() {
646 // We add the `crate::` keyword on Rust 2018, only when desired.
647 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
648 write!(self.printer, "{}", keywords::Crate.name())?;
649 return Ok(PrettyPath { empty: false });
652 Ok(PrettyPath { empty: true })
654 write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
655 Ok(PrettyPath { empty: false })
658 fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path {
659 write!(self.printer, "{}", text)?;
660 Ok(PrettyPath { empty: false })
663 self: &mut PrintCx<'_, '_, '_, Self>,
669 // FIXME(eddyb) this shouldn't happen, but is currently
670 // the case for `extern { ... }` "foreign modules".
676 write!(self.printer, "::")?;
678 write!(self.printer, "{}", text)?;
679 Ok(PrettyPath { empty: false })
683 impl<F: fmt::Write> PrettyPrinter for FmtPrinter<F> {}