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