]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/print/pretty.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / print / pretty.rs
CommitLineData
923072b8 1use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
923072b8 2use crate::ty::{
f2b60f7d 3 self, ConstInt, DefIdTree, ParamConst, ScalarInt, Term, TermKind, Ty, TyCtxt, TypeFoldable,
064997fb 4 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable,
923072b8 5};
2b03887a 6use crate::ty::{GenericArg, GenericArgKind};
dc9dc135 7use rustc_apfloat::ieee::{Double, Single};
923072b8 8use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
cdc7bbd5 9use rustc_data_structures::sso::SsoHashSet;
ba9703b0 10use rustc_hir as hir;
1b1a35ee 11use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
04454e1e 12use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_ID, LOCAL_CRATE};
6522a427
EL
13use rustc_hir::definitions::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData};
14use rustc_hir::LangItem;
1b1a35ee 15use rustc_session::config::TrimmedDefPaths;
c295e0f8 16use rustc_session::cstore::{ExternCrate, ExternCrateSource};
6522a427 17use rustc_session::Limit;
f9f354fc 18use rustc_span::symbol::{kw, Ident, Symbol};
6522a427 19use rustc_span::FileNameDisplayPreference;
29967ef6 20use rustc_target::abi::Size;
532ac7d7 21use rustc_target::spec::abi::Abi;
2b03887a 22use smallvec::SmallVec;
532ac7d7
XL
23
24use std::cell::Cell;
ba9703b0 25use std::char;
60c5eb7d 26use std::collections::BTreeMap;
532ac7d7 27use std::fmt::{self, Write as _};
cdc7bbd5 28use std::iter;
29967ef6 29use std::ops::{ControlFlow, Deref, DerefMut};
532ac7d7
XL
30
31// `pretty` is a separate module only for organization.
32use super::*;
33
34macro_rules! p {
29967ef6
XL
35 (@$lit:literal) => {
36 write!(scoped_cx!(), $lit)?
37 };
532ac7d7
XL
38 (@write($($data:expr),+)) => {
39 write!(scoped_cx!(), $($data),+)?
40 };
41 (@print($x:expr)) => {
42 scoped_cx!() = $x.print(scoped_cx!())?
43 };
44 (@$method:ident($($arg:expr),*)) => {
45 scoped_cx!() = scoped_cx!().$method($($arg),*)?
46 };
29967ef6
XL
47 ($($elem:tt $(($($args:tt)*))?),+) => {{
48 $(p!(@ $elem $(($($args)*))?);)+
532ac7d7
XL
49 }};
50}
51macro_rules! define_scoped_cx {
52 ($cx:ident) => {
53 #[allow(unused_macros)]
54 macro_rules! scoped_cx {
dfeec247
XL
55 () => {
56 $cx
57 };
532ac7d7
XL
58 }
59 };
60}
61
62thread_local! {
17df50a5
XL
63 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
64 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
65 static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
6522a427 66 static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
17df50a5 67 static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
c295e0f8 68 static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
60c5eb7d
XL
69}
70
5e7ed085
FG
71macro_rules! define_helper {
72 ($($(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident);)+) => {
73 $(
74 #[must_use]
75 pub struct $helper(bool);
76
77 impl $helper {
78 pub fn new() -> $helper {
79 $helper($tl.with(|c| c.replace(true)))
80 }
81 }
532ac7d7 82
5e7ed085
FG
83 $(#[$a])*
84 pub macro $name($e:expr) {
85 {
86 let _guard = $helper::new();
87 $e
88 }
89 }
532ac7d7 90
5e7ed085
FG
91 impl Drop for $helper {
92 fn drop(&mut self) {
93 $tl.with(|c| c.set(self.0))
94 }
95 }
96 )+
97 }
1b1a35ee
XL
98}
99
5e7ed085
FG
100define_helper!(
101 /// Avoids running any queries during any prints that occur
102 /// during the closure. This may alter the appearance of some
103 /// types (e.g. forcing verbose printing for opaque types).
104 /// This method is used during some queries (e.g. `explicit_item_bounds`
105 /// for opaque types), to ensure that any debug printing that
106 /// occurs during the query computation does not end up recursively
107 /// calling the same query.
108 fn with_no_queries(NoQueriesGuard, NO_QUERIES);
109 /// Force us to name impls with just the filename/line number. We
110 /// normally try to use types. But at some points, notably while printing
111 /// cycle errors, this can result in extra or suboptimal error output,
112 /// so this variable disables that check.
113 fn with_forced_impl_filename_line(ForcedImplGuard, FORCE_IMPL_FILENAME_LINE);
114 /// Adds the `crate::` prefix to paths where appropriate.
115 fn with_crate_prefix(CratePrefixGuard, SHOULD_PREFIX_WITH_CRATE);
116 /// Prevent path trimming if it is turned on. Path trimming affects `Display` impl
117 /// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
118 /// if no other `Vec` is found.
119 fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
6522a427 120 fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
5e7ed085
FG
121 /// Prevent selection of visible paths. `Display` impl of DefId will prefer
122 /// visible (public) reexports of types as paths.
123 fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
124);
c295e0f8 125
532ac7d7
XL
126/// The "region highlights" are used to control region printing during
127/// specific error messages. When a "region highlight" is enabled, it
128/// gives an alternate way to print specific regions. For now, we
129/// always print those regions using a number, so something like "`'0`".
130///
131/// Regions not selected by the region highlight mode are presently
132/// unaffected.
5099ac24
FG
133#[derive(Copy, Clone)]
134pub struct RegionHighlightMode<'tcx> {
135 tcx: TyCtxt<'tcx>,
136
532ac7d7
XL
137 /// If enabled, when we see the selected region, use "`'N`"
138 /// instead of the ordinary behavior.
5099ac24 139 highlight_regions: [Option<(ty::Region<'tcx>, usize)>; 3],
532ac7d7
XL
140
141 /// If enabled, when printing a "free region" that originated from
fc512014 142 /// the given `ty::BoundRegionKind`, print it as "`'1`". Free regions that would ordinarily
532ac7d7
XL
143 /// have names print as normal.
144 ///
145 /// This is used when you have a signature like `fn foo(x: &u32,
146 /// y: &'a u32)` and we want to give a name to the region of the
147 /// reference `x`.
fc512014 148 highlight_bound_region: Option<(ty::BoundRegionKind, usize)>,
532ac7d7
XL
149}
150
5099ac24
FG
151impl<'tcx> RegionHighlightMode<'tcx> {
152 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
153 Self {
154 tcx,
155 highlight_regions: Default::default(),
156 highlight_bound_region: Default::default(),
157 }
158 }
159
532ac7d7
XL
160 /// If `region` and `number` are both `Some`, invokes
161 /// `highlighting_region`.
162 pub fn maybe_highlighting_region(
163 &mut self,
5099ac24 164 region: Option<ty::Region<'tcx>>,
532ac7d7
XL
165 number: Option<usize>,
166 ) {
167 if let Some(k) = region {
168 if let Some(n) = number {
169 self.highlighting_region(k, n);
170 }
171 }
172 }
173
174 /// Highlights the region inference variable `vid` as `'N`.
5099ac24 175 pub fn highlighting_region(&mut self, region: ty::Region<'tcx>, number: usize) {
532ac7d7 176 let num_slots = self.highlight_regions.len();
dfeec247 177 let first_avail_slot =
74b04a01 178 self.highlight_regions.iter_mut().find(|s| s.is_none()).unwrap_or_else(|| {
dfeec247 179 bug!("can only highlight {} placeholders at a time", num_slots,)
532ac7d7 180 });
5099ac24 181 *first_avail_slot = Some((region, number));
532ac7d7
XL
182 }
183
184 /// Convenience wrapper for `highlighting_region`.
dfeec247 185 pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) {
5099ac24 186 self.highlighting_region(self.tcx.mk_region(ty::ReVar(vid)), number)
532ac7d7
XL
187 }
188
189 /// Returns `Some(n)` with the number to use for the given region, if any.
923072b8 190 fn region_highlighted(&self, region: ty::Region<'tcx>) -> Option<usize> {
f9f354fc 191 self.highlight_regions.iter().find_map(|h| match h {
5099ac24 192 Some((r, n)) if *r == region => Some(*n),
f9f354fc
XL
193 _ => None,
194 })
532ac7d7
XL
195 }
196
197 /// Highlight the given bound region.
198 /// We can only highlight one bound region at a time. See
199 /// the field `highlight_bound_region` for more detailed notes.
fc512014 200 pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) {
532ac7d7
XL
201 assert!(self.highlight_bound_region.is_none());
202 self.highlight_bound_region = Some((br, number));
203 }
204}
205
206/// Trait for printers that pretty-print using `fmt::Write` to the printer.
dc9dc135
XL
207pub trait PrettyPrinter<'tcx>:
208 Printer<
209 'tcx,
532ac7d7
XL
210 Error = fmt::Error,
211 Path = Self,
212 Region = Self,
213 Type = Self,
214 DynExistential = Self,
dc9dc135
XL
215 Const = Self,
216 > + fmt::Write
532ac7d7
XL
217{
218 /// Like `print_def_path` but for value paths.
219 fn print_value_path(
220 self,
221 def_id: DefId,
e74abb32 222 substs: &'tcx [GenericArg<'tcx>],
532ac7d7
XL
223 ) -> Result<Self::Path, Self::Error> {
224 self.print_def_path(def_id, substs)
225 }
226
cdc7bbd5 227 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
dc9dc135
XL
228 where
229 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
532ac7d7 230 {
f035d41b 231 value.as_ref().skip_binder().print(self)
532ac7d7
XL
232 }
233
064997fb 234 fn wrap_binder<T, F: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
fc512014 235 self,
cdc7bbd5 236 value: &ty::Binder<'tcx, T>,
fc512014
XL
237 f: F,
238 ) -> Result<Self, Self::Error>
239 where
240 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
241 {
242 f(value.as_ref().skip_binder(), self)
243 }
244
e1599b0c 245 /// Prints comma-separated elements.
dc9dc135
XL
246 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
247 where
248 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
532ac7d7
XL
249 {
250 if let Some(first) = elems.next() {
251 self = first.print(self)?;
252 for elem in elems {
253 self.write_str(", ")?;
254 self = elem.print(self)?;
255 }
256 }
257 Ok(self)
258 }
259
ba9703b0
XL
260 /// Prints `{f: t}` or `{f as t}` depending on the `cast` argument
261 fn typed_value(
262 mut self,
263 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
264 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
265 conversion: &str,
266 ) -> Result<Self::Const, Self::Error> {
267 self.write_str("{")?;
268 self = f(self)?;
269 self.write_str(conversion)?;
270 self = t(self)?;
271 self.write_str("}")?;
272 Ok(self)
273 }
274
e1599b0c 275 /// Prints `<...>` around what `f` prints.
532ac7d7
XL
276 fn generic_delimiters(
277 self,
278 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
279 ) -> Result<Self, Self::Error>;
280
e1599b0c
XL
281 /// Returns `true` if the region should be printed in
282 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
532ac7d7 283 /// This is typically the case for all non-`'_` regions.
923072b8 284 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool;
532ac7d7 285
6522a427
EL
286 fn reset_type_limit(&mut self) {}
287
74b04a01 288 // Defaults (should not be overridden):
532ac7d7
XL
289
290 /// If possible, this returns a global path resolving to `def_id` that is visible
e1599b0c 291 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
532ac7d7 292 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
dfeec247 293 fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> {
c295e0f8
XL
294 if NO_VISIBLE_PATH.with(|flag| flag.get()) {
295 return Ok((self, false));
296 }
297
416331ca
XL
298 let mut callers = Vec::new();
299 self.try_print_visible_def_path_recur(def_id, &mut callers)
300 }
301
6522a427
EL
302 // Given a `DefId`, produce a short name. For types and traits, it prints *only* its name,
303 // For associated items on traits it prints out the trait's name and the associated item's name.
304 // For enum variants, if they have an unique name, then we only print the name, otherwise we
305 // print the enum name and the variant name. Otherwise, we do not print anything and let the
306 // caller use the `print_def_path` fallback.
307 fn force_print_trimmed_def_path(
308 mut self,
309 def_id: DefId,
310 ) -> Result<(Self::Path, bool), Self::Error> {
311 let key = self.tcx().def_key(def_id);
312 let visible_parent_map = self.tcx().visible_parent_map(());
313 let kind = self.tcx().def_kind(def_id);
314
315 let get_local_name = |this: &Self, name, def_id, key: DefKey| {
316 if let Some(visible_parent) = visible_parent_map.get(&def_id)
317 && let actual_parent = this.tcx().opt_parent(def_id)
318 && let DefPathData::TypeNs(_) = key.disambiguated_data.data
319 && Some(*visible_parent) != actual_parent
320 {
321 this
322 .tcx()
323 .module_children(visible_parent)
324 .iter()
325 .filter(|child| child.res.opt_def_id() == Some(def_id))
326 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
327 .map(|child| child.ident.name)
328 .unwrap_or(name)
329 } else {
330 name
331 }
332 };
333 if let DefKind::Variant = kind
334 && let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
335 {
336 // If `Assoc` is unique, we don't want to talk about `Trait::Assoc`.
337 self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?;
338 return Ok((self, true));
339 }
340 if let Some(symbol) = key.get_opt_name() {
341 if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
342 && let Some(parent) = self.tcx().opt_parent(def_id)
343 && let parent_key = self.tcx().def_key(parent)
344 && let Some(symbol) = parent_key.get_opt_name()
345 {
346 // Trait
347 self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
348 self.write_str("::")?;
349 } else if let DefKind::Variant = kind
350 && let Some(parent) = self.tcx().opt_parent(def_id)
351 && let parent_key = self.tcx().def_key(parent)
352 && let Some(symbol) = parent_key.get_opt_name()
353 {
354 // Enum
355
356 // For associated items and variants, we want the "full" path, namely, include
357 // the parent type in the path. For example, `Iterator::Item`.
358 self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
359 self.write_str("::")?;
360 } else if let DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Trait
361 | DefKind::TyAlias | DefKind::Fn | DefKind::Const | DefKind::Static(_) = kind
362 {
363 } else {
364 // If not covered above, like for example items out of `impl` blocks, fallback.
365 return Ok((self, false));
366 }
367 self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?;
368 return Ok((self, true));
369 }
370 Ok((self, false))
371 }
372
1b1a35ee
XL
373 /// Try to see if this path can be trimmed to a unique symbol name.
374 fn try_print_trimmed_def_path(
375 mut self,
376 def_id: DefId,
377 ) -> Result<(Self::Path, bool), Self::Error> {
6522a427
EL
378 if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
379 let (s, trimmed) = self.force_print_trimmed_def_path(def_id)?;
380 if trimmed {
381 return Ok((s, true));
382 }
383 self = s;
384 }
064997fb 385 if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
1b1a35ee
XL
386 || matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
387 || NO_TRIMMED_PATH.with(|flag| flag.get())
388 || SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get())
389 {
390 return Ok((self, false));
391 }
392
17df50a5 393 match self.tcx().trimmed_def_paths(()).get(&def_id) {
1b1a35ee
XL
394 None => Ok((self, false)),
395 Some(symbol) => {
6522a427 396 write!(self, "{}", Ident::with_dummy_span(*symbol))?;
1b1a35ee
XL
397 Ok((self, true))
398 }
399 }
400 }
401
416331ca
XL
402 /// Does the work of `try_print_visible_def_path`, building the
403 /// full definition path recursively before attempting to
404 /// post-process it into the valid and visible version that
405 /// accounts for re-exports.
406 ///
74b04a01 407 /// This method should only be called by itself or
416331ca
XL
408 /// `try_print_visible_def_path`.
409 ///
410 /// `callers` is a chain of visible_parent's leading to `def_id`,
411 /// to support cycle detection during recursion.
a2a8927a
XL
412 ///
413 /// This method returns false if we can't print the visible path, so
414 /// `print_def_path` can fall back on the item's real definition path.
416331ca 415 fn try_print_visible_def_path_recur(
532ac7d7
XL
416 mut self,
417 def_id: DefId,
416331ca 418 callers: &mut Vec<DefId>,
532ac7d7
XL
419 ) -> Result<(Self, bool), Self::Error> {
420 define_scoped_cx!(self);
421
422 debug!("try_print_visible_def_path: def_id={:?}", def_id);
423
424 // If `def_id` is a direct or injected extern crate, return the
425 // path to the crate followed by the path to the item within the crate.
04454e1e 426 if let Some(cnum) = def_id.as_crate_root() {
532ac7d7
XL
427 if cnum == LOCAL_CRATE {
428 return Ok((self.path_crate(cnum)?, true));
429 }
430
431 // In local mode, when we encounter a crate other than
432 // LOCAL_CRATE, execution proceeds in one of two ways:
433 //
e1599b0c 434 // 1. For a direct dependency, where user added an
532ac7d7
XL
435 // `extern crate` manually, we put the `extern
436 // crate` as the parent. So you wind up with
437 // something relative to the current crate.
e1599b0c 438 // 2. For an extern inferred from a path or an indirect crate,
532ac7d7
XL
439 // where there is no explicit `extern crate`, we just prepend
440 // the crate name.
dc9dc135 441 match self.tcx().extern_crate(def_id) {
f035d41b
XL
442 Some(&ExternCrate { src, dependency_of, span, .. }) => match (src, dependency_of) {
443 (ExternCrateSource::Extern(def_id), LOCAL_CRATE) => {
3c0e092e
XL
444 // NOTE(eddyb) the only reason `span` might be dummy,
445 // that we're aware of, is that it's the `std`/`core`
446 // `extern crate` injected by default.
447 // FIXME(eddyb) find something better to key this on,
448 // or avoid ending up with `ExternCrateSource::Extern`,
449 // for the injected `std`/`core`.
450 if span.is_dummy() {
451 return Ok((self.path_crate(cnum)?, true));
452 }
453
454 // Disable `try_print_trimmed_def_path` behavior within
455 // the `print_def_path` call, to avoid infinite recursion
456 // in cases where the `extern crate foo` has non-trivial
457 // parents, e.g. it's nested in `impl foo::Trait for Bar`
458 // (see also issues #55779 and #87932).
5e7ed085 459 self = with_no_visible_paths!(self.print_def_path(def_id, &[])?);
3c0e092e
XL
460
461 return Ok((self, true));
f035d41b
XL
462 }
463 (ExternCrateSource::Path, LOCAL_CRATE) => {
f035d41b
XL
464 return Ok((self.path_crate(cnum)?, true));
465 }
466 _ => {}
467 },
532ac7d7
XL
468 None => {
469 return Ok((self.path_crate(cnum)?, true));
470 }
532ac7d7
XL
471 }
472 }
473
474 if def_id.is_local() {
475 return Ok((self, false));
476 }
477
17df50a5 478 let visible_parent_map = self.tcx().visible_parent_map(());
532ac7d7
XL
479
480 let mut cur_def_key = self.tcx().def_key(def_id);
481 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
482
e1599b0c 483 // For a constructor, we want the name of its parent rather than <unnamed>.
ba9703b0
XL
484 if let DefPathData::Ctor = cur_def_key.disambiguated_data.data {
485 let parent = DefId {
486 krate: def_id.krate,
487 index: cur_def_key
488 .parent
489 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
490 };
532ac7d7 491
ba9703b0 492 cur_def_key = self.tcx().def_key(parent);
532ac7d7
XL
493 }
494
5e7ed085
FG
495 let Some(visible_parent) = visible_parent_map.get(&def_id).cloned() else {
496 return Ok((self, false));
532ac7d7 497 };
a2a8927a 498
04454e1e 499 let actual_parent = self.tcx().opt_parent(def_id);
532ac7d7
XL
500 debug!(
501 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
502 visible_parent, actual_parent,
503 );
504
505 let mut data = cur_def_key.disambiguated_data.data;
506 debug!(
507 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
508 data, visible_parent, actual_parent,
509 );
510
511 match data {
512 // In order to output a path that could actually be imported (valid and visible),
513 // we need to handle re-exports correctly.
514 //
515 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
516 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
517 //
5e7ed085 518 // `std::os::unix` reexports the contents of `std::sys::unix::ext`. `std::sys` is
532ac7d7
XL
519 // private so the "true" path to `CommandExt` isn't accessible.
520 //
521 // In this case, the `visible_parent_map` will look something like this:
522 //
523 // (child) -> (parent)
524 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
525 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
526 // `std::sys::unix::ext` -> `std::os`
527 //
528 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
529 // `std::os`.
530 //
531 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
532 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
533 // to the parent - resulting in a mangled path like
534 // `std::os::ext::process::CommandExt`.
535 //
536 // Instead, we must detect that there was a re-export and instead print `unix`
537 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
538 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
539 // the visible parent (`std::os`). If these do not match, then we iterate over
540 // the children of the visible parent (as was done when computing
541 // `visible_parent_map`), looking for the specific child we currently have and then
542 // have access to the re-exported name.
532ac7d7 543 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
a2a8927a
XL
544 // Item might be re-exported several times, but filter for the one
545 // that's public and whose identifier isn't `_`.
dfeec247
XL
546 let reexport = self
547 .tcx()
5099ac24 548 .module_children(visible_parent)
532ac7d7 549 .iter()
a2a8927a
XL
550 .filter(|child| child.res.opt_def_id() == Some(def_id))
551 .find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
e74abb32 552 .map(|child| child.ident.name);
a2a8927a
XL
553
554 if let Some(new_name) = reexport {
555 *name = new_name;
556 } else {
557 // There is no name that is public and isn't `_`, so bail.
558 return Ok((self, false));
532ac7d7
XL
559 }
560 }
561 // Re-exported `extern crate` (#43189).
562 DefPathData::CrateRoot => {
17df50a5 563 data = DefPathData::TypeNs(self.tcx().crate_name(def_id.krate));
532ac7d7
XL
564 }
565 _ => {}
566 }
567 debug!("try_print_visible_def_path: data={:?}", data);
568
a2a8927a
XL
569 if callers.contains(&visible_parent) {
570 return Ok((self, false));
571 }
572 callers.push(visible_parent);
573 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
574 // knowing ahead of time whether the entire path will succeed or not.
575 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
576 // linked list on the stack would need to be built, before any printing.
577 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
578 (cx, false) => return Ok((cx, false)),
579 (cx, true) => self = cx,
580 }
581 callers.pop();
582
dfeec247 583 Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true))
532ac7d7
XL
584 }
585
586 fn pretty_path_qualified(
587 self,
588 self_ty: Ty<'tcx>,
589 trait_ref: Option<ty::TraitRef<'tcx>>,
590 ) -> Result<Self::Path, Self::Error> {
591 if trait_ref.is_none() {
592 // Inherent impls. Try to print `Foo::bar` for an inherent
593 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
594 // anything other than a simple path.
1b1a35ee 595 match self_ty.kind() {
dfeec247
XL
596 ty::Adt(..)
597 | ty::Foreign(_)
598 | ty::Bool
599 | ty::Char
600 | ty::Str
601 | ty::Int(_)
602 | ty::Uint(_)
603 | ty::Float(_) => {
532ac7d7
XL
604 return self_ty.print(self);
605 }
606
607 _ => {}
608 }
609 }
610
611 self.generic_delimiters(|mut cx| {
612 define_scoped_cx!(cx);
613
614 p!(print(self_ty));
615 if let Some(trait_ref) = trait_ref {
29967ef6 616 p!(" as ", print(trait_ref.print_only_trait_path()));
532ac7d7
XL
617 }
618 Ok(cx)
619 })
620 }
621
622 fn pretty_path_append_impl(
623 mut self,
624 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
625 self_ty: Ty<'tcx>,
626 trait_ref: Option<ty::TraitRef<'tcx>>,
627 ) -> Result<Self::Path, Self::Error> {
628 self = print_prefix(self)?;
629
630 self.generic_delimiters(|mut cx| {
631 define_scoped_cx!(cx);
632
29967ef6 633 p!("impl ");
532ac7d7 634 if let Some(trait_ref) = trait_ref {
29967ef6 635 p!(print(trait_ref.print_only_trait_path()), " for ");
532ac7d7
XL
636 }
637 p!(print(self_ty));
638
639 Ok(cx)
640 })
641 }
642
dfeec247 643 fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
532ac7d7
XL
644 define_scoped_cx!(self);
645
1b1a35ee 646 match *ty.kind() {
29967ef6
XL
647 ty::Bool => p!("bool"),
648 ty::Char => p!("char"),
60c5eb7d
XL
649 ty::Int(t) => p!(write("{}", t.name_str())),
650 ty::Uint(t) => p!(write("{}", t.name_str())),
651 ty::Float(t) => p!(write("{}", t.name_str())),
532ac7d7 652 ty::RawPtr(ref tm) => {
dfeec247
XL
653 p!(write(
654 "*{} ",
655 match tm.mutbl {
656 hir::Mutability::Mut => "mut",
657 hir::Mutability::Not => "const",
658 }
659 ));
532ac7d7
XL
660 p!(print(tm.ty))
661 }
662 ty::Ref(r, ty, mutbl) => {
29967ef6 663 p!("&");
5e7ed085 664 if self.should_print_region(r) {
29967ef6 665 p!(print(r), " ");
532ac7d7
XL
666 }
667 p!(print(ty::TypeAndMut { ty, mutbl }))
668 }
29967ef6 669 ty::Never => p!("!"),
532ac7d7 670 ty::Tuple(ref tys) => {
29967ef6 671 p!("(", comma_sep(tys.iter()));
ba9703b0 672 if tys.len() == 1 {
29967ef6 673 p!(",");
532ac7d7 674 }
29967ef6 675 p!(")")
532ac7d7
XL
676 }
677 ty::FnDef(def_id, substs) => {
04454e1e 678 let sig = self.tcx().bound_fn_sig(def_id).subst(self.tcx(), substs);
29967ef6 679 p!(print(sig), " {{", print_value_path(def_id, substs), "}}");
532ac7d7 680 }
dfeec247 681 ty::FnPtr(ref bare_fn) => p!(print(bare_fn)),
dc9dc135 682 ty::Infer(infer_ty) => {
6522a427 683 let verbose = self.should_print_verbose();
dc9dc135 684 if let ty::TyVar(ty_vid) = infer_ty {
5099ac24 685 if let Some(name) = self.ty_infer_name(ty_vid) {
dc9dc135
XL
686 p!(write("{}", name))
687 } else {
5869c6ff
XL
688 if verbose {
689 p!(write("{:?}", infer_ty))
690 } else {
691 p!(write("{}", infer_ty))
692 }
dc9dc135
XL
693 }
694 } else {
5869c6ff 695 if verbose { p!(write("{:?}", infer_ty)) } else { p!(write("{}", infer_ty)) }
dc9dc135 696 }
dfeec247 697 }
29967ef6 698 ty::Error(_) => p!("[type error]"),
5e7ed085 699 ty::Param(ref param_ty) => p!(print(param_ty)),
dfeec247 700 ty::Bound(debruijn, bound_ty) => match bound_ty.kind {
ba9703b0 701 ty::BoundTyKind::Anon => self.pretty_print_bound_var(debruijn, bound_ty.var)?,
dfeec247
XL
702 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
703 },
532ac7d7 704 ty::Adt(def, substs) => {
5e7ed085 705 p!(print_def_path(def.did(), substs));
532ac7d7 706 }
f2b60f7d 707 ty::Dynamic(data, r, repr) => {
5e7ed085 708 let print_r = self.should_print_region(r);
532ac7d7 709 if print_r {
29967ef6 710 p!("(");
532ac7d7 711 }
f2b60f7d
FG
712 match repr {
713 ty::Dyn => p!("dyn "),
714 ty::DynStar => p!("dyn* "),
715 }
716 p!(print(data));
532ac7d7 717 if print_r {
29967ef6 718 p!(" + ", print(r), ")");
532ac7d7
XL
719 }
720 }
721 ty::Foreign(def_id) => {
722 p!(print_def_path(def_id, &[]));
723 }
6522a427
EL
724 ty::Alias(ty::Projection, ref data) => {
725 if !(self.should_print_verbose() || NO_QUERIES.with(|q| q.get()))
726 && self.tcx().def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
2b03887a 727 {
6522a427 728 return self.pretty_print_opaque_impl_type(data.def_id, data.substs);
f2b60f7d
FG
729 } else {
730 p!(print(data))
731 }
732 }
dfeec247 733 ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
6522a427 734 ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => {
532ac7d7 735 // FIXME(eddyb) print this with `print_def_path`.
60c5eb7d
XL
736 // We use verbose printing in 'NO_QUERIES' mode, to
737 // avoid needing to call `predicates_of`. This should
738 // only affect certain debug messages (e.g. messages printed
ba9703b0 739 // from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
60c5eb7d 740 // and should have no effect on any compiler output.
6522a427 741 if self.should_print_verbose() || NO_QUERIES.with(|q| q.get()) {
532ac7d7
XL
742 p!(write("Opaque({:?}, {:?})", def_id, substs));
743 return Ok(self);
744 }
745
04454e1e 746 let parent = self.tcx().parent(def_id);
5e7ed085
FG
747 match self.tcx().def_kind(parent) {
748 DefKind::TyAlias | DefKind::AssocTy => {
6522a427
EL
749 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) =
750 *self.tcx().type_of(parent).kind()
751 {
5e7ed085
FG
752 if d == def_id {
753 // If the type alias directly starts with the `impl` of the
754 // opaque type we're printing, then skip the `::{opaque#1}`.
755 p!(print_def_path(parent, substs));
756 return Ok(self);
757 }
532ac7d7 758 }
5e7ed085
FG
759 // Complex opaque type, e.g. `type Foo = (i32, impl Debug);`
760 p!(print_def_path(def_id, substs));
60c5eb7d 761 return Ok(self);
532ac7d7 762 }
5e7ed085
FG
763 _ => return self.pretty_print_opaque_impl_type(def_id, substs),
764 }
532ac7d7 765 }
29967ef6 766 ty::Str => p!("str"),
532ac7d7 767 ty::Generator(did, substs, movability) => {
1b1a35ee 768 p!(write("["));
6522a427
EL
769 let generator_kind = self.tcx().generator_kind(did).unwrap();
770 let should_print_movability =
771 self.should_print_verbose() || generator_kind == hir::GeneratorKind::Gen;
772
773 if should_print_movability {
774 match movability {
775 hir::Movability::Movable => {}
776 hir::Movability::Static => p!("static "),
777 }
532ac7d7
XL
778 }
779
6522a427
EL
780 if !self.should_print_verbose() {
781 p!(write("{}", generator_kind));
1b1a35ee
XL
782 // FIXME(eddyb) should use `def_span`.
783 if let Some(did) = did.as_local() {
5099ac24 784 let span = self.tcx().def_span(did);
17df50a5
XL
785 p!(write(
786 "@{}",
787 // This may end up in stderr diagnostics but it may also be emitted
788 // into MIR. Hence we use the remapped path if available
789 self.tcx().sess.source_map().span_to_embeddable_string(span)
790 ));
1b1a35ee 791 } else {
29967ef6 792 p!(write("@"), print_def_path(did, substs));
532ac7d7
XL
793 }
794 } else {
1b1a35ee 795 p!(print_def_path(did, substs));
29967ef6
XL
796 p!(" upvar_tys=(");
797 if !substs.as_generator().is_valid() {
798 p!("unavailable");
799 } else {
800 self = self.comma_sep(substs.as_generator().upvar_tys())?;
532ac7d7 801 }
29967ef6 802 p!(")");
532ac7d7 803
136023e0
XL
804 if substs.as_generator().is_valid() {
805 p!(" ", print(substs.as_generator().witness()));
806 }
ba9703b0
XL
807 }
808
29967ef6 809 p!("]")
dfeec247 810 }
532ac7d7
XL
811 ty::GeneratorWitness(types) => {
812 p!(in_binder(&types));
813 }
814 ty::Closure(did, substs) => {
1b1a35ee 815 p!(write("["));
6522a427 816 if !self.should_print_verbose() {
1b1a35ee
XL
817 p!(write("closure"));
818 // FIXME(eddyb) should use `def_span`.
819 if let Some(did) = did.as_local() {
064997fb 820 if self.tcx().sess.opts.unstable_opts.span_free_formats {
29967ef6 821 p!("@", print_def_path(did.to_def_id(), substs));
1b1a35ee 822 } else {
5099ac24 823 let span = self.tcx().def_span(did);
6522a427
EL
824 let preference = if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
825 FileNameDisplayPreference::Short
826 } else {
827 FileNameDisplayPreference::Remapped
828 };
17df50a5
XL
829 p!(write(
830 "@{}",
831 // This may end up in stderr diagnostics but it may also be emitted
832 // into MIR. Hence we use the remapped path if available
6522a427 833 self.tcx().sess.source_map().span_to_string(span, preference)
17df50a5 834 ));
ba9703b0 835 }
1b1a35ee 836 } else {
29967ef6 837 p!(write("@"), print_def_path(did, substs));
532ac7d7
XL
838 }
839 } else {
1b1a35ee 840 p!(print_def_path(did, substs));
29967ef6
XL
841 if !substs.as_closure().is_valid() {
842 p!(" closure_substs=(unavailable)");
3c0e092e 843 p!(write(" substs={:?}", substs));
29967ef6
XL
844 } else {
845 p!(" closure_kind_ty=", print(substs.as_closure().kind_ty()));
846 p!(
847 " closure_sig_as_fn_ptr_ty=",
848 print(substs.as_closure().sig_as_fn_ptr_ty())
849 );
850 p!(" upvar_tys=(");
851 self = self.comma_sep(substs.as_closure().upvar_tys())?;
852 p!(")");
532ac7d7
XL
853 }
854 }
29967ef6 855 p!("]");
dfeec247 856 }
6522a427 857 ty::Array(ty, sz) => p!("[", print(ty), "; ", print(sz), "]"),
29967ef6 858 ty::Slice(ty) => p!("[", print(ty), "]"),
532ac7d7
XL
859 }
860
861 Ok(self)
862 }
863
3c0e092e
XL
864 fn pretty_print_opaque_impl_type(
865 mut self,
866 def_id: DefId,
867 substs: &'tcx ty::List<ty::GenericArg<'tcx>>,
868 ) -> Result<Self::Type, Self::Error> {
064997fb 869 let tcx = self.tcx();
3c0e092e
XL
870
871 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
872 // by looking up the projections associated with the def_id.
064997fb 873 let bounds = tcx.bound_explicit_item_bounds(def_id);
3c0e092e 874
923072b8
FG
875 let mut traits = FxIndexMap::default();
876 let mut fn_traits = FxIndexMap::default();
3c0e092e 877 let mut is_sized = false;
2b03887a 878 let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new();
3c0e092e 879
2b03887a 880 for (predicate, _) in bounds.subst_iter_copied(tcx, substs) {
3c0e092e
XL
881 let bound_predicate = predicate.kind();
882
883 match bound_predicate.skip_binder() {
6522a427 884 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
3c0e092e
XL
885 let trait_ref = bound_predicate.rebind(pred.trait_ref);
886
887 // Don't print + Sized, but rather + ?Sized if absent.
064997fb 888 if Some(trait_ref.def_id()) == tcx.lang_items().sized_trait() {
3c0e092e
XL
889 is_sized = true;
890 continue;
891 }
892
893 self.insert_trait_and_projection(trait_ref, None, &mut traits, &mut fn_traits);
894 }
6522a427 895 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
3c0e092e 896 let proj_ref = bound_predicate.rebind(pred);
064997fb 897 let trait_ref = proj_ref.required_poly_trait_ref(tcx);
3c0e092e
XL
898
899 // Projection type entry -- the def-id for naming, and the ty.
5099ac24 900 let proj_ty = (proj_ref.projection_def_id(), proj_ref.term());
3c0e092e
XL
901
902 self.insert_trait_and_projection(
903 trait_ref,
904 Some(proj_ty),
905 &mut traits,
906 &mut fn_traits,
907 );
908 }
6522a427 909 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(outlives)) => {
2b03887a
FG
910 lifetimes.push(outlives.1);
911 }
3c0e092e
XL
912 _ => {}
913 }
914 }
915
064997fb
FG
916 write!(self, "impl ")?;
917
3c0e092e
XL
918 let mut first = true;
919 // Insert parenthesis around (Fn(A, B) -> C) if the opaque ty has more than one other trait
920 let paren_needed = fn_traits.len() > 1 || traits.len() > 0 || !is_sized;
921
3c0e092e 922 for (fn_once_trait_ref, entry) in fn_traits {
064997fb
FG
923 write!(self, "{}", if first { "" } else { " + " })?;
924 write!(self, "{}", if paren_needed { "(" } else { "" })?;
3c0e092e 925
064997fb
FG
926 self = self.wrap_binder(&fn_once_trait_ref, |trait_ref, mut cx| {
927 define_scoped_cx!(cx);
928 // Get the (single) generic ty (the args) of this FnOnce trait ref.
929 let generics = tcx.generics_of(trait_ref.def_id);
930 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
931
932 match (entry.return_ty, args[0].expect_ty()) {
933 // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded
934 // a return type.
935 (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => {
936 let name = if entry.fn_trait_ref.is_some() {
937 "Fn"
938 } else if entry.fn_mut_trait_ref.is_some() {
939 "FnMut"
940 } else {
941 "FnOnce"
942 };
3c0e092e 943
064997fb
FG
944 p!(write("{}(", name));
945
946 for (idx, ty) in arg_tys.tuple_fields().iter().enumerate() {
947 if idx > 0 {
948 p!(", ");
949 }
950 p!(print(ty));
3c0e092e 951 }
3c0e092e 952
064997fb 953 p!(")");
f2b60f7d 954 if let Some(ty) = return_ty.skip_binder().ty() {
064997fb
FG
955 if !ty.is_unit() {
956 p!(" -> ", print(return_ty));
957 }
5099ac24 958 }
064997fb 959 p!(write("{}", if paren_needed { ")" } else { "" }));
3c0e092e 960
064997fb 961 first = false;
3c0e092e 962 }
064997fb
FG
963 // If we got here, we can't print as a `impl Fn(A, B) -> C`. Just record the
964 // trait_refs we collected in the OpaqueFnEntry as normal trait refs.
965 _ => {
966 if entry.has_fn_once {
967 traits.entry(fn_once_trait_ref).or_default().extend(
968 // Group the return ty with its def id, if we had one.
969 entry
970 .return_ty
6522a427 971 .map(|ty| (tcx.require_lang_item(LangItem::FnOnce, None), ty)),
064997fb
FG
972 );
973 }
974 if let Some(trait_ref) = entry.fn_mut_trait_ref {
975 traits.entry(trait_ref).or_default();
976 }
977 if let Some(trait_ref) = entry.fn_trait_ref {
978 traits.entry(trait_ref).or_default();
979 }
3c0e092e
XL
980 }
981 }
064997fb
FG
982
983 Ok(cx)
984 })?;
3c0e092e
XL
985 }
986
987 // Print the rest of the trait types (that aren't Fn* family of traits)
988 for (trait_ref, assoc_items) in traits {
064997fb 989 write!(self, "{}", if first { "" } else { " + " })?;
3c0e092e 990
064997fb
FG
991 self = self.wrap_binder(&trait_ref, |trait_ref, mut cx| {
992 define_scoped_cx!(cx);
993 p!(print(trait_ref.print_only_trait_name()));
3c0e092e 994
064997fb
FG
995 let generics = tcx.generics_of(trait_ref.def_id);
996 let args = generics.own_substs_no_defaults(tcx, trait_ref.substs);
3c0e092e 997
064997fb
FG
998 if !args.is_empty() || !assoc_items.is_empty() {
999 let mut first = true;
1000
1001 for ty in args {
1002 if first {
1003 p!("<");
1004 first = false;
1005 } else {
1006 p!(", ");
1007 }
1008 p!(print(ty));
3c0e092e 1009 }
3c0e092e 1010
064997fb
FG
1011 for (assoc_item_def_id, term) in assoc_items {
1012 // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks,
1013 // unless we can find out what generator return type it comes from.
1014 let term = if let Some(ty) = term.skip_binder().ty()
6522a427
EL
1015 && let ty::Alias(ty::Projection, proj) = ty.kind()
1016 && let Some(assoc) = tcx.opt_associated_item(proj.def_id)
f2b60f7d
FG
1017 && assoc.trait_container(tcx) == tcx.lang_items().gen_trait()
1018 && assoc.name == rustc_span::sym::Return
064997fb
FG
1019 {
1020 if let ty::Generator(_, substs, _) = substs.type_at(0).kind() {
1021 let return_ty = substs.as_generator().return_ty();
f2b60f7d 1022 if !return_ty.is_ty_var() {
064997fb
FG
1023 return_ty.into()
1024 } else {
1025 continue;
1026 }
5e7ed085
FG
1027 } else {
1028 continue;
1029 }
1030 } else {
064997fb
FG
1031 term.skip_binder()
1032 };
5e7ed085 1033
064997fb
FG
1034 if first {
1035 p!("<");
1036 first = false;
1037 } else {
1038 p!(", ");
1039 }
5e7ed085 1040
064997fb 1041 p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name));
5099ac24 1042
f2b60f7d
FG
1043 match term.unpack() {
1044 TermKind::Ty(ty) => p!(print(ty)),
1045 TermKind::Const(c) => p!(print(c)),
064997fb
FG
1046 };
1047 }
3c0e092e 1048
064997fb
FG
1049 if !first {
1050 p!(">");
1051 }
5e7ed085 1052 }
3c0e092e 1053
064997fb
FG
1054 first = false;
1055 Ok(cx)
1056 })?;
3c0e092e
XL
1057 }
1058
1059 if !is_sized {
064997fb 1060 write!(self, "{}?Sized", if first { "" } else { " + " })?;
3c0e092e 1061 } else if first {
064997fb 1062 write!(self, "Sized")?;
3c0e092e
XL
1063 }
1064
2b03887a
FG
1065 for re in lifetimes {
1066 write!(self, " + ")?;
1067 self = self.print_region(re)?;
1068 }
1069
3c0e092e
XL
1070 Ok(self)
1071 }
1072
1073 /// Insert the trait ref and optionally a projection type associated with it into either the
1074 /// traits map or fn_traits map, depending on if the trait is in the Fn* family of traits.
1075 fn insert_trait_and_projection(
1076 &mut self,
1077 trait_ref: ty::PolyTraitRef<'tcx>,
5099ac24 1078 proj_ty: Option<(DefId, ty::Binder<'tcx, Term<'tcx>>)>,
923072b8 1079 traits: &mut FxIndexMap<
5099ac24 1080 ty::PolyTraitRef<'tcx>,
923072b8 1081 FxIndexMap<DefId, ty::Binder<'tcx, Term<'tcx>>>,
5099ac24 1082 >,
923072b8 1083 fn_traits: &mut FxIndexMap<ty::PolyTraitRef<'tcx>, OpaqueFnEntry<'tcx>>,
3c0e092e
XL
1084 ) {
1085 let trait_def_id = trait_ref.def_id();
1086
1087 // If our trait_ref is FnOnce or any of its children, project it onto the parent FnOnce
1088 // super-trait ref and record it there.
1089 if let Some(fn_once_trait) = self.tcx().lang_items().fn_once_trait() {
1090 // If we have a FnOnce, then insert it into
1091 if trait_def_id == fn_once_trait {
1092 let entry = fn_traits.entry(trait_ref).or_default();
1093 // Optionally insert the return_ty as well.
1094 if let Some((_, ty)) = proj_ty {
1095 entry.return_ty = Some(ty);
1096 }
1097 entry.has_fn_once = true;
1098 return;
1099 } else if Some(trait_def_id) == self.tcx().lang_items().fn_mut_trait() {
1100 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1101 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1102 .unwrap();
1103
1104 fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
1105 return;
1106 } else if Some(trait_def_id) == self.tcx().lang_items().fn_trait() {
1107 let super_trait_ref = crate::traits::util::supertraits(self.tcx(), trait_ref)
1108 .find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
1109 .unwrap();
1110
1111 fn_traits.entry(super_trait_ref).or_default().fn_trait_ref = Some(trait_ref);
1112 return;
1113 }
1114 }
1115
1116 // Otherwise, just group our traits and projection types.
1117 traits.entry(trait_ref).or_default().extend(proj_ty);
1118 }
1119
ba9703b0
XL
1120 fn pretty_print_bound_var(
1121 &mut self,
1122 debruijn: ty::DebruijnIndex,
1123 var: ty::BoundVar,
1124 ) -> Result<(), Self::Error> {
1125 if debruijn == ty::INNERMOST {
1126 write!(self, "^{}", var.index())
1127 } else {
1128 write!(self, "^{}_{}", debruijn.index(), var.index())
1129 }
1130 }
1131
064997fb 1132 fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> {
5099ac24
FG
1133 None
1134 }
1135
064997fb 1136 fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<Symbol> {
dc9dc135
XL
1137 None
1138 }
1139
532ac7d7
XL
1140 fn pretty_print_dyn_existential(
1141 mut self,
6522a427 1142 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
532ac7d7 1143 ) -> Result<Self::DynExistential, Self::Error> {
532ac7d7
XL
1144 // Generate the main trait ref, including associated types.
1145 let mut first = true;
1146
1147 if let Some(principal) = predicates.principal() {
fc512014
XL
1148 self = self.wrap_binder(&principal, |principal, mut cx| {
1149 define_scoped_cx!(cx);
1150 p!(print_def_path(principal.def_id, &[]));
1151
1152 let mut resugared = false;
1153
5e7ed085 1154 // Special-case `Fn(...) -> ...` and re-sugar it.
6522a427
EL
1155 let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id);
1156 if !cx.should_print_verbose() && fn_trait_kind.is_some() {
5e7ed085 1157 if let ty::Tuple(tys) = principal.substs.type_at(0).kind() {
fc512014
XL
1158 let mut projections = predicates.projection_bounds();
1159 if let (Some(proj), None) = (projections.next(), projections.next()) {
5099ac24 1160 p!(pretty_fn_sig(
5e7ed085 1161 tys,
5099ac24
FG
1162 false,
1163 proj.skip_binder().term.ty().expect("Return type was a const")
1164 ));
fc512014
XL
1165 resugared = true;
1166 }
532ac7d7
XL
1167 }
1168 }
532ac7d7 1169
fc512014
XL
1170 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
1171 // in order to place the projections inside the `<...>`.
1172 if !resugared {
1173 // Use a type that can't appear in defaults of type parameters.
1174 let dummy_cx = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1175 let principal = principal.with_self_ty(cx.tcx(), dummy_cx);
1176
923072b8
FG
1177 let args = cx
1178 .tcx()
1179 .generics_of(principal.def_id)
1180 .own_substs_no_defaults(cx.tcx(), principal.substs);
fc512014 1181
fc512014 1182 let mut projections = predicates.projection_bounds();
532ac7d7 1183
2b03887a 1184 let mut args = args.iter().cloned();
fc512014
XL
1185 let arg0 = args.next();
1186 let projection0 = projections.next();
1187 if arg0.is_some() || projection0.is_some() {
1188 let args = arg0.into_iter().chain(args);
1189 let projections = projection0.into_iter().chain(projections);
532ac7d7 1190
fc512014
XL
1191 p!(generic_delimiters(|mut cx| {
1192 cx = cx.comma_sep(args)?;
1193 if arg0.is_some() && projection0.is_some() {
1194 write!(cx, ", ")?;
1195 }
1196 cx.comma_sep(projections)
1197 }));
1198 }
532ac7d7 1199 }
fc512014
XL
1200 Ok(cx)
1201 })?;
1202
532ac7d7
XL
1203 first = false;
1204 }
1205
fc512014
XL
1206 define_scoped_cx!(self);
1207
532ac7d7
XL
1208 // Builtin bounds.
1209 // FIXME(eddyb) avoid printing twice (needed to ensure
1210 // that the auto traits are sorted *and* printed via cx).
923072b8 1211 let mut auto_traits: Vec<_> = predicates.auto_traits().collect();
532ac7d7
XL
1212
1213 // The auto traits come ordered by `DefPathHash`. While
1214 // `DefPathHash` is *stable* in the sense that it depends on
1215 // neither the host nor the phase of the moon, it depends
1216 // "pseudorandomly" on the compiler version and the target.
1217 //
923072b8 1218 // To avoid causing instabilities in compiletest
532ac7d7 1219 // output, sort the auto-traits alphabetically.
6522a427 1220 auto_traits.sort_by_cached_key(|did| with_no_trimmed_paths!(self.tcx().def_path_str(*did)));
532ac7d7 1221
923072b8 1222 for def_id in auto_traits {
532ac7d7 1223 if !first {
29967ef6 1224 p!(" + ");
532ac7d7
XL
1225 }
1226 first = false;
1227
1228 p!(print_def_path(def_id, &[]));
1229 }
1230
1231 Ok(self)
1232 }
1233
1234 fn pretty_fn_sig(
1235 mut self,
1236 inputs: &[Ty<'tcx>],
1237 c_variadic: bool,
1238 output: Ty<'tcx>,
1239 ) -> Result<Self, Self::Error> {
1240 define_scoped_cx!(self);
1241
29967ef6 1242 p!("(", comma_sep(inputs.iter().copied()));
ba9703b0
XL
1243 if c_variadic {
1244 if !inputs.is_empty() {
29967ef6 1245 p!(", ");
532ac7d7 1246 }
29967ef6 1247 p!("...");
532ac7d7 1248 }
29967ef6 1249 p!(")");
532ac7d7 1250 if !output.is_unit() {
29967ef6 1251 p!(" -> ", print(output));
532ac7d7
XL
1252 }
1253
1254 Ok(self)
1255 }
dc9dc135
XL
1256
1257 fn pretty_print_const(
1258 mut self,
5099ac24 1259 ct: ty::Const<'tcx>,
dfeec247 1260 print_ty: bool,
dc9dc135
XL
1261 ) -> Result<Self::Const, Self::Error> {
1262 define_scoped_cx!(self);
1263
6522a427 1264 if self.should_print_verbose() {
923072b8 1265 p!(write("Const({:?}: {:?})", ct.kind(), ct.ty()));
dc9dc135
XL
1266 return Ok(self);
1267 }
e74abb32 1268
dfeec247
XL
1269 macro_rules! print_underscore {
1270 () => {{
dfeec247 1271 if print_ty {
ba9703b0
XL
1272 self = self.typed_value(
1273 |mut this| {
1274 write!(this, "_")?;
1275 Ok(this)
1276 },
5099ac24 1277 |this| this.print_type(ct.ty()),
ba9703b0
XL
1278 ": ",
1279 )?;
1280 } else {
1281 write!(self, "_")?;
dfeec247
XL
1282 }
1283 }};
1284 }
1285
923072b8 1286 match ct.kind() {
2b03887a 1287 ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => {
5099ac24 1288 match self.tcx().def_kind(def.did) {
6522a427 1289 DefKind::Const | DefKind::AssocConst => {
5099ac24
FG
1290 p!(print_value_path(def.did, substs))
1291 }
6522a427
EL
1292 DefKind::AnonConst => {
1293 if def.is_local()
1294 && let span = self.tcx().def_span(def.did)
1295 && let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span)
1296 {
1297 p!(write("{}", snip))
5099ac24 1298 } else {
6522a427
EL
1299 // Do not call `print_value_path` as if a parent of this anon const is an impl it will
1300 // attempt to print out the impl trait ref i.e. `<T as Trait>::{constant#0}`. This would
1301 // cause printing to enter an infinite recursion if the anon const is in the self type i.e.
1302 // `impl<T: Default> Default for [T; 32 - 1 - 1 - 1] {`
1303 // where we would try to print `<[T; /* print `constant#0` again */] as Default>::{constant#0}`
1304 p!(write("{}::{}", self.tcx().crate_name(def.did.krate), self.tcx().def_path(def.did).to_string_no_crate_verbose()))
e74abb32 1305 }
dfeec247 1306 }
6522a427 1307 defkind => bug!("`{:?}` has unexpcted defkind {:?}", ct, defkind),
e74abb32 1308 }
dfeec247 1309 }
5099ac24
FG
1310 ty::ConstKind::Infer(infer_ct) => {
1311 match infer_ct {
1312 ty::InferConst::Var(ct_vid)
1313 if let Some(name) = self.const_infer_name(ct_vid) =>
1314 p!(write("{}", name)),
1315 _ => print_underscore!(),
1316 }
1317 }
ba9703b0
XL
1318 ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
1319 ty::ConstKind::Value(value) => {
923072b8 1320 return self.pretty_print_const_valtree(value, ct.ty(), print_ty);
dfeec247 1321 }
60c5eb7d 1322
ba9703b0
XL
1323 ty::ConstKind::Bound(debruijn, bound_var) => {
1324 self.pretty_print_bound_var(debruijn, bound_var)?
60c5eb7d 1325 }
ba9703b0 1326 ty::ConstKind::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)),
6522a427
EL
1327 // FIXME(generic_const_exprs):
1328 // write out some legible representation of an abstract const?
1329 ty::ConstKind::Expr(_) => p!("[const expr]"),
29967ef6 1330 ty::ConstKind::Error(_) => p!("[const error]"),
60c5eb7d
XL
1331 };
1332 Ok(self)
1333 }
1334
ba9703b0 1335 fn pretty_print_const_scalar(
6a06907d 1336 self,
ba9703b0 1337 scalar: Scalar,
60c5eb7d 1338 ty: Ty<'tcx>,
dfeec247 1339 print_ty: bool,
6a06907d
XL
1340 ) -> Result<Self::Const, Self::Error> {
1341 match scalar {
136023e0 1342 Scalar::Ptr(ptr, _size) => self.pretty_print_const_scalar_ptr(ptr, ty, print_ty),
6a06907d
XL
1343 Scalar::Int(int) => self.pretty_print_const_scalar_int(int, ty, print_ty),
1344 }
1345 }
1346
1347 fn pretty_print_const_scalar_ptr(
1348 mut self,
1349 ptr: Pointer,
1350 ty: Ty<'tcx>,
1351 print_ty: bool,
60c5eb7d
XL
1352 ) -> Result<Self::Const, Self::Error> {
1353 define_scoped_cx!(self);
1354
136023e0 1355 let (alloc_id, offset) = ptr.into_parts();
6a06907d 1356 match ty.kind() {
ba9703b0 1357 // Byte strings (&[u8; N])
04454e1e
FG
1358 ty::Ref(_, inner, _) => {
1359 if let ty::Array(elem, len) = inner.kind() {
1360 if let ty::Uint(ty::UintTy::U8) = elem.kind() {
923072b8 1361 if let ty::ConstKind::Value(ty::ValTree::Leaf(int)) = len.kind() {
064997fb 1362 match self.tcx().try_get_global_alloc(alloc_id) {
04454e1e
FG
1363 Some(GlobalAlloc::Memory(alloc)) => {
1364 let len = int.assert_bits(self.tcx().data_layout.pointer_size);
1365 let range =
1366 AllocRange { start: offset, size: Size::from_bytes(len) };
1367 if let Ok(byte_str) =
f2b60f7d 1368 alloc.inner().get_bytes_strip_provenance(&self.tcx(), range)
04454e1e
FG
1369 {
1370 p!(pretty_print_byte_str(byte_str))
1371 } else {
1372 p!("<too short allocation>")
1373 }
1374 }
064997fb 1375 // FIXME: for statics, vtables, and functions, we could in principle print more detail.
04454e1e
FG
1376 Some(GlobalAlloc::Static(def_id)) => {
1377 p!(write("<static({:?})>", def_id))
1378 }
1379 Some(GlobalAlloc::Function(_)) => p!("<function>"),
064997fb 1380 Some(GlobalAlloc::VTable(..)) => p!("<vtable>"),
04454e1e
FG
1381 None => p!("<dangling pointer>"),
1382 }
1383 return Ok(self);
1384 }
f9f354fc
XL
1385 }
1386 }
04454e1e 1387 }
6a06907d
XL
1388 ty::FnPtr(_) => {
1389 // FIXME: We should probably have a helper method to share code with the "Byte strings"
1390 // printing above (which also has to handle pointers to all sorts of things).
064997fb
FG
1391 if let Some(GlobalAlloc::Function(instance)) =
1392 self.tcx().try_get_global_alloc(alloc_id)
04454e1e
FG
1393 {
1394 self = self.typed_value(
1395 |this| this.print_value_path(instance.def_id(), instance.substs),
1396 |this| this.print_type(ty),
1397 " as ",
1398 )?;
1399 return Ok(self);
6a06907d
XL
1400 }
1401 }
04454e1e 1402 _ => {}
6a06907d 1403 }
04454e1e
FG
1404 // Any pointer values not covered by a branch above
1405 self = self.pretty_print_const_pointer(ptr, ty, print_ty)?;
6a06907d
XL
1406 Ok(self)
1407 }
1408
1409 fn pretty_print_const_scalar_int(
1410 mut self,
1411 int: ScalarInt,
1412 ty: Ty<'tcx>,
1413 print_ty: bool,
1414 ) -> Result<Self::Const, Self::Error> {
1415 define_scoped_cx!(self);
1416
1417 match ty.kind() {
ba9703b0 1418 // Bool
6a06907d
XL
1419 ty::Bool if int == ScalarInt::FALSE => p!("false"),
1420 ty::Bool if int == ScalarInt::TRUE => p!("true"),
ba9703b0 1421 // Float
6a06907d 1422 ty::Float(ty::FloatTy::F32) => {
29967ef6 1423 p!(write("{}f32", Single::try_from(int).unwrap()))
dfeec247 1424 }
6a06907d 1425 ty::Float(ty::FloatTy::F64) => {
29967ef6 1426 p!(write("{}f64", Double::try_from(int).unwrap()))
dfeec247 1427 }
ba9703b0 1428 // Int
6a06907d 1429 ty::Uint(_) | ty::Int(_) => {
29967ef6
XL
1430 let int =
1431 ConstInt::new(int, matches!(ty.kind(), ty::Int(_)), ty.is_ptr_sized_integral());
f035d41b 1432 if print_ty { p!(write("{:#?}", int)) } else { p!(write("{:?}", int)) }
dfeec247 1433 }
ba9703b0 1434 // Char
6a06907d 1435 ty::Char if char::try_from(int).is_ok() => {
29967ef6 1436 p!(write("{:?}", char::try_from(int).unwrap()))
ba9703b0 1437 }
136023e0
XL
1438 // Pointer types
1439 ty::Ref(..) | ty::RawPtr(_) | ty::FnPtr(_) => {
29967ef6 1440 let data = int.assert_bits(self.tcx().data_layout.pointer_size);
ba9703b0
XL
1441 self = self.typed_value(
1442 |mut this| {
1443 write!(this, "0x{:x}", data)?;
1444 Ok(this)
1445 },
1446 |this| this.print_type(ty),
1447 " as ",
1448 )?;
dfeec247 1449 }
ba9703b0 1450 // Nontrivial types with scalar bit representation
6a06907d 1451 _ => {
ba9703b0 1452 let print = |mut this: Self| {
29967ef6 1453 if int.size() == Size::ZERO {
ba9703b0 1454 write!(this, "transmute(())")?;
416331ca 1455 } else {
29967ef6 1456 write!(this, "transmute(0x{:x})", int)?;
dc9dc135 1457 }
ba9703b0
XL
1458 Ok(this)
1459 };
1460 self = if print_ty {
1461 self.typed_value(print, |this| this.print_type(ty), ": ")?
e74abb32 1462 } else {
ba9703b0 1463 print(self)?
e74abb32 1464 };
ba9703b0 1465 }
ba9703b0
XL
1466 }
1467 Ok(self)
1468 }
1469
1470 /// This is overridden for MIR printing because we only want to hide alloc ids from users, not
1471 /// from MIR where it is actually useful.
064997fb 1472 fn pretty_print_const_pointer<Prov: Provenance>(
ba9703b0 1473 mut self,
064997fb 1474 _: Pointer<Prov>,
ba9703b0
XL
1475 ty: Ty<'tcx>,
1476 print_ty: bool,
1477 ) -> Result<Self::Const, Self::Error> {
1478 if print_ty {
1479 self.typed_value(
1480 |mut this| {
1481 this.write_str("&_")?;
1482 Ok(this)
1483 },
1484 |this| this.print_type(ty),
1485 ": ",
1486 )
1487 } else {
1488 self.write_str("&_")?;
1489 Ok(self)
1490 }
1491 }
1492
1493 fn pretty_print_byte_str(mut self, byte_str: &'tcx [u8]) -> Result<Self::Const, Self::Error> {
f2b60f7d 1494 write!(self, "b\"{}\"", byte_str.escape_ascii())?;
ba9703b0
XL
1495 Ok(self)
1496 }
1497
923072b8 1498 fn pretty_print_const_valtree(
ba9703b0 1499 mut self,
923072b8 1500 valtree: ty::ValTree<'tcx>,
ba9703b0
XL
1501 ty: Ty<'tcx>,
1502 print_ty: bool,
1503 ) -> Result<Self::Const, Self::Error> {
1504 define_scoped_cx!(self);
1505
6522a427 1506 if self.should_print_verbose() {
923072b8 1507 p!(write("ValTree({:?}: ", valtree), print(ty), ")");
ba9703b0
XL
1508 return Ok(self);
1509 }
1510
1511 let u8_type = self.tcx().types.u8;
923072b8
FG
1512 match (valtree, ty.kind()) {
1513 (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
1514 ty::Slice(t) if *t == u8_type => {
1515 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1516 bug!(
1517 "expected to convert valtree {:?} to raw bytes for type {:?}",
1518 valtree,
1519 t
1520 )
1521 });
1522 return self.pretty_print_byte_str(bytes);
04454e1e 1523 }
923072b8
FG
1524 ty::Str => {
1525 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
1526 bug!("expected to convert valtree to raw bytes for type {:?}", ty)
1527 });
1528 p!(write("{:?}", String::from_utf8_lossy(bytes)));
1529 return Ok(self);
1530 }
064997fb
FG
1531 _ => {
1532 p!("&");
1533 p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty));
1534 return Ok(self);
1535 }
923072b8
FG
1536 },
1537 (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
064997fb 1538 let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
923072b8
FG
1539 bug!("expected to convert valtree to raw bytes for type {:?}", t)
1540 });
29967ef6 1541 p!("*");
923072b8 1542 p!(pretty_print_byte_str(bytes));
04454e1e 1543 return Ok(self);
ba9703b0 1544 }
ba9703b0 1545 // Aggregates, printed as array/tuple/struct/variant construction syntax.
923072b8 1546 (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
6522a427 1547 let contents = self.tcx().destructure_const(self.tcx().mk_const(valtree, ty));
ba9703b0 1548 let fields = contents.fields.iter().copied();
1b1a35ee 1549 match *ty.kind() {
ba9703b0 1550 ty::Array(..) => {
29967ef6 1551 p!("[", comma_sep(fields), "]");
ba9703b0
XL
1552 }
1553 ty::Tuple(..) => {
29967ef6 1554 p!("(", comma_sep(fields));
ba9703b0 1555 if contents.fields.len() == 1 {
29967ef6 1556 p!(",");
ba9703b0 1557 }
29967ef6 1558 p!(")");
dfeec247 1559 }
5e7ed085 1560 ty::Adt(def, _) if def.variants().is_empty() => {
94222f64
XL
1561 self = self.typed_value(
1562 |mut this| {
1563 write!(this, "unreachable()")?;
1564 Ok(this)
1565 },
1566 |this| this.print_type(ty),
1567 ": ",
1568 )?;
f035d41b 1569 }
ba9703b0 1570 ty::Adt(def, substs) => {
94222f64
XL
1571 let variant_idx =
1572 contents.variant.expect("destructed const of adt without variant idx");
5e7ed085 1573 let variant_def = &def.variant(variant_idx);
ba9703b0 1574 p!(print_value_path(variant_def.def_id, substs));
6522a427
EL
1575 match variant_def.ctor_kind() {
1576 Some(CtorKind::Const) => {}
1577 Some(CtorKind::Fn) => {
29967ef6 1578 p!("(", comma_sep(fields), ")");
ba9703b0 1579 }
6522a427 1580 None => {
29967ef6 1581 p!(" {{ ");
ba9703b0 1582 let mut first = true;
cdc7bbd5 1583 for (field_def, field) in iter::zip(&variant_def.fields, fields) {
ba9703b0 1584 if !first {
29967ef6 1585 p!(", ");
ba9703b0 1586 }
5099ac24 1587 p!(write("{}: ", field_def.name), print(field));
ba9703b0
XL
1588 first = false;
1589 }
29967ef6 1590 p!(" }}");
ba9703b0
XL
1591 }
1592 }
1593 }
1594 _ => unreachable!(),
dc9dc135 1595 }
04454e1e 1596 return Ok(self);
dc9dc135 1597 }
f2b60f7d
FG
1598 (ty::ValTree::Leaf(leaf), ty::Ref(_, inner_ty, _)) => {
1599 p!(write("&"));
1600 return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty);
1601 }
923072b8
FG
1602 (ty::ValTree::Leaf(leaf), _) => {
1603 return self.pretty_print_const_scalar_int(leaf, ty, print_ty);
04454e1e 1604 }
ba9703b0
XL
1605 // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading
1606 // their fields instead of just dumping the memory.
04454e1e
FG
1607 _ => {}
1608 }
1609
1610 // fallback
923072b8
FG
1611 if valtree == ty::ValTree::zst() {
1612 p!(write("<ZST>"));
1613 } else {
1614 p!(write("{:?}", valtree));
1615 }
04454e1e
FG
1616 if print_ty {
1617 p!(": ", print(ty));
ba9703b0 1618 }
04454e1e 1619 Ok(self)
dc9dc135 1620 }
f2b60f7d
FG
1621
1622 fn pretty_closure_as_impl(
1623 mut self,
1624 closure: ty::ClosureSubsts<'tcx>,
1625 ) -> Result<Self::Const, Self::Error> {
1626 let sig = closure.sig();
1627 let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn);
1628
1629 write!(self, "impl ")?;
1630 self.wrap_binder(&sig, |sig, mut cx| {
1631 define_scoped_cx!(cx);
1632
1633 p!(print(kind), "(");
1634 for (i, arg) in sig.inputs()[0].tuple_fields().iter().enumerate() {
1635 if i > 0 {
1636 p!(", ");
1637 }
1638 p!(print(arg));
1639 }
1640 p!(")");
1641
1642 if !sig.output().is_unit() {
1643 p!(" -> ", print(sig.output()));
1644 }
1645
1646 Ok(cx)
1647 })
1648 }
6522a427
EL
1649
1650 fn should_print_verbose(&self) -> bool {
1651 self.tcx().sess.verbose()
1652 }
532ac7d7
XL
1653}
1654
1655// HACK(eddyb) boxed to avoid moving around a large struct by-value.
5e7ed085 1656pub struct FmtPrinter<'a, 'tcx>(Box<FmtPrinterData<'a, 'tcx>>);
532ac7d7 1657
5e7ed085 1658pub struct FmtPrinterData<'a, 'tcx> {
dc9dc135 1659 tcx: TyCtxt<'tcx>,
5e7ed085 1660 fmt: String,
532ac7d7
XL
1661
1662 empty_path: bool,
1663 in_value: bool,
ba9703b0 1664 pub print_alloc_ids: bool,
532ac7d7 1665
2b03887a 1666 // set of all named (non-anonymous) region names
e74abb32 1667 used_region_names: FxHashSet<Symbol>,
2b03887a 1668
532ac7d7
XL
1669 region_index: usize,
1670 binder_depth: usize,
6c58768f 1671 printed_type_count: usize,
6522a427
EL
1672 type_length_limit: Limit,
1673 truncated: bool,
532ac7d7 1674
5099ac24 1675 pub region_highlight_mode: RegionHighlightMode<'tcx>,
dc9dc135 1676
064997fb
FG
1677 pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<Symbol> + 'a>>,
1678 pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<Symbol> + 'a>>,
532ac7d7
XL
1679}
1680
5e7ed085
FG
1681impl<'a, 'tcx> Deref for FmtPrinter<'a, 'tcx> {
1682 type Target = FmtPrinterData<'a, 'tcx>;
532ac7d7
XL
1683 fn deref(&self) -> &Self::Target {
1684 &self.0
1685 }
1686}
1687
5e7ed085 1688impl DerefMut for FmtPrinter<'_, '_> {
532ac7d7
XL
1689 fn deref_mut(&mut self) -> &mut Self::Target {
1690 &mut self.0
1691 }
1692}
1693
5e7ed085
FG
1694impl<'a, 'tcx> FmtPrinter<'a, 'tcx> {
1695 pub fn new(tcx: TyCtxt<'tcx>, ns: Namespace) -> Self {
6522a427
EL
1696 Self::new_with_limit(tcx, ns, tcx.type_length_limit())
1697 }
1698
1699 pub fn new_with_limit(tcx: TyCtxt<'tcx>, ns: Namespace, type_length_limit: Limit) -> Self {
532ac7d7
XL
1700 FmtPrinter(Box::new(FmtPrinterData {
1701 tcx,
5e7ed085
FG
1702 // Estimated reasonable capacity to allocate upfront based on a few
1703 // benchmarks.
1704 fmt: String::with_capacity(64),
532ac7d7
XL
1705 empty_path: false,
1706 in_value: ns == Namespace::ValueNS,
ba9703b0 1707 print_alloc_ids: false,
532ac7d7
XL
1708 used_region_names: Default::default(),
1709 region_index: 0,
1710 binder_depth: 0,
6c58768f 1711 printed_type_count: 0,
6522a427
EL
1712 type_length_limit,
1713 truncated: false,
5099ac24
FG
1714 region_highlight_mode: RegionHighlightMode::new(tcx),
1715 ty_infer_name_resolver: None,
1716 const_infer_name_resolver: None,
532ac7d7
XL
1717 }))
1718 }
5e7ed085
FG
1719
1720 pub fn into_buffer(self) -> String {
1721 self.0.fmt
1722 }
532ac7d7
XL
1723}
1724
dfeec247
XL
1725// HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1726// (but also some things just print a `DefId` generally so maybe we need this?)
1727fn guess_def_namespace(tcx: TyCtxt<'_>, def_id: DefId) -> Namespace {
1728 match tcx.def_key(def_id).disambiguated_data.data {
1729 DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => {
1730 Namespace::TypeNS
532ac7d7 1731 }
dfeec247
XL
1732
1733 DefPathData::ValueNs(..)
1734 | DefPathData::AnonConst
1735 | DefPathData::ClosureExpr
1736 | DefPathData::Ctor => Namespace::ValueNS,
1737
1738 DefPathData::MacroNs(..) => Namespace::MacroNS,
1739
1740 _ => Namespace::TypeNS,
532ac7d7 1741 }
dfeec247 1742}
532ac7d7 1743
a2a8927a 1744impl<'t> TyCtxt<'t> {
532ac7d7
XL
1745 /// Returns a string identifying this `DefId`. This string is
1746 /// suitable for user output.
1747 pub fn def_path_str(self, def_id: DefId) -> String {
60c5eb7d
XL
1748 self.def_path_str_with_substs(def_id, &[])
1749 }
1750
1751 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
dfeec247 1752 let ns = guess_def_namespace(self, def_id);
532ac7d7 1753 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
5e7ed085 1754 FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer()
532ac7d7 1755 }
6522a427
EL
1756
1757 pub fn value_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1758 let ns = guess_def_namespace(self, def_id);
1759 debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns);
1760 FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer()
1761 }
532ac7d7
XL
1762}
1763
5e7ed085 1764impl fmt::Write for FmtPrinter<'_, '_> {
532ac7d7 1765 fn write_str(&mut self, s: &str) -> fmt::Result {
5e7ed085
FG
1766 self.fmt.push_str(s);
1767 Ok(())
532ac7d7
XL
1768 }
1769}
1770
5e7ed085 1771impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
532ac7d7
XL
1772 type Error = fmt::Error;
1773
1774 type Path = Self;
1775 type Region = Self;
1776 type Type = Self;
1777 type DynExistential = Self;
dc9dc135 1778 type Const = Self;
532ac7d7 1779
a2a8927a 1780 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
532ac7d7
XL
1781 self.tcx
1782 }
1783
1784 fn print_def_path(
1785 mut self,
1786 def_id: DefId,
e74abb32 1787 substs: &'tcx [GenericArg<'tcx>],
532ac7d7
XL
1788 ) -> Result<Self::Path, Self::Error> {
1789 define_scoped_cx!(self);
1790
1791 if substs.is_empty() {
1b1a35ee
XL
1792 match self.try_print_trimmed_def_path(def_id)? {
1793 (cx, true) => return Ok(cx),
1794 (cx, false) => self = cx,
1795 }
1796
532ac7d7
XL
1797 match self.try_print_visible_def_path(def_id)? {
1798 (cx, true) => return Ok(cx),
1799 (cx, false) => self = cx,
1800 }
1801 }
1802
1803 let key = self.tcx.def_key(def_id);
1804 if let DefPathData::Impl = key.disambiguated_data.data {
1805 // Always use types for non-local impls, where types are always
1806 // available, and filename/line-number is mostly uninteresting.
dfeec247
XL
1807 let use_types = !def_id.is_local() || {
1808 // Otherwise, use filename/line-number if forced.
1809 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1810 !force_no_types
1811 };
532ac7d7
XL
1812
1813 if !use_types {
1814 // If no type info is available, fall back to
1815 // pretty printing some span information. This should
1816 // only occur very early in the compiler pipeline.
1817 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1818 let span = self.tcx.def_span(def_id);
1819
1820 self = self.print_def_path(parent_def_id, &[])?;
1821
1822 // HACK(eddyb) copy of `path_append` to avoid
1823 // constructing a `DisambiguatedDefPathData`.
1824 if !self.empty_path {
1825 write!(self, "::")?;
1826 }
17df50a5
XL
1827 write!(
1828 self,
1829 "<impl at {}>",
1830 // This may end up in stderr diagnostics but it may also be emitted
1831 // into MIR. Hence we use the remapped path if available
1832 self.tcx.sess.source_map().span_to_embeddable_string(span)
1833 )?;
532ac7d7
XL
1834 self.empty_path = false;
1835
1836 return Ok(self);
1837 }
1838 }
1839
1840 self.default_print_def_path(def_id, substs)
1841 }
1842
923072b8 1843 fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> {
532ac7d7
XL
1844 self.pretty_print_region(region)
1845 }
1846
6c58768f 1847 fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
6522a427 1848 if self.type_length_limit.value_within_limit(self.printed_type_count) {
6c58768f
XL
1849 self.printed_type_count += 1;
1850 self.pretty_print_type(ty)
1851 } else {
6522a427 1852 self.truncated = true;
6c58768f
XL
1853 write!(self, "...")?;
1854 Ok(self)
1855 }
532ac7d7
XL
1856 }
1857
1858 fn print_dyn_existential(
1859 self,
6522a427 1860 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
532ac7d7
XL
1861 ) -> Result<Self::DynExistential, Self::Error> {
1862 self.pretty_print_dyn_existential(predicates)
1863 }
1864
5099ac24 1865 fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
064997fb 1866 self.pretty_print_const(ct, false)
dc9dc135
XL
1867 }
1868
dfeec247 1869 fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
532ac7d7
XL
1870 self.empty_path = true;
1871 if cnum == LOCAL_CRATE {
1872 if self.tcx.sess.rust_2018() {
1873 // We add the `crate::` keyword on Rust 2018, only when desired.
1874 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
dc9dc135 1875 write!(self, "{}", kw::Crate)?;
532ac7d7
XL
1876 self.empty_path = false;
1877 }
1878 }
1879 } else {
1880 write!(self, "{}", self.tcx.crate_name(cnum))?;
1881 self.empty_path = false;
1882 }
1883 Ok(self)
1884 }
e1599b0c 1885
532ac7d7
XL
1886 fn path_qualified(
1887 mut self,
1888 self_ty: Ty<'tcx>,
1889 trait_ref: Option<ty::TraitRef<'tcx>>,
1890 ) -> Result<Self::Path, Self::Error> {
1891 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1892 self.empty_path = false;
1893 Ok(self)
1894 }
1895
1896 fn path_append_impl(
1897 mut self,
1898 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1899 _disambiguated_data: &DisambiguatedDefPathData,
1900 self_ty: Ty<'tcx>,
1901 trait_ref: Option<ty::TraitRef<'tcx>>,
1902 ) -> Result<Self::Path, Self::Error> {
dfeec247
XL
1903 self = self.pretty_path_append_impl(
1904 |mut cx| {
1905 cx = print_prefix(cx)?;
1906 if !cx.empty_path {
1907 write!(cx, "::")?;
1908 }
532ac7d7 1909
dfeec247
XL
1910 Ok(cx)
1911 },
1912 self_ty,
1913 trait_ref,
1914 )?;
532ac7d7
XL
1915 self.empty_path = false;
1916 Ok(self)
1917 }
e1599b0c 1918
532ac7d7
XL
1919 fn path_append(
1920 mut self,
1921 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1922 disambiguated_data: &DisambiguatedDefPathData,
1923 ) -> Result<Self::Path, Self::Error> {
1924 self = print_prefix(self)?;
1925
a2a8927a
XL
1926 // Skip `::{{extern}}` blocks and `::{{constructor}}` on tuple/unit structs.
1927 if let DefPathData::ForeignMod | DefPathData::Ctor = disambiguated_data.data {
ba9703b0 1928 return Ok(self);
532ac7d7
XL
1929 }
1930
1b1a35ee 1931 let name = disambiguated_data.data.name();
a2a8927a
XL
1932 if !self.empty_path {
1933 write!(self, "::")?;
1934 }
532ac7d7 1935
a2a8927a
XL
1936 if let DefPathDataName::Named(name) = name {
1937 if Ident::with_dummy_span(name).is_raw_guess() {
1938 write!(self, "r#")?;
532ac7d7 1939 }
a2a8927a 1940 }
532ac7d7 1941
6522a427 1942 let verbose = self.should_print_verbose();
a2a8927a 1943 disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1b1a35ee 1944
a2a8927a 1945 self.empty_path = false;
532ac7d7
XL
1946
1947 Ok(self)
1948 }
e1599b0c 1949
532ac7d7
XL
1950 fn path_generic_args(
1951 mut self,
1952 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
e74abb32 1953 args: &[GenericArg<'tcx>],
532ac7d7
XL
1954 ) -> Result<Self::Path, Self::Error> {
1955 self = print_prefix(self)?;
1956
2b03887a 1957 if args.first().is_some() {
532ac7d7
XL
1958 if self.in_value {
1959 write!(self, "::")?;
1960 }
2b03887a 1961 self.generic_delimiters(|cx| cx.comma_sep(args.iter().cloned()))
532ac7d7
XL
1962 } else {
1963 Ok(self)
1964 }
1965 }
1966}
1967
5e7ed085 1968impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> {
064997fb 1969 fn ty_infer_name(&self, id: ty::TyVid) -> Option<Symbol> {
5099ac24
FG
1970 self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
1971 }
1972
6522a427
EL
1973 fn reset_type_limit(&mut self) {
1974 self.printed_type_count = 0;
1975 }
1976
064997fb 1977 fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<Symbol> {
5099ac24 1978 self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
dc9dc135
XL
1979 }
1980
532ac7d7
XL
1981 fn print_value_path(
1982 mut self,
1983 def_id: DefId,
e74abb32 1984 substs: &'tcx [GenericArg<'tcx>],
532ac7d7
XL
1985 ) -> Result<Self::Path, Self::Error> {
1986 let was_in_value = std::mem::replace(&mut self.in_value, true);
1987 self = self.print_def_path(def_id, substs)?;
1988 self.in_value = was_in_value;
1989
1990 Ok(self)
1991 }
1992
cdc7bbd5 1993 fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error>
dc9dc135
XL
1994 where
1995 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
532ac7d7
XL
1996 {
1997 self.pretty_in_binder(value)
1998 }
1999
064997fb 2000 fn wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, Self::Error>>(
fc512014 2001 self,
cdc7bbd5 2002 value: &ty::Binder<'tcx, T>,
fc512014
XL
2003 f: C,
2004 ) -> Result<Self, Self::Error>
2005 where
2006 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
2007 {
2008 self.pretty_wrap_binder(value, f)
2009 }
2010
ba9703b0
XL
2011 fn typed_value(
2012 mut self,
2013 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
2014 t: impl FnOnce(Self) -> Result<Self, Self::Error>,
2015 conversion: &str,
2016 ) -> Result<Self::Const, Self::Error> {
2017 self.write_str("{")?;
2018 self = f(self)?;
2019 self.write_str(conversion)?;
2020 let was_in_value = std::mem::replace(&mut self.in_value, false);
2021 self = t(self)?;
2022 self.in_value = was_in_value;
2023 self.write_str("}")?;
2024 Ok(self)
2025 }
2026
532ac7d7
XL
2027 fn generic_delimiters(
2028 mut self,
2029 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
2030 ) -> Result<Self, Self::Error> {
2031 write!(self, "<")?;
2032
2033 let was_in_value = std::mem::replace(&mut self.in_value, false);
2034 let mut inner = f(self)?;
2035 inner.in_value = was_in_value;
2036
2037 write!(inner, ">")?;
2038 Ok(inner)
2039 }
2040
923072b8 2041 fn should_print_region(&self, region: ty::Region<'tcx>) -> bool {
532ac7d7
XL
2042 let highlight = self.region_highlight_mode;
2043 if highlight.region_highlighted(region).is_some() {
2044 return true;
2045 }
2046
6522a427 2047 if self.should_print_verbose() {
532ac7d7
XL
2048 return true;
2049 }
2050
064997fb 2051 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
532ac7d7
XL
2052
2053 match *region {
6522a427 2054 ty::ReEarlyBound(ref data) => data.has_name(),
532ac7d7 2055
cdc7bbd5 2056 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
dfeec247
XL
2057 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2058 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
6522a427
EL
2059 if br.is_named() {
2060 return true;
532ac7d7
XL
2061 }
2062
2063 if let Some((region, _)) = highlight.highlight_bound_region {
2064 if br == region {
2065 return true;
2066 }
2067 }
2068
2069 false
2070 }
2071
f9f354fc 2072 ty::ReVar(_) if identify_regions => true,
532ac7d7 2073
f9f354fc 2074 ty::ReVar(_) | ty::ReErased => false,
532ac7d7 2075
f2b60f7d 2076 ty::ReStatic => true,
ba9703b0
XL
2077 }
2078 }
2079
064997fb 2080 fn pretty_print_const_pointer<Prov: Provenance>(
ba9703b0 2081 self,
064997fb 2082 p: Pointer<Prov>,
ba9703b0
XL
2083 ty: Ty<'tcx>,
2084 print_ty: bool,
2085 ) -> Result<Self::Const, Self::Error> {
2086 let print = |mut this: Self| {
2087 define_scoped_cx!(this);
2088 if this.print_alloc_ids {
2089 p!(write("{:?}", p));
2090 } else {
29967ef6 2091 p!("&_");
ba9703b0
XL
2092 }
2093 Ok(this)
2094 };
2095 if print_ty {
2096 self.typed_value(print, |this| this.print_type(ty), ": ")
2097 } else {
2098 print(self)
532ac7d7
XL
2099 }
2100 }
2101}
2102
2103// HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
923072b8
FG
2104impl<'tcx> FmtPrinter<'_, 'tcx> {
2105 pub fn pretty_print_region(mut self, region: ty::Region<'tcx>) -> Result<Self, fmt::Error> {
532ac7d7
XL
2106 define_scoped_cx!(self);
2107
2108 // Watch out for region highlights.
2109 let highlight = self.region_highlight_mode;
2110 if let Some(n) = highlight.region_highlighted(region) {
2111 p!(write("'{}", n));
2112 return Ok(self);
2113 }
2114
6522a427 2115 if self.should_print_verbose() {
532ac7d7
XL
2116 p!(write("{:?}", region));
2117 return Ok(self);
2118 }
2119
064997fb 2120 let identify_regions = self.tcx.sess.opts.unstable_opts.identify_regions;
532ac7d7 2121
6522a427 2122 // These printouts are concise. They do not contain all the information
532ac7d7 2123 // the user might want to diagnose an error, but there is basically no way
6522a427 2124 // to fit that into a short string. Hence the recommendation to use
532ac7d7
XL
2125 // `explain_region()` or `note_and_explain_region()`.
2126 match *region {
2127 ty::ReEarlyBound(ref data) => {
5869c6ff 2128 if data.name != kw::Empty {
532ac7d7
XL
2129 p!(write("{}", data.name));
2130 return Ok(self);
2131 }
2132 }
cdc7bbd5 2133 ty::ReLateBound(_, ty::BoundRegion { kind: br, .. })
dfeec247
XL
2134 | ty::ReFree(ty::FreeRegion { bound_region: br, .. })
2135 | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
6522a427
EL
2136 if let ty::BrNamed(_, name) = br && br.is_named() {
2137 p!(write("{}", name));
2138 return Ok(self);
532ac7d7
XL
2139 }
2140
2141 if let Some((region, counter)) = highlight.highlight_bound_region {
2142 if br == region {
2143 p!(write("'{}", counter));
2144 return Ok(self);
2145 }
2146 }
2147 }
532ac7d7
XL
2148 ty::ReVar(region_vid) if identify_regions => {
2149 p!(write("{:?}", region_vid));
2150 return Ok(self);
2151 }
2152 ty::ReVar(_) => {}
f9f354fc 2153 ty::ReErased => {}
532ac7d7 2154 ty::ReStatic => {
29967ef6 2155 p!("'static");
532ac7d7
XL
2156 return Ok(self);
2157 }
532ac7d7
XL
2158 }
2159
29967ef6 2160 p!("'_");
532ac7d7
XL
2161
2162 Ok(self)
2163 }
2164}
2165
136023e0
XL
2166/// Folds through bound vars and placeholders, naming them
2167struct RegionFolder<'a, 'tcx> {
2168 tcx: TyCtxt<'tcx>,
2169 current_index: ty::DebruijnIndex,
2170 region_map: BTreeMap<ty::BoundRegion, ty::Region<'tcx>>,
2b03887a
FG
2171 name: &'a mut (
2172 dyn FnMut(
2173 Option<ty::DebruijnIndex>, // Debruijn index of the folded late-bound region
2174 ty::DebruijnIndex, // Index corresponding to binder level
2175 ty::BoundRegion,
2176 ) -> ty::Region<'tcx>
2177 + 'a
2178 ),
136023e0
XL
2179}
2180
2181impl<'a, 'tcx> ty::TypeFolder<'tcx> for RegionFolder<'a, 'tcx> {
2182 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
2183 self.tcx
2184 }
2185
2186 fn fold_binder<T: TypeFoldable<'tcx>>(
2187 &mut self,
2188 t: ty::Binder<'tcx, T>,
2189 ) -> ty::Binder<'tcx, T> {
2190 self.current_index.shift_in(1);
2191 let t = t.super_fold_with(self);
2192 self.current_index.shift_out(1);
2193 t
2194 }
2195
2196 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
2197 match *t.kind() {
2198 _ if t.has_vars_bound_at_or_above(self.current_index) || t.has_placeholders() => {
2199 return t.super_fold_with(self);
2200 }
2201 _ => {}
2202 }
2203 t
2204 }
2205
2206 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
2207 let name = &mut self.name;
2208 let region = match *r {
2b03887a
FG
2209 ty::ReLateBound(db, br) if db >= self.current_index => {
2210 *self.region_map.entry(br).or_insert_with(|| name(Some(db), self.current_index, br))
2211 }
136023e0
XL
2212 ty::RePlaceholder(ty::PlaceholderRegion { name: kind, .. }) => {
2213 // If this is an anonymous placeholder, don't rename. Otherwise, in some
2214 // async fns, we get a `for<'r> Send` bound
2215 match kind {
6522a427 2216 ty::BrAnon(..) | ty::BrEnv => r,
136023e0
XL
2217 _ => {
2218 // Index doesn't matter, since this is just for naming and these never get bound
2219 let br = ty::BoundRegion { var: ty::BoundVar::from_u32(0), kind };
2b03887a
FG
2220 *self
2221 .region_map
2222 .entry(br)
2223 .or_insert_with(|| name(None, self.current_index, br))
136023e0
XL
2224 }
2225 }
2226 }
2227 _ => return r,
2228 };
2229 if let ty::ReLateBound(debruijn1, br) = *region {
2230 assert_eq!(debruijn1, ty::INNERMOST);
2231 self.tcx.mk_region(ty::ReLateBound(self.current_index, br))
2232 } else {
2233 region
2234 }
2235 }
2236}
2237
532ac7d7
XL
2238// HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
2239// `region_index` and `used_region_names`.
5e7ed085 2240impl<'tcx> FmtPrinter<'_, 'tcx> {
60c5eb7d
XL
2241 pub fn name_all_regions<T>(
2242 mut self,
cdc7bbd5 2243 value: &ty::Binder<'tcx, T>,
136023e0 2244 ) -> Result<(Self, T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>), fmt::Error>
dc9dc135
XL
2245 where
2246 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
532ac7d7 2247 {
2b03887a
FG
2248 fn name_by_region_index(
2249 index: usize,
2250 available_names: &mut Vec<Symbol>,
2251 num_available: usize,
2252 ) -> Symbol {
2253 if let Some(name) = available_names.pop() {
2254 name
2255 } else {
2256 Symbol::intern(&format!("'z{}", index - num_available))
48663c56 2257 }
532ac7d7
XL
2258 }
2259
2b03887a
FG
2260 debug!("name_all_regions");
2261
532ac7d7 2262 // Replace any anonymous late-bound regions with named
e74abb32 2263 // variants, using new unique identifiers, so that we can
532ac7d7
XL
2264 // clearly differentiate between named and unnamed regions in
2265 // the output. We'll probably want to tweak this over time to
2266 // decide just how much information to give.
2267 if self.binder_depth == 0 {
2b03887a 2268 self.prepare_region_info(value);
532ac7d7
XL
2269 }
2270
2b03887a
FG
2271 debug!("self.used_region_names: {:?}", &self.used_region_names);
2272
532ac7d7
XL
2273 let mut empty = true;
2274 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
136023e0
XL
2275 let w = if empty {
2276 empty = false;
2277 start
2278 } else {
2279 cont
2280 };
2281 let _ = write!(cx, "{}", w);
2282 };
2283 let do_continue = |cx: &mut Self, cont: Symbol| {
2284 let _ = write!(cx, "{}", cont);
532ac7d7
XL
2285 };
2286
2287 define_scoped_cx!(self);
2288
6522a427 2289 let possible_names = ('a'..='z').rev().map(|s| Symbol::intern(&format!("'{s}")));
2b03887a
FG
2290
2291 let mut available_names = possible_names
2b03887a
FG
2292 .filter(|name| !self.used_region_names.contains(&name))
2293 .collect::<Vec<_>>();
2294 debug!(?available_names);
2295 let num_available = available_names.len();
2296
60c5eb7d 2297 let mut region_index = self.region_index;
2b03887a
FG
2298 let mut next_name = |this: &Self| {
2299 let mut name;
2300
2301 loop {
2302 name = name_by_region_index(region_index, &mut available_names, num_available);
2303 region_index += 1;
2304
2305 if !this.used_region_names.contains(&name) {
2306 break;
2307 }
923072b8 2308 }
2b03887a
FG
2309
2310 name
923072b8
FG
2311 };
2312
5e7ed085 2313 // If we want to print verbosely, then print *all* binders, even if they
cdc7bbd5
XL
2314 // aren't named. Eventually, we might just want this as the default, but
2315 // this is not *quite* right and changes the ordering of some output
2316 // anyways.
6522a427
EL
2317 let (new_value, map) = if self.should_print_verbose() {
2318 for var in value.bound_vars().iter() {
2319 start_or_continue(&mut self, "for<", ", ");
2320 write!(self, "{:?}", var)?;
2321 }
136023e0 2322 start_or_continue(&mut self, "", "> ");
6522a427 2323 (value.clone().skip_binder(), BTreeMap::default())
cdc7bbd5 2324 } else {
136023e0 2325 let tcx = self.tcx;
2b03887a
FG
2326
2327 // Closure used in `RegionFolder` to create names for anonymous late-bound
2328 // regions. We use two `DebruijnIndex`es (one for the currently folded
2329 // late-bound region and the other for the binder level) to determine
2330 // whether a name has already been created for the currently folded region,
2331 // see issue #102392.
2332 let mut name = |lifetime_idx: Option<ty::DebruijnIndex>,
2333 binder_level_idx: ty::DebruijnIndex,
2334 br: ty::BoundRegion| {
2335 let (name, kind) = match br.kind {
6522a427 2336 ty::BrAnon(..) | ty::BrEnv => {
923072b8 2337 let name = next_name(&self);
2b03887a
FG
2338
2339 if let Some(lt_idx) = lifetime_idx {
2340 if lt_idx > binder_level_idx {
2341 let kind = ty::BrNamed(CRATE_DEF_ID.to_def_id(), name);
2342 return tcx.mk_region(ty::ReLateBound(
2343 ty::INNERMOST,
2344 ty::BoundRegion { var: br.var, kind },
2345 ));
2346 }
2347 }
2348
2349 (name, ty::BrNamed(CRATE_DEF_ID.to_def_id(), name))
cdc7bbd5 2350 }
6522a427 2351 ty::BrNamed(def_id, kw::UnderscoreLifetime | kw::Empty) => {
923072b8 2352 let name = next_name(&self);
2b03887a
FG
2353
2354 if let Some(lt_idx) = lifetime_idx {
2355 if lt_idx > binder_level_idx {
2356 let kind = ty::BrNamed(def_id, name);
2357 return tcx.mk_region(ty::ReLateBound(
2358 ty::INNERMOST,
2359 ty::BoundRegion { var: br.var, kind },
2360 ));
2361 }
2362 }
2363
2364 (name, ty::BrNamed(def_id, name))
923072b8
FG
2365 }
2366 ty::BrNamed(_, name) => {
2b03887a
FG
2367 if let Some(lt_idx) = lifetime_idx {
2368 if lt_idx > binder_level_idx {
2369 let kind = br.kind;
2370 return tcx.mk_region(ty::ReLateBound(
2371 ty::INNERMOST,
2372 ty::BoundRegion { var: br.var, kind },
2373 ));
2374 }
2375 }
2376
2377 (name, br.kind)
923072b8 2378 }
cdc7bbd5 2379 };
2b03887a
FG
2380
2381 start_or_continue(&mut self, "for<", ", ");
2382 do_continue(&mut self, name);
136023e0
XL
2383 tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BoundRegion { var: br.var, kind }))
2384 };
2385 let mut folder = RegionFolder {
2386 tcx,
2387 current_index: ty::INNERMOST,
2388 name: &mut name,
2389 region_map: BTreeMap::new(),
2390 };
2391 let new_value = value.clone().skip_binder().fold_with(&mut folder);
2392 let region_map = folder.region_map;
2393 start_or_continue(&mut self, "", "> ");
2394 (new_value, region_map)
cdc7bbd5 2395 };
532ac7d7
XL
2396
2397 self.binder_depth += 1;
2398 self.region_index = region_index;
136023e0 2399 Ok((self, new_value, map))
60c5eb7d
XL
2400 }
2401
cdc7bbd5 2402 pub fn pretty_in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, fmt::Error>
60c5eb7d
XL
2403 where
2404 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2405 {
2406 let old_region_index = self.region_index;
136023e0
XL
2407 let (new, new_value, _) = self.name_all_regions(value)?;
2408 let mut inner = new_value.print(new)?;
532ac7d7
XL
2409 inner.region_index = old_region_index;
2410 inner.binder_depth -= 1;
2411 Ok(inner)
2412 }
2413
064997fb 2414 pub fn pretty_wrap_binder<T, C: FnOnce(&T, Self) -> Result<Self, fmt::Error>>(
fc512014 2415 self,
cdc7bbd5 2416 value: &ty::Binder<'tcx, T>,
fc512014
XL
2417 f: C,
2418 ) -> Result<Self, fmt::Error>
2419 where
2420 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
2421 {
2422 let old_region_index = self.region_index;
136023e0
XL
2423 let (new, new_value, _) = self.name_all_regions(value)?;
2424 let mut inner = f(&new_value, new)?;
fc512014
XL
2425 inner.region_index = old_region_index;
2426 inner.binder_depth -= 1;
2427 Ok(inner)
2428 }
2429
2b03887a 2430 fn prepare_region_info<T>(&mut self, value: &ty::Binder<'tcx, T>)
dfeec247 2431 where
064997fb 2432 T: TypeVisitable<'tcx>,
532ac7d7 2433 {
2b03887a
FG
2434 struct RegionNameCollector<'tcx> {
2435 used_region_names: FxHashSet<Symbol>,
cdc7bbd5
XL
2436 type_collector: SsoHashSet<Ty<'tcx>>,
2437 }
2438
2b03887a
FG
2439 impl<'tcx> RegionNameCollector<'tcx> {
2440 fn new() -> Self {
2441 RegionNameCollector {
2442 used_region_names: Default::default(),
2443 type_collector: SsoHashSet::new(),
2444 }
2445 }
2446 }
2447
2448 impl<'tcx> ty::visit::TypeVisitor<'tcx> for RegionNameCollector<'tcx> {
cdc7bbd5
XL
2449 type BreakTy = ();
2450
fc512014 2451 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
5099ac24 2452 trace!("address: {:p}", r.0.0);
2b03887a
FG
2453
2454 // Collect all named lifetimes. These allow us to prevent duplication
2455 // of already existing lifetime names when introducing names for
2456 // anonymous late-bound regions.
2457 if let Some(name) = r.get_name() {
136023e0 2458 self.used_region_names.insert(name);
532ac7d7 2459 }
2b03887a 2460
532ac7d7
XL
2461 r.super_visit_with(self)
2462 }
cdc7bbd5
XL
2463
2464 // We collect types in order to prevent really large types from compiling for
2465 // a really long time. See issue #83150 for why this is necessary.
2466 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
cdc7bbd5
XL
2467 let not_previously_inserted = self.type_collector.insert(ty);
2468 if not_previously_inserted {
2469 ty.super_visit_with(self)
2470 } else {
6522a427 2471 ControlFlow::Continue(())
cdc7bbd5
XL
2472 }
2473 }
532ac7d7
XL
2474 }
2475
2b03887a 2476 let mut collector = RegionNameCollector::new();
532ac7d7 2477 value.visit_with(&mut collector);
2b03887a 2478 self.used_region_names = collector.used_region_names;
532ac7d7
XL
2479 self.region_index = 0;
2480 }
2481}
2482
cdc7bbd5 2483impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<'tcx, T>
dc9dc135
XL
2484where
2485 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
532ac7d7
XL
2486{
2487 type Output = P;
2488 type Error = P::Error;
923072b8 2489
532ac7d7
XL
2490 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
2491 cx.in_binder(self)
2492 }
2493}
2494
dc9dc135
XL
2495impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
2496where
2497 T: Print<'tcx, P, Output = P, Error = P::Error>,
2498 U: Print<'tcx, P, Output = P, Error = P::Error>,
532ac7d7
XL
2499{
2500 type Output = P;
2501 type Error = P::Error;
2502 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
2503 define_scoped_cx!(cx);
29967ef6 2504 p!(print(self.0), ": ", print(self.1));
532ac7d7
XL
2505 Ok(cx)
2506 }
2507}
2508
2509macro_rules! forward_display_to_print {
2510 ($($ty:ty),+) => {
a2a8927a
XL
2511 // Some of the $ty arguments may not actually use 'tcx
2512 $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty {
532ac7d7
XL
2513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2514 ty::tls::with(|tcx| {
5e7ed085 2515 let cx = tcx.lift(*self)
532ac7d7 2516 .expect("could not lift for printing")
5e7ed085
FG
2517 .print(FmtPrinter::new(tcx, Namespace::TypeNS))?;
2518 f.write_str(&cx.into_buffer())?;
532ac7d7
XL
2519 Ok(())
2520 })
2521 }
2522 })+
2523 };
2524}
2525
2526macro_rules! define_print_and_forward_display {
2527 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
dc9dc135 2528 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
532ac7d7
XL
2529 type Output = P;
2530 type Error = fmt::Error;
2531 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
2532 #[allow(unused_mut)]
2533 let mut $cx = $cx;
2534 define_scoped_cx!($cx);
2535 let _: () = $print;
2536 #[allow(unreachable_code)]
2537 Ok($cx)
2538 }
2539 })+
2540
2541 forward_display_to_print!($($ty),+);
2542 };
2543}
2544
60c5eb7d
XL
2545/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2546/// the trait path. That is, it will print `Trait<U>` instead of
2547/// `<T as Trait<U>>`.
064997fb 2548#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
60c5eb7d
XL
2549pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
2550
a2a8927a 2551impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
60c5eb7d
XL
2552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2553 fmt::Display::fmt(self, f)
2554 }
2555}
2556
c295e0f8
XL
2557/// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
2558/// the trait name. That is, it will print `Trait` instead of
2559/// `<T as Trait<U>>`.
064997fb 2560#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
c295e0f8
XL
2561pub struct TraitRefPrintOnlyTraitName<'tcx>(ty::TraitRef<'tcx>);
2562
a2a8927a 2563impl<'tcx> fmt::Debug for TraitRefPrintOnlyTraitName<'tcx> {
c295e0f8
XL
2564 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2565 fmt::Display::fmt(self, f)
2566 }
2567}
2568
a2a8927a 2569impl<'tcx> ty::TraitRef<'tcx> {
60c5eb7d
XL
2570 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
2571 TraitRefPrintOnlyTraitPath(self)
2572 }
c295e0f8
XL
2573
2574 pub fn print_only_trait_name(self) -> TraitRefPrintOnlyTraitName<'tcx> {
2575 TraitRefPrintOnlyTraitName(self)
2576 }
60c5eb7d
XL
2577}
2578
a2a8927a 2579impl<'tcx> ty::Binder<'tcx, ty::TraitRef<'tcx>> {
cdc7bbd5 2580 pub fn print_only_trait_path(self) -> ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>> {
60c5eb7d
XL
2581 self.map_bound(|tr| tr.print_only_trait_path())
2582 }
2583}
2584
064997fb 2585#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
5099ac24
FG
2586pub struct TraitPredPrintModifiersAndPath<'tcx>(ty::TraitPredicate<'tcx>);
2587
2588impl<'tcx> fmt::Debug for TraitPredPrintModifiersAndPath<'tcx> {
2589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2590 fmt::Display::fmt(self, f)
2591 }
2592}
2593
2594impl<'tcx> ty::TraitPredicate<'tcx> {
2595 pub fn print_modifiers_and_trait_path(self) -> TraitPredPrintModifiersAndPath<'tcx> {
2596 TraitPredPrintModifiersAndPath(self)
2597 }
2598}
2599
2600impl<'tcx> ty::PolyTraitPredicate<'tcx> {
2601 pub fn print_modifiers_and_trait_path(
2602 self,
2603 ) -> ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>> {
2604 self.map_bound(TraitPredPrintModifiersAndPath)
2605 }
2606}
2607
f2b60f7d
FG
2608#[derive(Debug, Copy, Clone, TypeFoldable, TypeVisitable, Lift)]
2609pub struct PrintClosureAsImpl<'tcx> {
2610 pub closure: ty::ClosureSubsts<'tcx>,
2611}
2612
532ac7d7 2613forward_display_to_print! {
923072b8 2614 ty::Region<'tcx>,
532ac7d7 2615 Ty<'tcx>,
6522a427 2616 &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
5099ac24 2617 ty::Const<'tcx>,
532ac7d7
XL
2618
2619 // HACK(eddyb) these are exhaustive instead of generic,
dc9dc135 2620 // because `for<'tcx>` isn't possible yet.
6522a427 2621 ty::PolyExistentialPredicate<'tcx>,
cdc7bbd5 2622 ty::Binder<'tcx, ty::TraitRef<'tcx>>,
dc3f5686 2623 ty::Binder<'tcx, ty::ExistentialTraitRef<'tcx>>,
cdc7bbd5 2624 ty::Binder<'tcx, TraitRefPrintOnlyTraitPath<'tcx>>,
c295e0f8 2625 ty::Binder<'tcx, TraitRefPrintOnlyTraitName<'tcx>>,
cdc7bbd5
XL
2626 ty::Binder<'tcx, ty::FnSig<'tcx>>,
2627 ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
5099ac24 2628 ty::Binder<'tcx, TraitPredPrintModifiersAndPath<'tcx>>,
cdc7bbd5
XL
2629 ty::Binder<'tcx, ty::SubtypePredicate<'tcx>>,
2630 ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
2631 ty::Binder<'tcx, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
2632 ty::Binder<'tcx, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
532ac7d7
XL
2633
2634 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
2635 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
2636}
2637
2638define_print_and_forward_display! {
2639 (self, cx):
2640
2641 &'tcx ty::List<Ty<'tcx>> {
29967ef6 2642 p!("{{", comma_sep(self.iter()), "}}")
532ac7d7
XL
2643 }
2644
2645 ty::TypeAndMut<'tcx> {
60c5eb7d 2646 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
532ac7d7
XL
2647 }
2648
2649 ty::ExistentialTraitRef<'tcx> {
2650 // Use a type that can't appear in defaults of type parameters.
48663c56 2651 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
532ac7d7 2652 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
60c5eb7d 2653 p!(print(trait_ref.print_only_trait_path()))
532ac7d7
XL
2654 }
2655
2656 ty::ExistentialProjection<'tcx> {
6522a427 2657 let name = cx.tcx().associated_item(self.def_id).name;
5099ac24 2658 p!(write("{} = ", name), print(self.term))
532ac7d7
XL
2659 }
2660
2661 ty::ExistentialPredicate<'tcx> {
2662 match *self {
2663 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
2664 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
2665 ty::ExistentialPredicate::AutoTrait(def_id) => {
2666 p!(print_def_path(def_id, &[]));
2667 }
2668 }
2669 }
2670
2671 ty::FnSig<'tcx> {
60c5eb7d 2672 p!(write("{}", self.unsafety.prefix_str()));
532ac7d7
XL
2673
2674 if self.abi != Abi::Rust {
2675 p!(write("extern {} ", self.abi));
2676 }
2677
29967ef6 2678 p!("fn", pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
532ac7d7
XL
2679 }
2680
532ac7d7 2681 ty::TraitRef<'tcx> {
60c5eb7d
XL
2682 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
2683 }
2684
2685 TraitRefPrintOnlyTraitPath<'tcx> {
2686 p!(print_def_path(self.0.def_id, self.0.substs));
532ac7d7
XL
2687 }
2688
c295e0f8
XL
2689 TraitRefPrintOnlyTraitName<'tcx> {
2690 p!(print_def_path(self.0.def_id, &[]));
2691 }
2692
5099ac24
FG
2693 TraitPredPrintModifiersAndPath<'tcx> {
2694 if let ty::BoundConstness::ConstIfConst = self.0.constness {
2695 p!("~const ")
2696 }
2697
2698 if let ty::ImplPolarity::Negative = self.0.polarity {
2699 p!("!")
2700 }
2701
2702 p!(print(self.0.trait_ref.print_only_trait_path()));
2703 }
2704
f2b60f7d
FG
2705 PrintClosureAsImpl<'tcx> {
2706 p!(pretty_closure_as_impl(self.closure))
2707 }
2708
532ac7d7
XL
2709 ty::ParamTy {
2710 p!(write("{}", self.name))
2711 }
2712
2713 ty::ParamConst {
2714 p!(write("{}", self.name))
2715 }
2716
2717 ty::SubtypePredicate<'tcx> {
6522a427
EL
2718 p!(print(self.a), " <: ");
2719 cx.reset_type_limit();
2720 p!(print(self.b))
532ac7d7
XL
2721 }
2722
94222f64 2723 ty::CoercePredicate<'tcx> {
6522a427
EL
2724 p!(print(self.a), " -> ");
2725 cx.reset_type_limit();
2726 p!(print(self.b))
94222f64
XL
2727 }
2728
532ac7d7 2729 ty::TraitPredicate<'tcx> {
5099ac24 2730 p!(print(self.trait_ref.self_ty()), ": ");
064997fb 2731 if let ty::BoundConstness::ConstIfConst = self.constness && cx.tcx().features().const_trait_impl {
5099ac24
FG
2732 p!("~const ");
2733 }
2734 p!(print(self.trait_ref.print_only_trait_path()))
532ac7d7
XL
2735 }
2736
2737 ty::ProjectionPredicate<'tcx> {
6522a427
EL
2738 p!(print(self.projection_ty), " == ");
2739 cx.reset_type_limit();
2740 p!(print(self.term))
5099ac24
FG
2741 }
2742
2743 ty::Term<'tcx> {
f2b60f7d
FG
2744 match self.unpack() {
2745 ty::TermKind::Ty(ty) => p!(print(ty)),
2746 ty::TermKind::Const(c) => p!(print(c)),
5099ac24 2747 }
532ac7d7
XL
2748 }
2749
6522a427
EL
2750 ty::AliasTy<'tcx> {
2751 p!(print_def_path(self.def_id, self.substs));
532ac7d7
XL
2752 }
2753
2754 ty::ClosureKind {
2755 match *self {
29967ef6
XL
2756 ty::ClosureKind::Fn => p!("Fn"),
2757 ty::ClosureKind::FnMut => p!("FnMut"),
2758 ty::ClosureKind::FnOnce => p!("FnOnce"),
532ac7d7
XL
2759 }
2760 }
2761
2762 ty::Predicate<'tcx> {
5869c6ff
XL
2763 let binder = self.kind();
2764 p!(print(binder))
3dfed10e
XL
2765 }
2766
5869c6ff 2767 ty::PredicateKind<'tcx> {
3dfed10e 2768 match *self {
6522a427 2769 ty::PredicateKind::Clause(ty::Clause::Trait(ref data)) => {
dfeec247
XL
2770 p!(print(data))
2771 }
5869c6ff 2772 ty::PredicateKind::Subtype(predicate) => p!(print(predicate)),
94222f64 2773 ty::PredicateKind::Coerce(predicate) => p!(print(predicate)),
6522a427
EL
2774 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(predicate)) => p!(print(predicate)),
2775 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(predicate)) => p!(print(predicate)),
2776 ty::PredicateKind::Clause(ty::Clause::Projection(predicate)) => p!(print(predicate)),
5869c6ff
XL
2777 ty::PredicateKind::WellFormed(arg) => p!(print(arg), " well-formed"),
2778 ty::PredicateKind::ObjectSafe(trait_def_id) => {
29967ef6 2779 p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe")
532ac7d7 2780 }
5869c6ff 2781 ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => {
29967ef6 2782 p!("the closure `",
3dfed10e
XL
2783 print_value_path(closure_def_id, &[]),
2784 write("` implements the trait `{}`", kind))
532ac7d7 2785 }
2b03887a
FG
2786 ty::PredicateKind::ConstEvaluatable(ct) => {
2787 p!("the constant `", print(ct), "` can be evaluated")
532ac7d7 2788 }
5869c6ff 2789 ty::PredicateKind::ConstEquate(c1, c2) => {
29967ef6 2790 p!("the constant `", print(c1), "` equals `", print(c2), "`")
f9f354fc 2791 }
5869c6ff 2792 ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
29967ef6 2793 p!("the type `", print(ty), "` is found in the environment")
1b1a35ee 2794 }
6522a427 2795 ty::PredicateKind::Ambiguous => p!("ambiguous"),
532ac7d7
XL
2796 }
2797 }
2798
e74abb32 2799 GenericArg<'tcx> {
532ac7d7 2800 match self.unpack() {
e74abb32
XL
2801 GenericArgKind::Lifetime(lt) => p!(print(lt)),
2802 GenericArgKind::Type(ty) => p!(print(ty)),
2803 GenericArgKind::Const(ct) => p!(print(ct)),
532ac7d7
XL
2804 }
2805 }
2806}
1b1a35ee
XL
2807
2808fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
2809 // Iterate all local crate items no matter where they are defined.
2810 let hir = tcx.hir();
04454e1e 2811 for id in hir.items() {
2b03887a 2812 if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
04454e1e
FG
2813 continue;
2814 }
2815
2816 let item = hir.item(id);
2817 if item.ident.name == kw::Empty {
1b1a35ee
XL
2818 continue;
2819 }
2820
2b03887a 2821 let def_id = item.owner_id.to_def_id();
6a06907d
XL
2822 let ns = tcx.def_kind(def_id).ns().unwrap_or(Namespace::TypeNS);
2823 collect_fn(&item.ident, ns, def_id);
1b1a35ee
XL
2824 }
2825
2826 // Now take care of extern crate items.
2827 let queue = &mut Vec::new();
2828 let mut seen_defs: DefIdSet = Default::default();
2829
136023e0 2830 for &cnum in tcx.crates(()).iter() {
04454e1e 2831 let def_id = cnum.as_def_id();
1b1a35ee
XL
2832
2833 // Ignore crates that are not direct dependencies.
2834 match tcx.extern_crate(def_id) {
2835 None => continue,
2836 Some(extern_crate) => {
2837 if !extern_crate.is_direct() {
2838 continue;
2839 }
2840 }
2841 }
2842
2843 queue.push(def_id);
2844 }
2845
2846 // Iterate external crate defs but be mindful about visibility
2847 while let Some(def) = queue.pop() {
5099ac24 2848 for child in tcx.module_children(def).iter() {
3c0e092e 2849 if !child.vis.is_public() {
1b1a35ee
XL
2850 continue;
2851 }
2852
2853 match child.res {
2854 def::Res::Def(DefKind::AssocTy, _) => {}
6a06907d 2855 def::Res::Def(DefKind::TyAlias, _) => {}
1b1a35ee
XL
2856 def::Res::Def(defkind, def_id) => {
2857 if let Some(ns) = defkind.ns() {
2858 collect_fn(&child.ident, ns, def_id);
2859 }
2860
5099ac24
FG
2861 if matches!(defkind, DefKind::Mod | DefKind::Enum | DefKind::Trait)
2862 && seen_defs.insert(def_id)
2863 {
1b1a35ee
XL
2864 queue.push(def_id);
2865 }
2866 }
2867 _ => {}
2868 }
2869 }
2870 }
2871}
2872
2873/// The purpose of this function is to collect public symbols names that are unique across all
2874/// crates in the build. Later, when printing about types we can use those names instead of the
2875/// full exported path to them.
2876///
2877/// So essentially, if a symbol name can only be imported from one place for a type, and as
2878/// long as it was not glob-imported anywhere in the current crate, we can trim its printed
2879/// path and print only the name.
2880///
2881/// This has wide implications on error messages with types, for example, shortening
2882/// `std::vec::Vec` to just `Vec`, as long as there is no other `Vec` importable anywhere.
2883///
2884/// The implementation uses similar import discovery logic to that of 'use' suggestions.
6522a427
EL
2885///
2886/// See also [`DelayDm`](rustc_error_messages::DelayDm) and [`with_no_trimmed_paths`].
17df50a5 2887fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> FxHashMap<DefId, Symbol> {
c295e0f8 2888 let mut map: FxHashMap<DefId, Symbol> = FxHashMap::default();
1b1a35ee
XL
2889
2890 if let TrimmedDefPaths::GoodPath = tcx.sess.opts.trimmed_def_paths {
6522a427
EL
2891 // Trimming paths is expensive and not optimized, since we expect it to only be used for error reporting.
2892 //
1b1a35ee
XL
2893 // For good paths causing this bug, the `rustc_middle::ty::print::with_no_trimmed_paths`
2894 // wrapper can be used to suppress this query, in exchange for full paths being formatted.
6522a427
EL
2895 tcx.sess.delay_good_path_bug(
2896 "trimmed_def_paths constructed but no error emitted; use `DelayDm` for lints or `with_no_trimmed_paths` for debugging",
2897 );
1b1a35ee
XL
2898 }
2899
2900 let unique_symbols_rev: &mut FxHashMap<(Namespace, Symbol), Option<DefId>> =
2901 &mut FxHashMap::default();
2902
136023e0 2903 for symbol_set in tcx.resolutions(()).glob_map.values() {
1b1a35ee
XL
2904 for symbol in symbol_set {
2905 unique_symbols_rev.insert((Namespace::TypeNS, *symbol), None);
2906 unique_symbols_rev.insert((Namespace::ValueNS, *symbol), None);
2907 unique_symbols_rev.insert((Namespace::MacroNS, *symbol), None);
2908 }
2909 }
2910
2911 for_each_def(tcx, |ident, ns, def_id| {
2912 use std::collections::hash_map::Entry::{Occupied, Vacant};
2913
2914 match unique_symbols_rev.entry((ns, ident.name)) {
2915 Occupied(mut v) => match v.get() {
2916 None => {}
2917 Some(existing) => {
2918 if *existing != def_id {
2919 v.insert(None);
2920 }
2921 }
2922 },
2923 Vacant(v) => {
2924 v.insert(Some(def_id));
2925 }
2926 }
2927 });
2928
2929 for ((_, symbol), opt_def_id) in unique_symbols_rev.drain() {
c295e0f8
XL
2930 use std::collections::hash_map::Entry::{Occupied, Vacant};
2931
1b1a35ee 2932 if let Some(def_id) = opt_def_id {
c295e0f8
XL
2933 match map.entry(def_id) {
2934 Occupied(mut v) => {
2935 // A single DefId can be known under multiple names (e.g.,
2936 // with a `pub use ... as ...;`). We need to ensure that the
2937 // name placed in this map is chosen deterministically, so
2938 // if we find multiple names (`symbol`) resolving to the
2939 // same `def_id`, we prefer the lexicographically smallest
2940 // name.
2941 //
2942 // Any stable ordering would be fine here though.
2943 if *v.get() != symbol {
2944 if v.get().as_str() > symbol.as_str() {
2945 v.insert(symbol);
2946 }
2947 }
2948 }
2949 Vacant(v) => {
2950 v.insert(symbol);
2951 }
2952 }
1b1a35ee
XL
2953 }
2954 }
2955
2956 map
2957}
2958
2959pub fn provide(providers: &mut ty::query::Providers) {
2960 *providers = ty::query::Providers { trimmed_def_paths, ..*providers };
2961}
3c0e092e
XL
2962
2963#[derive(Default)]
2964pub struct OpaqueFnEntry<'tcx> {
2965 // The trait ref is already stored as a key, so just track if we have it as a real predicate
2966 has_fn_once: bool,
2967 fn_mut_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
2968 fn_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
5099ac24 2969 return_ty: Option<ty::Binder<'tcx, Term<'tcx>>>,
3c0e092e 2970}