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