]> git.proxmox.com Git - rustc.git/blob - src/librustc/ty/print/pretty.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustc / ty / print / pretty.rs
1 use crate::hir;
2 use crate::hir::def::{Namespace, DefKind};
3 use crate::hir::map::{DefPathData, DisambiguatedDefPathData};
4 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
5 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
6 use crate::middle::region;
7 use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable};
8 use crate::ty::subst::{GenericArg, Subst, GenericArgKind};
9 use crate::ty::layout::{Integer, IntegerExt, Size};
10 use crate::mir::interpret::{ConstValue, sign_extend, Scalar, truncate};
11
12 use rustc_apfloat::ieee::{Double, Single};
13 use rustc_apfloat::Float;
14 use rustc_target::spec::abi::Abi;
15 use syntax::ast;
16 use syntax::attr::{SignedInt, UnsignedInt};
17 use syntax::symbol::{kw, Symbol};
18
19 use std::cell::Cell;
20 use std::collections::BTreeMap;
21 use std::fmt::{self, Write as _};
22 use std::ops::{Deref, DerefMut};
23
24 // `pretty` is a separate module only for organization.
25 use super::*;
26
27 macro_rules! p {
28 (@write($($data:expr),+)) => {
29 write!(scoped_cx!(), $($data),+)?
30 };
31 (@print($x:expr)) => {
32 scoped_cx!() = $x.print(scoped_cx!())?
33 };
34 (@$method:ident($($arg:expr),*)) => {
35 scoped_cx!() = scoped_cx!().$method($($arg),*)?
36 };
37 ($($kind:ident $data:tt),+) => {{
38 $(p!(@$kind $data);)+
39 }};
40 }
41 macro_rules! define_scoped_cx {
42 ($cx:ident) => {
43 #[allow(unused_macros)]
44 macro_rules! scoped_cx {
45 () => ($cx)
46 }
47 };
48 }
49
50 thread_local! {
51 static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
52 static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
53 static NO_QUERIES: Cell<bool> = Cell::new(false);
54 }
55
56 /// Avoids running any queries during any prints that occur
57 /// during the closure. This may alter the appearance of some
58 /// types (e.g. forcing verbose printing for opaque types).
59 /// This method is used during some queries (e.g. `predicates_of`
60 /// for opaque types), to ensure that any debug printing that
61 /// occurs during the query computation does not end up recursively
62 /// calling the same query.
63 pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R {
64 NO_QUERIES.with(|no_queries| {
65 let old = no_queries.get();
66 no_queries.set(true);
67 let result = f();
68 no_queries.set(old);
69 result
70 })
71 }
72
73 /// Force us to name impls with just the filename/line number. We
74 /// normally try to use types. But at some points, notably while printing
75 /// cycle errors, this can result in extra or suboptimal error output,
76 /// so this variable disables that check.
77 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
78 FORCE_IMPL_FILENAME_LINE.with(|force| {
79 let old = force.get();
80 force.set(true);
81 let result = f();
82 force.set(old);
83 result
84 })
85 }
86
87 /// Adds the `crate::` prefix to paths where appropriate.
88 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
89 SHOULD_PREFIX_WITH_CRATE.with(|flag| {
90 let old = flag.get();
91 flag.set(true);
92 let result = f();
93 flag.set(old);
94 result
95 })
96 }
97
98 /// The "region highlights" are used to control region printing during
99 /// specific error messages. When a "region highlight" is enabled, it
100 /// gives an alternate way to print specific regions. For now, we
101 /// always print those regions using a number, so something like "`'0`".
102 ///
103 /// Regions not selected by the region highlight mode are presently
104 /// unaffected.
105 #[derive(Copy, Clone, Default)]
106 pub struct RegionHighlightMode {
107 /// If enabled, when we see the selected region, use "`'N`"
108 /// instead of the ordinary behavior.
109 highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
110
111 /// If enabled, when printing a "free region" that originated from
112 /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
113 /// have names print as normal.
114 ///
115 /// This is used when you have a signature like `fn foo(x: &u32,
116 /// y: &'a u32)` and we want to give a name to the region of the
117 /// reference `x`.
118 highlight_bound_region: Option<(ty::BoundRegion, usize)>,
119 }
120
121 impl RegionHighlightMode {
122 /// If `region` and `number` are both `Some`, invokes
123 /// `highlighting_region`.
124 pub fn maybe_highlighting_region(
125 &mut self,
126 region: Option<ty::Region<'_>>,
127 number: Option<usize>,
128 ) {
129 if let Some(k) = region {
130 if let Some(n) = number {
131 self.highlighting_region(k, n);
132 }
133 }
134 }
135
136 /// Highlights the region inference variable `vid` as `'N`.
137 pub fn highlighting_region(
138 &mut self,
139 region: ty::Region<'_>,
140 number: usize,
141 ) {
142 let num_slots = self.highlight_regions.len();
143 let first_avail_slot = self.highlight_regions.iter_mut()
144 .filter(|s| s.is_none())
145 .next()
146 .unwrap_or_else(|| {
147 bug!(
148 "can only highlight {} placeholders at a time",
149 num_slots,
150 )
151 });
152 *first_avail_slot = Some((*region, number));
153 }
154
155 /// Convenience wrapper for `highlighting_region`.
156 pub fn highlighting_region_vid(
157 &mut self,
158 vid: ty::RegionVid,
159 number: usize,
160 ) {
161 self.highlighting_region(&ty::ReVar(vid), number)
162 }
163
164 /// Returns `Some(n)` with the number to use for the given region, if any.
165 fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
166 self
167 .highlight_regions
168 .iter()
169 .filter_map(|h| match h {
170 Some((r, n)) if r == region => Some(*n),
171 _ => None,
172 })
173 .next()
174 }
175
176 /// Highlight the given bound region.
177 /// We can only highlight one bound region at a time. See
178 /// the field `highlight_bound_region` for more detailed notes.
179 pub fn highlighting_bound_region(
180 &mut self,
181 br: ty::BoundRegion,
182 number: usize,
183 ) {
184 assert!(self.highlight_bound_region.is_none());
185 self.highlight_bound_region = Some((br, number));
186 }
187 }
188
189 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
190 pub trait PrettyPrinter<'tcx>:
191 Printer<
192 'tcx,
193 Error = fmt::Error,
194 Path = Self,
195 Region = Self,
196 Type = Self,
197 DynExistential = Self,
198 Const = Self,
199 > + fmt::Write
200 {
201 /// Like `print_def_path` but for value paths.
202 fn print_value_path(
203 self,
204 def_id: DefId,
205 substs: &'tcx [GenericArg<'tcx>],
206 ) -> Result<Self::Path, Self::Error> {
207 self.print_def_path(def_id, substs)
208 }
209
210 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
211 where
212 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
213 {
214 value.skip_binder().print(self)
215 }
216
217 /// Prints comma-separated elements.
218 fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error>
219 where
220 T: Print<'tcx, Self, Output = Self, Error = Self::Error>,
221 {
222 if let Some(first) = elems.next() {
223 self = first.print(self)?;
224 for elem in elems {
225 self.write_str(", ")?;
226 self = elem.print(self)?;
227 }
228 }
229 Ok(self)
230 }
231
232 /// Prints `<...>` around what `f` prints.
233 fn generic_delimiters(
234 self,
235 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
236 ) -> Result<Self, Self::Error>;
237
238 /// Returns `true` if the region should be printed in
239 /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`.
240 /// This is typically the case for all non-`'_` regions.
241 fn region_should_not_be_omitted(
242 &self,
243 region: ty::Region<'_>,
244 ) -> bool;
245
246 // Defaults (should not be overriden):
247
248 /// If possible, this returns a global path resolving to `def_id` that is visible
249 /// from at least one local module, and returns `true`. If the crate defining `def_id` is
250 /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
251 fn try_print_visible_def_path(
252 self,
253 def_id: DefId,
254 ) -> Result<(Self, bool), Self::Error> {
255 let mut callers = Vec::new();
256 self.try_print_visible_def_path_recur(def_id, &mut callers)
257 }
258
259 /// Does the work of `try_print_visible_def_path`, building the
260 /// full definition path recursively before attempting to
261 /// post-process it into the valid and visible version that
262 /// accounts for re-exports.
263 ///
264 /// This method should only be callled by itself or
265 /// `try_print_visible_def_path`.
266 ///
267 /// `callers` is a chain of visible_parent's leading to `def_id`,
268 /// to support cycle detection during recursion.
269 fn try_print_visible_def_path_recur(
270 mut self,
271 def_id: DefId,
272 callers: &mut Vec<DefId>,
273 ) -> Result<(Self, bool), Self::Error> {
274 define_scoped_cx!(self);
275
276 debug!("try_print_visible_def_path: def_id={:?}", def_id);
277
278 // If `def_id` is a direct or injected extern crate, return the
279 // path to the crate followed by the path to the item within the crate.
280 if def_id.index == CRATE_DEF_INDEX {
281 let cnum = def_id.krate;
282
283 if cnum == LOCAL_CRATE {
284 return Ok((self.path_crate(cnum)?, true));
285 }
286
287 // In local mode, when we encounter a crate other than
288 // LOCAL_CRATE, execution proceeds in one of two ways:
289 //
290 // 1. For a direct dependency, where user added an
291 // `extern crate` manually, we put the `extern
292 // crate` as the parent. So you wind up with
293 // something relative to the current crate.
294 // 2. For an extern inferred from a path or an indirect crate,
295 // where there is no explicit `extern crate`, we just prepend
296 // the crate name.
297 match self.tcx().extern_crate(def_id) {
298 Some(&ExternCrate {
299 src: ExternCrateSource::Extern(def_id),
300 dependency_of: LOCAL_CRATE,
301 span,
302 ..
303 }) => {
304 debug!("try_print_visible_def_path: def_id={:?}", def_id);
305 return Ok((if !span.is_dummy() {
306 self.print_def_path(def_id, &[])?
307 } else {
308 self.path_crate(cnum)?
309 }, true));
310 }
311 None => {
312 return Ok((self.path_crate(cnum)?, true));
313 }
314 _ => {},
315 }
316 }
317
318 if def_id.is_local() {
319 return Ok((self, false));
320 }
321
322 let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE);
323
324 let mut cur_def_key = self.tcx().def_key(def_id);
325 debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
326
327 // For a constructor, we want the name of its parent rather than <unnamed>.
328 match cur_def_key.disambiguated_data.data {
329 DefPathData::Ctor => {
330 let parent = DefId {
331 krate: def_id.krate,
332 index: cur_def_key.parent
333 .expect("`DefPathData::Ctor` / `VariantData` missing a parent"),
334 };
335
336 cur_def_key = self.tcx().def_key(parent);
337 },
338 _ => {},
339 }
340
341 let visible_parent = match visible_parent_map.get(&def_id).cloned() {
342 Some(parent) => parent,
343 None => return Ok((self, false)),
344 };
345 if callers.contains(&visible_parent) {
346 return Ok((self, false));
347 }
348 callers.push(visible_parent);
349 // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid
350 // knowing ahead of time whether the entire path will succeed or not.
351 // To support printers that do not implement `PrettyPrinter`, a `Vec` or
352 // linked list on the stack would need to be built, before any printing.
353 match self.try_print_visible_def_path_recur(visible_parent, callers)? {
354 (cx, false) => return Ok((cx, false)),
355 (cx, true) => self = cx,
356 }
357 callers.pop();
358 let actual_parent = self.tcx().parent(def_id);
359 debug!(
360 "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}",
361 visible_parent, actual_parent,
362 );
363
364 let mut data = cur_def_key.disambiguated_data.data;
365 debug!(
366 "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
367 data, visible_parent, actual_parent,
368 );
369
370 match data {
371 // In order to output a path that could actually be imported (valid and visible),
372 // we need to handle re-exports correctly.
373 //
374 // For example, take `std::os::unix::process::CommandExt`, this trait is actually
375 // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
376 //
377 // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
378 // private so the "true" path to `CommandExt` isn't accessible.
379 //
380 // In this case, the `visible_parent_map` will look something like this:
381 //
382 // (child) -> (parent)
383 // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
384 // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
385 // `std::sys::unix::ext` -> `std::os`
386 //
387 // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
388 // `std::os`.
389 //
390 // When printing the path to `CommandExt` and looking at the `cur_def_key` that
391 // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
392 // to the parent - resulting in a mangled path like
393 // `std::os::ext::process::CommandExt`.
394 //
395 // Instead, we must detect that there was a re-export and instead print `unix`
396 // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
397 // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
398 // the visible parent (`std::os`). If these do not match, then we iterate over
399 // the children of the visible parent (as was done when computing
400 // `visible_parent_map`), looking for the specific child we currently have and then
401 // have access to the re-exported name.
402 DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => {
403 let reexport = self.tcx().item_children(visible_parent)
404 .iter()
405 .find(|child| child.res.def_id() == def_id)
406 .map(|child| child.ident.name);
407 if let Some(reexport) = reexport {
408 *name = reexport;
409 }
410 }
411 // Re-exported `extern crate` (#43189).
412 DefPathData::CrateRoot => {
413 data = DefPathData::TypeNs(
414 self.tcx().original_crate_name(def_id.krate),
415 );
416 }
417 _ => {}
418 }
419 debug!("try_print_visible_def_path: data={:?}", data);
420
421 Ok((self.path_append(Ok, &DisambiguatedDefPathData {
422 data,
423 disambiguator: 0,
424 })?, true))
425 }
426
427 fn pretty_path_qualified(
428 self,
429 self_ty: Ty<'tcx>,
430 trait_ref: Option<ty::TraitRef<'tcx>>,
431 ) -> Result<Self::Path, Self::Error> {
432 if trait_ref.is_none() {
433 // Inherent impls. Try to print `Foo::bar` for an inherent
434 // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
435 // anything other than a simple path.
436 match self_ty.kind {
437 ty::Adt(..) | ty::Foreign(_) |
438 ty::Bool | ty::Char | ty::Str |
439 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
440 return self_ty.print(self);
441 }
442
443 _ => {}
444 }
445 }
446
447 self.generic_delimiters(|mut cx| {
448 define_scoped_cx!(cx);
449
450 p!(print(self_ty));
451 if let Some(trait_ref) = trait_ref {
452 p!(write(" as "), print(trait_ref.print_only_trait_path()));
453 }
454 Ok(cx)
455 })
456 }
457
458 fn pretty_path_append_impl(
459 mut self,
460 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
461 self_ty: Ty<'tcx>,
462 trait_ref: Option<ty::TraitRef<'tcx>>,
463 ) -> Result<Self::Path, Self::Error> {
464 self = print_prefix(self)?;
465
466 self.generic_delimiters(|mut cx| {
467 define_scoped_cx!(cx);
468
469 p!(write("impl "));
470 if let Some(trait_ref) = trait_ref {
471 p!(print(trait_ref.print_only_trait_path()), write(" for "));
472 }
473 p!(print(self_ty));
474
475 Ok(cx)
476 })
477 }
478
479 fn pretty_print_type(
480 mut self,
481 ty: Ty<'tcx>,
482 ) -> Result<Self::Type, Self::Error> {
483 define_scoped_cx!(self);
484
485 match ty.kind {
486 ty::Bool => p!(write("bool")),
487 ty::Char => p!(write("char")),
488 ty::Int(t) => p!(write("{}", t.name_str())),
489 ty::Uint(t) => p!(write("{}", t.name_str())),
490 ty::Float(t) => p!(write("{}", t.name_str())),
491 ty::RawPtr(ref tm) => {
492 p!(write("*{} ", match tm.mutbl {
493 hir::Mutability::Mutable => "mut",
494 hir::Mutability::Immutable => "const",
495 }));
496 p!(print(tm.ty))
497 }
498 ty::Ref(r, ty, mutbl) => {
499 p!(write("&"));
500 if self.region_should_not_be_omitted(r) {
501 p!(print(r), write(" "));
502 }
503 p!(print(ty::TypeAndMut { ty, mutbl }))
504 }
505 ty::Never => p!(write("!")),
506 ty::Tuple(ref tys) => {
507 p!(write("("));
508 let mut tys = tys.iter();
509 if let Some(&ty) = tys.next() {
510 p!(print(ty), write(","));
511 if let Some(&ty) = tys.next() {
512 p!(write(" "), print(ty));
513 for &ty in tys {
514 p!(write(", "), print(ty));
515 }
516 }
517 }
518 p!(write(")"))
519 }
520 ty::FnDef(def_id, substs) => {
521 let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs);
522 p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}"));
523 }
524 ty::FnPtr(ref bare_fn) => {
525 p!(print(bare_fn))
526 }
527 ty::Infer(infer_ty) => {
528 if let ty::TyVar(ty_vid) = infer_ty {
529 if let Some(name) = self.infer_ty_name(ty_vid) {
530 p!(write("{}", name))
531 } else {
532 p!(write("{}", infer_ty))
533 }
534 } else {
535 p!(write("{}", infer_ty))
536 }
537 },
538 ty::Error => p!(write("[type error]")),
539 ty::Param(ref param_ty) => p!(write("{}", param_ty)),
540 ty::Bound(debruijn, bound_ty) => {
541 match bound_ty.kind {
542 ty::BoundTyKind::Anon => {
543 if debruijn == ty::INNERMOST {
544 p!(write("^{}", bound_ty.var.index()))
545 } else {
546 p!(write("^{}_{}", debruijn.index(), bound_ty.var.index()))
547 }
548 }
549
550 ty::BoundTyKind::Param(p) => p!(write("{}", p)),
551 }
552 }
553 ty::Adt(def, substs) => {
554 p!(print_def_path(def.did, substs));
555 }
556 ty::Dynamic(data, r) => {
557 let print_r = self.region_should_not_be_omitted(r);
558 if print_r {
559 p!(write("("));
560 }
561 p!(write("dyn "), print(data));
562 if print_r {
563 p!(write(" + "), print(r), write(")"));
564 }
565 }
566 ty::Foreign(def_id) => {
567 p!(print_def_path(def_id, &[]));
568 }
569 ty::Projection(ref data) => p!(print(data)),
570 ty::UnnormalizedProjection(ref data) => {
571 p!(write("Unnormalized("), print(data), write(")"))
572 }
573 ty::Placeholder(placeholder) => {
574 p!(write("Placeholder({:?})", placeholder))
575 }
576 ty::Opaque(def_id, substs) => {
577 // FIXME(eddyb) print this with `print_def_path`.
578 // We use verbose printing in 'NO_QUERIES' mode, to
579 // avoid needing to call `predicates_of`. This should
580 // only affect certain debug messages (e.g. messages printed
581 // from `rustc::ty` during the computation of `tcx.predicates_of`),
582 // and should have no effect on any compiler output.
583 if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) {
584 p!(write("Opaque({:?}, {:?})", def_id, substs));
585 return Ok(self);
586 }
587
588 return Ok(with_no_queries(|| {
589
590 let def_key = self.tcx().def_key(def_id);
591 if let Some(name) = def_key.disambiguated_data.data.get_opt_name() {
592 p!(write("{}", name));
593 let mut substs = substs.iter();
594 // FIXME(eddyb) print this with `print_def_path`.
595 if let Some(first) = substs.next() {
596 p!(write("::<"));
597 p!(print(first));
598 for subst in substs {
599 p!(write(", "), print(subst));
600 }
601 p!(write(">"));
602 }
603 return Ok(self);
604 }
605 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
606 // by looking up the projections associated with the def_id.
607 let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
608
609 let mut first = true;
610 let mut is_sized = false;
611 p!(write("impl"));
612 for predicate in bounds.predicates {
613 if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() {
614 // Don't print +Sized, but rather +?Sized if absent.
615 if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() {
616 is_sized = true;
617 continue;
618 }
619
620 p!(
621 write("{}", if first { " " } else { "+" }),
622 print(trait_ref.print_only_trait_path()));
623 first = false;
624 }
625 }
626 if !is_sized {
627 p!(write("{}?Sized", if first { " " } else { "+" }));
628 } else if first {
629 p!(write(" Sized"));
630 }
631 Ok(self)
632 })?);
633 }
634 ty::Str => p!(write("str")),
635 ty::Generator(did, substs, movability) => {
636 let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx());
637 let witness = substs.as_generator().witness(did, self.tcx());
638 match movability {
639 hir::Movability::Movable => p!(write("[generator")),
640 hir::Movability::Static => p!(write("[static generator")),
641 }
642
643 // FIXME(eddyb) should use `def_span`.
644 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
645 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
646 let mut sep = " ";
647 for (&var_id, upvar_ty) in self.tcx().upvars(did)
648 .as_ref()
649 .iter()
650 .flat_map(|v| v.keys())
651 .zip(upvar_tys)
652 {
653 p!(
654 write("{}{}:",
655 sep,
656 self.tcx().hir().name(var_id)),
657 print(upvar_ty));
658 sep = ", ";
659 }
660 } else {
661 // Cross-crate closure types should only be
662 // visible in codegen bug reports, I imagine.
663 p!(write("@{:?}", did));
664 let mut sep = " ";
665 for (index, upvar_ty) in upvar_tys.enumerate() {
666 p!(
667 write("{}{}:", sep, index),
668 print(upvar_ty));
669 sep = ", ";
670 }
671 }
672
673 p!(write(" "), print(witness), write("]"))
674 },
675 ty::GeneratorWitness(types) => {
676 p!(in_binder(&types));
677 }
678 ty::Closure(did, substs) => {
679 let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx());
680 p!(write("[closure"));
681
682 // FIXME(eddyb) should use `def_span`.
683 if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
684 if self.tcx().sess.opts.debugging_opts.span_free_formats {
685 p!(write("@"), print_def_path(did, substs));
686 } else {
687 p!(write("@{:?}", self.tcx().hir().span(hir_id)));
688 }
689 let mut sep = " ";
690 for (&var_id, upvar_ty) in self.tcx().upvars(did)
691 .as_ref()
692 .iter()
693 .flat_map(|v| v.keys())
694 .zip(upvar_tys)
695 {
696 p!(
697 write("{}{}:",
698 sep,
699 self.tcx().hir().name(var_id)),
700 print(upvar_ty));
701 sep = ", ";
702 }
703 } else {
704 // Cross-crate closure types should only be
705 // visible in codegen bug reports, I imagine.
706 p!(write("@{:?}", did));
707 let mut sep = " ";
708 for (index, upvar_ty) in upvar_tys.enumerate() {
709 p!(
710 write("{}{}:", sep, index),
711 print(upvar_ty));
712 sep = ", ";
713 }
714 }
715
716 if self.tcx().sess.verbose() {
717 p!(write(
718 " closure_kind_ty={:?} closure_sig_ty={:?}",
719 substs.as_closure().kind_ty(did, self.tcx()),
720 substs.as_closure().sig_ty(did, self.tcx())
721 ));
722 }
723
724 p!(write("]"))
725 },
726 ty::Array(ty, sz) => {
727 p!(write("["), print(ty), write("; "));
728 if self.tcx().sess.verbose() {
729 p!(write("{:?}", sz));
730 } else if let ty::ConstKind::Unevaluated(..) = sz.val {
731 // do not try to evalute unevaluated constants. If we are const evaluating an
732 // array length anon const, rustc will (with debug assertions) print the
733 // constant's path. Which will end up here again.
734 p!(write("_"));
735 } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) {
736 p!(write("{}", n));
737 } else {
738 p!(write("_"));
739 }
740 p!(write("]"))
741 }
742 ty::Slice(ty) => {
743 p!(write("["), print(ty), write("]"))
744 }
745 }
746
747 Ok(self)
748 }
749
750 fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
751 None
752 }
753
754 fn pretty_print_dyn_existential(
755 mut self,
756 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
757 ) -> Result<Self::DynExistential, Self::Error> {
758 define_scoped_cx!(self);
759
760 // Generate the main trait ref, including associated types.
761 let mut first = true;
762
763 if let Some(principal) = predicates.principal() {
764 p!(print_def_path(principal.def_id, &[]));
765
766 let mut resugared = false;
767
768 // Special-case `Fn(...) -> ...` and resugar it.
769 let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id);
770 if !self.tcx().sess.verbose() && fn_trait_kind.is_some() {
771 if let ty::Tuple(ref args) = principal.substs.type_at(0).kind {
772 let mut projections = predicates.projection_bounds();
773 if let (Some(proj), None) = (projections.next(), projections.next()) {
774 let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect();
775 p!(pretty_fn_sig(&tys, false, proj.ty));
776 resugared = true;
777 }
778 }
779 }
780
781 // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`,
782 // in order to place the projections inside the `<...>`.
783 if !resugared {
784 // Use a type that can't appear in defaults of type parameters.
785 let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0));
786 let principal = principal.with_self_ty(self.tcx(), dummy_self);
787
788 let args = self.generic_args_to_print(
789 self.tcx().generics_of(principal.def_id),
790 principal.substs,
791 );
792
793 // Don't print `'_` if there's no unerased regions.
794 let print_regions = args.iter().any(|arg| {
795 match arg.unpack() {
796 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
797 _ => false,
798 }
799 });
800 let mut args = args.iter().cloned().filter(|arg| {
801 match arg.unpack() {
802 GenericArgKind::Lifetime(_) => print_regions,
803 _ => true,
804 }
805 });
806 let mut projections = predicates.projection_bounds();
807
808 let arg0 = args.next();
809 let projection0 = projections.next();
810 if arg0.is_some() || projection0.is_some() {
811 let args = arg0.into_iter().chain(args);
812 let projections = projection0.into_iter().chain(projections);
813
814 p!(generic_delimiters(|mut cx| {
815 cx = cx.comma_sep(args)?;
816 if arg0.is_some() && projection0.is_some() {
817 write!(cx, ", ")?;
818 }
819 cx.comma_sep(projections)
820 }));
821 }
822 }
823 first = false;
824 }
825
826 // Builtin bounds.
827 // FIXME(eddyb) avoid printing twice (needed to ensure
828 // that the auto traits are sorted *and* printed via cx).
829 let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| {
830 (self.tcx().def_path_str(did), did)
831 }).collect();
832
833 // The auto traits come ordered by `DefPathHash`. While
834 // `DefPathHash` is *stable* in the sense that it depends on
835 // neither the host nor the phase of the moon, it depends
836 // "pseudorandomly" on the compiler version and the target.
837 //
838 // To avoid that causing instabilities in compiletest
839 // output, sort the auto-traits alphabetically.
840 auto_traits.sort();
841
842 for (_, def_id) in auto_traits {
843 if !first {
844 p!(write(" + "));
845 }
846 first = false;
847
848 p!(print_def_path(def_id, &[]));
849 }
850
851 Ok(self)
852 }
853
854 fn pretty_fn_sig(
855 mut self,
856 inputs: &[Ty<'tcx>],
857 c_variadic: bool,
858 output: Ty<'tcx>,
859 ) -> Result<Self, Self::Error> {
860 define_scoped_cx!(self);
861
862 p!(write("("));
863 let mut inputs = inputs.iter();
864 if let Some(&ty) = inputs.next() {
865 p!(print(ty));
866 for &ty in inputs {
867 p!(write(", "), print(ty));
868 }
869 if c_variadic {
870 p!(write(", ..."));
871 }
872 }
873 p!(write(")"));
874 if !output.is_unit() {
875 p!(write(" -> "), print(output));
876 }
877
878 Ok(self)
879 }
880
881 fn pretty_print_const(
882 mut self,
883 ct: &'tcx ty::Const<'tcx>,
884 ) -> Result<Self::Const, Self::Error> {
885 define_scoped_cx!(self);
886
887 if self.tcx().sess.verbose() {
888 p!(write("Const({:?}: {:?})", ct.val, ct.ty));
889 return Ok(self);
890 }
891
892 match (ct.val, &ct.ty.kind) {
893 (_, ty::FnDef(did, substs)) => p!(print_value_path(*did, substs)),
894 (ty::ConstKind::Unevaluated(did, substs), _) => {
895 match self.tcx().def_kind(did) {
896 | Some(DefKind::Static)
897 | Some(DefKind::Const)
898 | Some(DefKind::AssocConst) => p!(print_value_path(did, substs)),
899 _ => if did.is_local() {
900 let span = self.tcx().def_span(did);
901 if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) {
902 p!(write("{}", snip))
903 } else {
904 p!(write("_: "), print(ct.ty))
905 }
906 } else {
907 p!(write("_: "), print(ct.ty))
908 },
909 }
910 },
911 (ty::ConstKind::Infer(..), _) => p!(write("_: "), print(ct.ty)),
912 (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)),
913 (ty::ConstKind::Value(value), _) => return self.pretty_print_const_value(value, ct.ty),
914
915 _ => {
916 // fallback
917 p!(write("{:?} : ", ct.val), print(ct.ty))
918 }
919 };
920 Ok(self)
921 }
922
923 fn pretty_print_const_value(
924 mut self,
925 ct: ConstValue<'tcx>,
926 ty: Ty<'tcx>,
927 ) -> Result<Self::Const, Self::Error> {
928 define_scoped_cx!(self);
929
930 if self.tcx().sess.verbose() {
931 p!(write("ConstValue({:?}: {:?})", ct, ty));
932 return Ok(self);
933 }
934
935 let u8 = self.tcx().types.u8;
936
937 match (ct, &ty.kind) {
938 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) =>
939 p!(write("{}", if data == 0 { "false" } else { "true" })),
940 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) =>
941 p!(write("{}f32", Single::from_bits(data))),
942 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) =>
943 p!(write("{}f64", Double::from_bits(data))),
944 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => {
945 let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size();
946 let max = truncate(u128::max_value(), bit_size);
947
948 let ui_str = ui.name_str();
949 if data == max {
950 p!(write("std::{}::MAX", ui_str))
951 } else {
952 p!(write("{}{}", data, ui_str))
953 };
954 },
955 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => {
956 let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i))
957 .size().bits() as u128;
958 let min = 1u128 << (bit_size - 1);
959 let max = min - 1;
960
961 let ty = self.tcx().lift(&ty).unwrap();
962 let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty))
963 .unwrap()
964 .size;
965 let i_str = i.name_str();
966 match data {
967 d if d == min => p!(write("std::{}::MIN", i_str)),
968 d if d == max => p!(write("std::{}::MAX", i_str)),
969 _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str))
970 }
971 },
972 (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) =>
973 p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap())),
974 (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")),
975 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => {
976 let instance = {
977 let alloc_map = self.tcx().alloc_map.lock();
978 alloc_map.unwrap_fn(ptr.alloc_id)
979 };
980 p!(print_value_path(instance.def_id(), instance.substs));
981 },
982 _ => {
983 let printed = if let ty::Ref(_, ref_ty, _) = ty.kind {
984 let byte_str = match (ct, &ref_ty.kind) {
985 (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => {
986 let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty());
987 Some(self.tcx()
988 .alloc_map.lock()
989 .unwrap_memory(ptr.alloc_id)
990 .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)).unwrap())
991 },
992 (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => {
993 // The `inspect` here is okay since we checked the bounds, and there are
994 // no relocations (we have an active slice reference here). We don't use
995 // this result to affect interpreter execution.
996 Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end))
997 },
998 _ => None,
999 };
1000
1001 if let Some(byte_str) = byte_str {
1002 p!(write("b\""));
1003 for &c in byte_str {
1004 for e in std::ascii::escape_default(c) {
1005 self.write_char(e as char)?;
1006 }
1007 }
1008 p!(write("\""));
1009 true
1010 } else if let (ConstValue::Slice { data, start, end }, ty::Str) =
1011 (ct, &ref_ty.kind)
1012 {
1013 // The `inspect` here is okay since we checked the bounds, and there are no
1014 // relocations (we have an active `str` reference here). We don't use this
1015 // result to affect interpreter execution.
1016 let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end);
1017 let s = ::std::str::from_utf8(slice)
1018 .expect("non utf8 str from miri");
1019 p!(write("{:?}", s));
1020 true
1021 } else {
1022 false
1023 }
1024 } else {
1025 false
1026 };
1027 if !printed {
1028 // fallback
1029 p!(write("{:?} : ", ct), print(ty))
1030 }
1031 }
1032 };
1033 Ok(self)
1034 }
1035 }
1036
1037 // HACK(eddyb) boxed to avoid moving around a large struct by-value.
1038 pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>);
1039
1040 pub struct FmtPrinterData<'a, 'tcx, F> {
1041 tcx: TyCtxt<'tcx>,
1042 fmt: F,
1043
1044 empty_path: bool,
1045 in_value: bool,
1046
1047 used_region_names: FxHashSet<Symbol>,
1048 region_index: usize,
1049 binder_depth: usize,
1050
1051 pub region_highlight_mode: RegionHighlightMode,
1052
1053 pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>,
1054 }
1055
1056 impl<F> Deref for FmtPrinter<'a, 'tcx, F> {
1057 type Target = FmtPrinterData<'a, 'tcx, F>;
1058 fn deref(&self) -> &Self::Target {
1059 &self.0
1060 }
1061 }
1062
1063 impl<F> DerefMut for FmtPrinter<'_, '_, F> {
1064 fn deref_mut(&mut self) -> &mut Self::Target {
1065 &mut self.0
1066 }
1067 }
1068
1069 impl<F> FmtPrinter<'a, 'tcx, F> {
1070 pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self {
1071 FmtPrinter(Box::new(FmtPrinterData {
1072 tcx,
1073 fmt,
1074 empty_path: false,
1075 in_value: ns == Namespace::ValueNS,
1076 used_region_names: Default::default(),
1077 region_index: 0,
1078 binder_depth: 0,
1079 region_highlight_mode: RegionHighlightMode::default(),
1080 name_resolver: None,
1081 }))
1082 }
1083 }
1084
1085 impl TyCtxt<'t> {
1086 // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
1087 // (but also some things just print a `DefId` generally so maybe we need this?)
1088 fn guess_def_namespace(self, def_id: DefId) -> Namespace {
1089 match self.def_key(def_id).disambiguated_data.data {
1090 DefPathData::TypeNs(..)
1091 | DefPathData::CrateRoot
1092 | DefPathData::ImplTrait => Namespace::TypeNS,
1093
1094 DefPathData::ValueNs(..)
1095 | DefPathData::AnonConst
1096 | DefPathData::ClosureExpr
1097 | DefPathData::Ctor => Namespace::ValueNS,
1098
1099 DefPathData::MacroNs(..) => Namespace::MacroNS,
1100
1101 _ => Namespace::TypeNS,
1102 }
1103 }
1104
1105 /// Returns a string identifying this `DefId`. This string is
1106 /// suitable for user output.
1107 pub fn def_path_str(self, def_id: DefId) -> String {
1108 self.def_path_str_with_substs(def_id, &[])
1109 }
1110
1111 pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String {
1112 let ns = self.guess_def_namespace(def_id);
1113 debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
1114 let mut s = String::new();
1115 let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs);
1116 s
1117 }
1118 }
1119
1120 impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> {
1121 fn write_str(&mut self, s: &str) -> fmt::Result {
1122 self.fmt.write_str(s)
1123 }
1124 }
1125
1126 impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
1127 type Error = fmt::Error;
1128
1129 type Path = Self;
1130 type Region = Self;
1131 type Type = Self;
1132 type DynExistential = Self;
1133 type Const = Self;
1134
1135 fn tcx(&'a self) -> TyCtxt<'tcx> {
1136 self.tcx
1137 }
1138
1139 fn print_def_path(
1140 mut self,
1141 def_id: DefId,
1142 substs: &'tcx [GenericArg<'tcx>],
1143 ) -> Result<Self::Path, Self::Error> {
1144 define_scoped_cx!(self);
1145
1146 if substs.is_empty() {
1147 match self.try_print_visible_def_path(def_id)? {
1148 (cx, true) => return Ok(cx),
1149 (cx, false) => self = cx,
1150 }
1151 }
1152
1153 let key = self.tcx.def_key(def_id);
1154 if let DefPathData::Impl = key.disambiguated_data.data {
1155 // Always use types for non-local impls, where types are always
1156 // available, and filename/line-number is mostly uninteresting.
1157 let use_types =
1158 !def_id.is_local() || {
1159 // Otherwise, use filename/line-number if forced.
1160 let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
1161 !force_no_types
1162 };
1163
1164 if !use_types {
1165 // If no type info is available, fall back to
1166 // pretty printing some span information. This should
1167 // only occur very early in the compiler pipeline.
1168 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
1169 let span = self.tcx.def_span(def_id);
1170
1171 self = self.print_def_path(parent_def_id, &[])?;
1172
1173 // HACK(eddyb) copy of `path_append` to avoid
1174 // constructing a `DisambiguatedDefPathData`.
1175 if !self.empty_path {
1176 write!(self, "::")?;
1177 }
1178 write!(self, "<impl at {:?}>", span)?;
1179 self.empty_path = false;
1180
1181 return Ok(self);
1182 }
1183 }
1184
1185 self.default_print_def_path(def_id, substs)
1186 }
1187
1188 fn print_region(
1189 self,
1190 region: ty::Region<'_>,
1191 ) -> Result<Self::Region, Self::Error> {
1192 self.pretty_print_region(region)
1193 }
1194
1195 fn print_type(
1196 self,
1197 ty: Ty<'tcx>,
1198 ) -> Result<Self::Type, Self::Error> {
1199 self.pretty_print_type(ty)
1200 }
1201
1202 fn print_dyn_existential(
1203 self,
1204 predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1205 ) -> Result<Self::DynExistential, Self::Error> {
1206 self.pretty_print_dyn_existential(predicates)
1207 }
1208
1209 fn print_const(
1210 self,
1211 ct: &'tcx ty::Const<'tcx>,
1212 ) -> Result<Self::Const, Self::Error> {
1213 self.pretty_print_const(ct)
1214 }
1215
1216 fn path_crate(
1217 mut self,
1218 cnum: CrateNum,
1219 ) -> Result<Self::Path, Self::Error> {
1220 self.empty_path = true;
1221 if cnum == LOCAL_CRATE {
1222 if self.tcx.sess.rust_2018() {
1223 // We add the `crate::` keyword on Rust 2018, only when desired.
1224 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1225 write!(self, "{}", kw::Crate)?;
1226 self.empty_path = false;
1227 }
1228 }
1229 } else {
1230 write!(self, "{}", self.tcx.crate_name(cnum))?;
1231 self.empty_path = false;
1232 }
1233 Ok(self)
1234 }
1235
1236 fn path_qualified(
1237 mut self,
1238 self_ty: Ty<'tcx>,
1239 trait_ref: Option<ty::TraitRef<'tcx>>,
1240 ) -> Result<Self::Path, Self::Error> {
1241 self = self.pretty_path_qualified(self_ty, trait_ref)?;
1242 self.empty_path = false;
1243 Ok(self)
1244 }
1245
1246 fn path_append_impl(
1247 mut self,
1248 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1249 _disambiguated_data: &DisambiguatedDefPathData,
1250 self_ty: Ty<'tcx>,
1251 trait_ref: Option<ty::TraitRef<'tcx>>,
1252 ) -> Result<Self::Path, Self::Error> {
1253 self = self.pretty_path_append_impl(|mut cx| {
1254 cx = print_prefix(cx)?;
1255 if !cx.empty_path {
1256 write!(cx, "::")?;
1257 }
1258
1259 Ok(cx)
1260 }, self_ty, trait_ref)?;
1261 self.empty_path = false;
1262 Ok(self)
1263 }
1264
1265 fn path_append(
1266 mut self,
1267 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1268 disambiguated_data: &DisambiguatedDefPathData,
1269 ) -> Result<Self::Path, Self::Error> {
1270 self = print_prefix(self)?;
1271
1272 // Skip `::{{constructor}}` on tuple/unit structs.
1273 match disambiguated_data.data {
1274 DefPathData::Ctor => return Ok(self),
1275 _ => {}
1276 }
1277
1278 // FIXME(eddyb) `name` should never be empty, but it
1279 // currently is for `extern { ... }` "foreign modules".
1280 let name = disambiguated_data.data.as_symbol().as_str();
1281 if !name.is_empty() {
1282 if !self.empty_path {
1283 write!(self, "::")?;
1284 }
1285 if ast::Ident::from_str(&name).is_raw_guess() {
1286 write!(self, "r#")?;
1287 }
1288 write!(self, "{}", name)?;
1289
1290 // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1291 // might be nicer to use something else, e.g. `{closure#3}`.
1292 let dis = disambiguated_data.disambiguator;
1293 let print_dis =
1294 disambiguated_data.data.get_opt_name().is_none() ||
1295 dis != 0 && self.tcx.sess.verbose();
1296 if print_dis {
1297 write!(self, "#{}", dis)?;
1298 }
1299
1300 self.empty_path = false;
1301 }
1302
1303 Ok(self)
1304 }
1305
1306 fn path_generic_args(
1307 mut self,
1308 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
1309 args: &[GenericArg<'tcx>],
1310 ) -> Result<Self::Path, Self::Error> {
1311 self = print_prefix(self)?;
1312
1313 // Don't print `'_` if there's no unerased regions.
1314 let print_regions = args.iter().any(|arg| {
1315 match arg.unpack() {
1316 GenericArgKind::Lifetime(r) => *r != ty::ReErased,
1317 _ => false,
1318 }
1319 });
1320 let args = args.iter().cloned().filter(|arg| {
1321 match arg.unpack() {
1322 GenericArgKind::Lifetime(_) => print_regions,
1323 _ => true,
1324 }
1325 });
1326
1327 if args.clone().next().is_some() {
1328 if self.in_value {
1329 write!(self, "::")?;
1330 }
1331 self.generic_delimiters(|cx| cx.comma_sep(args))
1332 } else {
1333 Ok(self)
1334 }
1335 }
1336 }
1337
1338 impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
1339 fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
1340 self.0.name_resolver.as_ref().and_then(|func| func(id))
1341 }
1342
1343 fn print_value_path(
1344 mut self,
1345 def_id: DefId,
1346 substs: &'tcx [GenericArg<'tcx>],
1347 ) -> Result<Self::Path, Self::Error> {
1348 let was_in_value = std::mem::replace(&mut self.in_value, true);
1349 self = self.print_def_path(def_id, substs)?;
1350 self.in_value = was_in_value;
1351
1352 Ok(self)
1353 }
1354
1355 fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error>
1356 where
1357 T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>,
1358 {
1359 self.pretty_in_binder(value)
1360 }
1361
1362 fn generic_delimiters(
1363 mut self,
1364 f: impl FnOnce(Self) -> Result<Self, Self::Error>,
1365 ) -> Result<Self, Self::Error> {
1366 write!(self, "<")?;
1367
1368 let was_in_value = std::mem::replace(&mut self.in_value, false);
1369 let mut inner = f(self)?;
1370 inner.in_value = was_in_value;
1371
1372 write!(inner, ">")?;
1373 Ok(inner)
1374 }
1375
1376 fn region_should_not_be_omitted(
1377 &self,
1378 region: ty::Region<'_>,
1379 ) -> bool {
1380 let highlight = self.region_highlight_mode;
1381 if highlight.region_highlighted(region).is_some() {
1382 return true;
1383 }
1384
1385 if self.tcx.sess.verbose() {
1386 return true;
1387 }
1388
1389 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1390
1391 match *region {
1392 ty::ReEarlyBound(ref data) => {
1393 data.name != kw::Invalid &&
1394 data.name != kw::UnderscoreLifetime
1395 }
1396
1397 ty::ReLateBound(_, br) |
1398 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1399 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1400 if let ty::BrNamed(_, name) = br {
1401 if name != kw::Invalid &&
1402 name != kw::UnderscoreLifetime {
1403 return true;
1404 }
1405 }
1406
1407 if let Some((region, _)) = highlight.highlight_bound_region {
1408 if br == region {
1409 return true;
1410 }
1411 }
1412
1413 false
1414 }
1415
1416 ty::ReScope(_) |
1417 ty::ReVar(_) if identify_regions => true,
1418
1419 ty::ReVar(_) |
1420 ty::ReScope(_) |
1421 ty::ReErased => false,
1422
1423 ty::ReStatic |
1424 ty::ReEmpty |
1425 ty::ReClosureBound(_) => true,
1426 }
1427 }
1428 }
1429
1430 // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`.
1431 impl<F: fmt::Write> FmtPrinter<'_, '_, F> {
1432 pub fn pretty_print_region(
1433 mut self,
1434 region: ty::Region<'_>,
1435 ) -> Result<Self, fmt::Error> {
1436 define_scoped_cx!(self);
1437
1438 // Watch out for region highlights.
1439 let highlight = self.region_highlight_mode;
1440 if let Some(n) = highlight.region_highlighted(region) {
1441 p!(write("'{}", n));
1442 return Ok(self);
1443 }
1444
1445 if self.tcx.sess.verbose() {
1446 p!(write("{:?}", region));
1447 return Ok(self);
1448 }
1449
1450 let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions;
1451
1452 // These printouts are concise. They do not contain all the information
1453 // the user might want to diagnose an error, but there is basically no way
1454 // to fit that into a short string. Hence the recommendation to use
1455 // `explain_region()` or `note_and_explain_region()`.
1456 match *region {
1457 ty::ReEarlyBound(ref data) => {
1458 if data.name != kw::Invalid {
1459 p!(write("{}", data.name));
1460 return Ok(self);
1461 }
1462 }
1463 ty::ReLateBound(_, br) |
1464 ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1465 ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1466 if let ty::BrNamed(_, name) = br {
1467 if name != kw::Invalid &&
1468 name != kw::UnderscoreLifetime {
1469 p!(write("{}", name));
1470 return Ok(self);
1471 }
1472 }
1473
1474 if let Some((region, counter)) = highlight.highlight_bound_region {
1475 if br == region {
1476 p!(write("'{}", counter));
1477 return Ok(self);
1478 }
1479 }
1480 }
1481 ty::ReScope(scope) if identify_regions => {
1482 match scope.data {
1483 region::ScopeData::Node =>
1484 p!(write("'{}s", scope.item_local_id().as_usize())),
1485 region::ScopeData::CallSite =>
1486 p!(write("'{}cs", scope.item_local_id().as_usize())),
1487 region::ScopeData::Arguments =>
1488 p!(write("'{}as", scope.item_local_id().as_usize())),
1489 region::ScopeData::Destruction =>
1490 p!(write("'{}ds", scope.item_local_id().as_usize())),
1491 region::ScopeData::Remainder(first_statement_index) => p!(write(
1492 "'{}_{}rs",
1493 scope.item_local_id().as_usize(),
1494 first_statement_index.index()
1495 )),
1496 }
1497 return Ok(self);
1498 }
1499 ty::ReVar(region_vid) if identify_regions => {
1500 p!(write("{:?}", region_vid));
1501 return Ok(self);
1502 }
1503 ty::ReVar(_) => {}
1504 ty::ReScope(_) |
1505 ty::ReErased => {}
1506 ty::ReStatic => {
1507 p!(write("'static"));
1508 return Ok(self);
1509 }
1510 ty::ReEmpty => {
1511 p!(write("'<empty>"));
1512 return Ok(self);
1513 }
1514
1515 // The user should never encounter these in unsubstituted form.
1516 ty::ReClosureBound(vid) => {
1517 p!(write("{:?}", vid));
1518 return Ok(self);
1519 }
1520 }
1521
1522 p!(write("'_"));
1523
1524 Ok(self)
1525 }
1526 }
1527
1528 // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`,
1529 // `region_index` and `used_region_names`.
1530 impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> {
1531 pub fn name_all_regions<T>(
1532 mut self,
1533 value: &ty::Binder<T>,
1534 ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error>
1535 where
1536 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1537 {
1538 fn name_by_region_index(index: usize) -> Symbol {
1539 match index {
1540 0 => Symbol::intern("'r"),
1541 1 => Symbol::intern("'s"),
1542 i => Symbol::intern(&format!("'t{}", i-2)),
1543 }
1544 }
1545
1546 // Replace any anonymous late-bound regions with named
1547 // variants, using new unique identifiers, so that we can
1548 // clearly differentiate between named and unnamed regions in
1549 // the output. We'll probably want to tweak this over time to
1550 // decide just how much information to give.
1551 if self.binder_depth == 0 {
1552 self.prepare_late_bound_region_info(value);
1553 }
1554
1555 let mut empty = true;
1556 let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
1557 write!(cx, "{}", if empty {
1558 empty = false;
1559 start
1560 } else {
1561 cont
1562 })
1563 };
1564
1565 define_scoped_cx!(self);
1566
1567 let mut region_index = self.region_index;
1568 let new_value = self.tcx.replace_late_bound_regions(value, |br| {
1569 let _ = start_or_continue(&mut self, "for<", ", ");
1570 let br = match br {
1571 ty::BrNamed(_, name) => {
1572 let _ = write!(self, "{}", name);
1573 br
1574 }
1575 ty::BrAnon(_) |
1576 ty::BrEnv => {
1577 let name = loop {
1578 let name = name_by_region_index(region_index);
1579 region_index += 1;
1580 if !self.used_region_names.contains(&name) {
1581 break name;
1582 }
1583 };
1584 let _ = write!(self, "{}", name);
1585 ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name)
1586 }
1587 };
1588 self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br))
1589 });
1590 start_or_continue(&mut self, "", "> ")?;
1591
1592 self.binder_depth += 1;
1593 self.region_index = region_index;
1594 Ok((self, new_value))
1595 }
1596
1597 pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error>
1598 where
1599 T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>,
1600 {
1601 let old_region_index = self.region_index;
1602 let (new, new_value) = self.name_all_regions(value)?;
1603 let mut inner = new_value.0.print(new)?;
1604 inner.region_index = old_region_index;
1605 inner.binder_depth -= 1;
1606 Ok(inner)
1607 }
1608
1609 fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
1610 where T: TypeFoldable<'tcx>
1611 {
1612
1613 struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>);
1614 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> {
1615 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
1616 match *r {
1617 ty::ReLateBound(_, ty::BrNamed(_, name)) => {
1618 self.0.insert(name);
1619 },
1620 _ => {},
1621 }
1622 r.super_visit_with(self)
1623 }
1624 }
1625
1626 self.used_region_names.clear();
1627 let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names);
1628 value.visit_with(&mut collector);
1629 self.region_index = 0;
1630 }
1631 }
1632
1633 impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T>
1634 where
1635 T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>,
1636 {
1637 type Output = P;
1638 type Error = P::Error;
1639 fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
1640 cx.in_binder(self)
1641 }
1642 }
1643
1644 impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U>
1645 where
1646 T: Print<'tcx, P, Output = P, Error = P::Error>,
1647 U: Print<'tcx, P, Output = P, Error = P::Error>,
1648 {
1649 type Output = P;
1650 type Error = P::Error;
1651 fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> {
1652 define_scoped_cx!(cx);
1653 p!(print(self.0), write(" : "), print(self.1));
1654 Ok(cx)
1655 }
1656 }
1657
1658 macro_rules! forward_display_to_print {
1659 ($($ty:ty),+) => {
1660 $(impl fmt::Display for $ty {
1661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1662 ty::tls::with(|tcx| {
1663 tcx.lift(self)
1664 .expect("could not lift for printing")
1665 .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1666 Ok(())
1667 })
1668 }
1669 })+
1670 };
1671 }
1672
1673 macro_rules! define_print_and_forward_display {
1674 (($self:ident, $cx:ident): $($ty:ty $print:block)+) => {
1675 $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty {
1676 type Output = P;
1677 type Error = fmt::Error;
1678 fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> {
1679 #[allow(unused_mut)]
1680 let mut $cx = $cx;
1681 define_scoped_cx!($cx);
1682 let _: () = $print;
1683 #[allow(unreachable_code)]
1684 Ok($cx)
1685 }
1686 })+
1687
1688 forward_display_to_print!($($ty),+);
1689 };
1690 }
1691
1692 // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting.
1693 impl fmt::Display for ty::RegionKind {
1694 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1695 ty::tls::with(|tcx| {
1696 self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?;
1697 Ok(())
1698 })
1699 }
1700 }
1701
1702 /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only
1703 /// the trait path. That is, it will print `Trait<U>` instead of
1704 /// `<T as Trait<U>>`.
1705 #[derive(Copy, Clone, TypeFoldable, Lift)]
1706 pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>);
1707
1708 impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> {
1709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1710 fmt::Display::fmt(self, f)
1711 }
1712 }
1713
1714 impl ty::TraitRef<'tcx> {
1715 pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> {
1716 TraitRefPrintOnlyTraitPath(self)
1717 }
1718 }
1719
1720 impl ty::Binder<ty::TraitRef<'tcx>> {
1721 pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> {
1722 self.map_bound(|tr| tr.print_only_trait_path())
1723 }
1724 }
1725
1726 forward_display_to_print! {
1727 Ty<'tcx>,
1728 &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
1729 &'tcx ty::Const<'tcx>,
1730
1731 // HACK(eddyb) these are exhaustive instead of generic,
1732 // because `for<'tcx>` isn't possible yet.
1733 ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
1734 ty::Binder<ty::TraitRef<'tcx>>,
1735 ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>,
1736 ty::Binder<ty::FnSig<'tcx>>,
1737 ty::Binder<ty::TraitPredicate<'tcx>>,
1738 ty::Binder<ty::SubtypePredicate<'tcx>>,
1739 ty::Binder<ty::ProjectionPredicate<'tcx>>,
1740 ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>,
1741 ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>,
1742
1743 ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>,
1744 ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>
1745 }
1746
1747 define_print_and_forward_display! {
1748 (self, cx):
1749
1750 &'tcx ty::List<Ty<'tcx>> {
1751 p!(write("{{"));
1752 let mut tys = self.iter();
1753 if let Some(&ty) = tys.next() {
1754 p!(print(ty));
1755 for &ty in tys {
1756 p!(write(", "), print(ty));
1757 }
1758 }
1759 p!(write("}}"))
1760 }
1761
1762 ty::TypeAndMut<'tcx> {
1763 p!(write("{}", self.mutbl.prefix_str()), print(self.ty))
1764 }
1765
1766 ty::ExistentialTraitRef<'tcx> {
1767 // Use a type that can't appear in defaults of type parameters.
1768 let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0));
1769 let trait_ref = self.with_self_ty(cx.tcx(), dummy_self);
1770 p!(print(trait_ref.print_only_trait_path()))
1771 }
1772
1773 ty::ExistentialProjection<'tcx> {
1774 let name = cx.tcx().associated_item(self.item_def_id).ident;
1775 p!(write("{} = ", name), print(self.ty))
1776 }
1777
1778 ty::ExistentialPredicate<'tcx> {
1779 match *self {
1780 ty::ExistentialPredicate::Trait(x) => p!(print(x)),
1781 ty::ExistentialPredicate::Projection(x) => p!(print(x)),
1782 ty::ExistentialPredicate::AutoTrait(def_id) => {
1783 p!(print_def_path(def_id, &[]));
1784 }
1785 }
1786 }
1787
1788 ty::FnSig<'tcx> {
1789 p!(write("{}", self.unsafety.prefix_str()));
1790
1791 if self.abi != Abi::Rust {
1792 p!(write("extern {} ", self.abi));
1793 }
1794
1795 p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output()));
1796 }
1797
1798 ty::InferTy {
1799 if cx.tcx().sess.verbose() {
1800 p!(write("{:?}", self));
1801 return Ok(cx);
1802 }
1803 match *self {
1804 ty::TyVar(_) => p!(write("_")),
1805 ty::IntVar(_) => p!(write("{}", "{integer}")),
1806 ty::FloatVar(_) => p!(write("{}", "{float}")),
1807 ty::FreshTy(v) => p!(write("FreshTy({})", v)),
1808 ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)),
1809 ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v))
1810 }
1811 }
1812
1813 ty::TraitRef<'tcx> {
1814 p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path()))
1815 }
1816
1817 TraitRefPrintOnlyTraitPath<'tcx> {
1818 p!(print_def_path(self.0.def_id, self.0.substs));
1819 }
1820
1821 ty::ParamTy {
1822 p!(write("{}", self.name))
1823 }
1824
1825 ty::ParamConst {
1826 p!(write("{}", self.name))
1827 }
1828
1829 ty::SubtypePredicate<'tcx> {
1830 p!(print(self.a), write(" <: "), print(self.b))
1831 }
1832
1833 ty::TraitPredicate<'tcx> {
1834 p!(print(self.trait_ref.self_ty()), write(": "),
1835 print(self.trait_ref.print_only_trait_path()))
1836 }
1837
1838 ty::ProjectionPredicate<'tcx> {
1839 p!(print(self.projection_ty), write(" == "), print(self.ty))
1840 }
1841
1842 ty::ProjectionTy<'tcx> {
1843 p!(print_def_path(self.item_def_id, self.substs));
1844 }
1845
1846 ty::ClosureKind {
1847 match *self {
1848 ty::ClosureKind::Fn => p!(write("Fn")),
1849 ty::ClosureKind::FnMut => p!(write("FnMut")),
1850 ty::ClosureKind::FnOnce => p!(write("FnOnce")),
1851 }
1852 }
1853
1854 ty::Predicate<'tcx> {
1855 match *self {
1856 ty::Predicate::Trait(ref data) => p!(print(data)),
1857 ty::Predicate::Subtype(ref predicate) => p!(print(predicate)),
1858 ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)),
1859 ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)),
1860 ty::Predicate::Projection(ref predicate) => p!(print(predicate)),
1861 ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")),
1862 ty::Predicate::ObjectSafe(trait_def_id) => {
1863 p!(write("the trait `"),
1864 print_def_path(trait_def_id, &[]),
1865 write("` is object-safe"))
1866 }
1867 ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => {
1868 p!(write("the closure `"),
1869 print_value_path(closure_def_id, &[]),
1870 write("` implements the trait `{}`", kind))
1871 }
1872 ty::Predicate::ConstEvaluatable(def_id, substs) => {
1873 p!(write("the constant `"),
1874 print_value_path(def_id, substs),
1875 write("` can be evaluated"))
1876 }
1877 }
1878 }
1879
1880 GenericArg<'tcx> {
1881 match self.unpack() {
1882 GenericArgKind::Lifetime(lt) => p!(print(lt)),
1883 GenericArgKind::Type(ty) => p!(print(ty)),
1884 GenericArgKind::Const(ct) => p!(print(ct)),
1885 }
1886 }
1887 }