]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print.rs
rustc: support overriding type printing in ty::print::Printer.
[rust.git] / src / librustc / ty / print.rs
1 use crate::hir::def::Namespace;
2 use crate::hir::map::DefPathData;
3 use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
4 use crate::middle::region;
5 use crate::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
6 use crate::ty::subst::{Kind, Subst, SubstsRef, UnpackedKind};
7 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
8 use syntax::symbol::{keywords, Symbol};
9
10 use rustc_data_structures::fx::FxHashSet;
11 use syntax::symbol::InternedString;
12
13 use std::cell::Cell;
14 use std::fmt::{self, Write as _};
15 use std::iter;
16 use std::ops::Deref;
17
18 thread_local! {
19     static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false);
20     static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false);
21 }
22
23 /// Force us to name impls with just the filename/line number. We
24 /// normally try to use types. But at some points, notably while printing
25 /// cycle errors, this can result in extra or suboptimal error output,
26 /// so this variable disables that check.
27 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
28     FORCE_IMPL_FILENAME_LINE.with(|force| {
29         let old = force.get();
30         force.set(true);
31         let result = f();
32         force.set(old);
33         result
34     })
35 }
36
37 /// Adds the `crate::` prefix to paths where appropriate.
38 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
39     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
40         let old = flag.get();
41         flag.set(true);
42         let result = f();
43         flag.set(old);
44         result
45     })
46 }
47
48 // FIXME(eddyb) this module uses `pub(crate)` for things used only
49 // from `ppaux` - when that is removed, they can be re-privatized.
50
51 /// The "region highlights" are used to control region printing during
52 /// specific error messages. When a "region highlight" is enabled, it
53 /// gives an alternate way to print specific regions. For now, we
54 /// always print those regions using a number, so something like "`'0`".
55 ///
56 /// Regions not selected by the region highlight mode are presently
57 /// unaffected.
58 #[derive(Copy, Clone, Default)]
59 pub struct RegionHighlightMode {
60     /// If enabled, when we see the selected region, use "`'N`"
61     /// instead of the ordinary behavior.
62     highlight_regions: [Option<(ty::RegionKind, usize)>; 3],
63
64     /// If enabled, when printing a "free region" that originated from
65     /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily
66     /// have names print as normal.
67     ///
68     /// This is used when you have a signature like `fn foo(x: &u32,
69     /// y: &'a u32)` and we want to give a name to the region of the
70     /// reference `x`.
71     highlight_bound_region: Option<(ty::BoundRegion, usize)>,
72 }
73
74 impl RegionHighlightMode {
75     /// If `region` and `number` are both `Some`, invokes
76     /// `highlighting_region`.
77     pub fn maybe_highlighting_region(
78         &mut self,
79         region: Option<ty::Region<'_>>,
80         number: Option<usize>,
81     ) {
82         if let Some(k) = region {
83             if let Some(n) = number {
84                 self.highlighting_region(k, n);
85             }
86         }
87     }
88
89     /// Highlights the region inference variable `vid` as `'N`.
90     pub fn highlighting_region(
91         &mut self,
92         region: ty::Region<'_>,
93         number: usize,
94     ) {
95         let num_slots = self.highlight_regions.len();
96         let first_avail_slot = self.highlight_regions.iter_mut()
97             .filter(|s| s.is_none())
98             .next()
99             .unwrap_or_else(|| {
100                 bug!(
101                     "can only highlight {} placeholders at a time",
102                     num_slots,
103                 )
104             });
105         *first_avail_slot = Some((*region, number));
106     }
107
108     /// Convenience wrapper for `highlighting_region`.
109     pub fn highlighting_region_vid(
110         &mut self,
111         vid: ty::RegionVid,
112         number: usize,
113     ) {
114         self.highlighting_region(&ty::ReVar(vid), number)
115     }
116
117     /// Returns `Some(n)` with the number to use for the given region, if any.
118     fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> {
119         self
120             .highlight_regions
121             .iter()
122             .filter_map(|h| match h {
123                 Some((r, n)) if r == region => Some(*n),
124                 _ => None,
125             })
126             .next()
127     }
128
129     /// Highlight the given bound region.
130     /// We can only highlight one bound region at a time. See
131     /// the field `highlight_bound_region` for more detailed notes.
132     pub fn highlighting_bound_region(
133         &mut self,
134         br: ty::BoundRegion,
135         number: usize,
136     ) {
137         assert!(self.highlight_bound_region.is_none());
138         self.highlight_bound_region = Some((br, number));
139     }
140 }
141
142 struct LateBoundRegionNameCollector(FxHashSet<InternedString>);
143 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector {
144     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
145         match *r {
146             ty::ReLateBound(_, ty::BrNamed(_, name)) => {
147                 self.0.insert(name);
148             },
149             _ => {},
150         }
151         r.super_visit_with(self)
152     }
153 }
154
155 pub(crate) struct PrintConfig {
156     pub(crate) is_debug: bool,
157     pub(crate) is_verbose: bool,
158     pub(crate) identify_regions: bool,
159     pub(crate) used_region_names: Option<FxHashSet<InternedString>>,
160     pub(crate) region_index: usize,
161     pub(crate) binder_depth: usize,
162 }
163
164 impl PrintConfig {
165     pub(crate) fn new(tcx: TyCtxt<'_, '_, '_>) -> Self {
166         PrintConfig {
167             is_debug: false,
168             is_verbose: tcx.sess.verbose(),
169             identify_regions: tcx.sess.opts.debugging_opts.identify_regions,
170             used_region_names: None,
171             region_index: 0,
172             binder_depth: 0,
173         }
174     }
175 }
176
177 pub struct PrintCx<'a, 'gcx, 'tcx, P> {
178     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
179     pub printer: P,
180     pub(crate) config: &'a mut PrintConfig,
181 }
182
183 // HACK(eddyb) this is solely for `self: PrintCx<Self>`, e.g. to
184 // implement traits on the printer and call the methods on the context.
185 impl<P> Deref for PrintCx<'_, '_, '_, P> {
186     type Target = P;
187     fn deref(&self) -> &P {
188         &self.printer
189     }
190 }
191
192 impl<'a, 'gcx, 'tcx, P> PrintCx<'a, 'gcx, 'tcx, P> {
193     pub fn with<R>(
194         tcx: TyCtxt<'a, 'gcx, 'tcx>,
195         printer: P,
196         f: impl FnOnce(PrintCx<'_, 'gcx, 'tcx, P>) -> R,
197     ) -> R {
198         f(PrintCx {
199             tcx,
200             printer,
201             config: &mut PrintConfig::new(tcx),
202         })
203     }
204
205     pub(crate) fn with_tls_tcx<R>(printer: P, f: impl FnOnce(PrintCx<'_, '_, '_, P>) -> R) -> R {
206         ty::tls::with(|tcx| PrintCx::with(tcx, printer, f))
207     }
208     pub(crate) fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
209     where T: TypeFoldable<'tcx>
210     {
211         let mut collector = LateBoundRegionNameCollector(Default::default());
212         value.visit_with(&mut collector);
213         self.config.used_region_names = Some(collector.0);
214         self.config.region_index = 0;
215     }
216 }
217
218 pub trait Print<'tcx, P> {
219     type Output;
220     type Error;
221
222     fn print(&self, cx: PrintCx<'_, '_, 'tcx, P>) -> Result<Self::Output, Self::Error>;
223     fn print_display(
224         &self,
225         cx: PrintCx<'_, '_, 'tcx, P>,
226     ) -> Result<Self::Output, Self::Error> {
227         let old_debug = cx.config.is_debug;
228         cx.config.is_debug = false;
229         let result = self.print(PrintCx {
230             tcx: cx.tcx,
231             printer: cx.printer,
232             config: cx.config,
233         });
234         cx.config.is_debug = old_debug;
235         result
236     }
237     fn print_debug(&self, cx: PrintCx<'_, '_, 'tcx, P>) -> Result<Self::Output, Self::Error> {
238         let old_debug = cx.config.is_debug;
239         cx.config.is_debug = true;
240         let result = self.print(PrintCx {
241             tcx: cx.tcx,
242             printer: cx.printer,
243             config: cx.config,
244         });
245         cx.config.is_debug = old_debug;
246         result
247     }
248 }
249
250 pub trait Printer: Sized {
251     type Error;
252
253     type Path;
254     type Region;
255     type Type;
256
257     fn print_def_path(
258         self: PrintCx<'_, '_, 'tcx, Self>,
259         def_id: DefId,
260         substs: Option<SubstsRef<'tcx>>,
261         ns: Namespace,
262         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
263     ) -> Result<Self::Path, Self::Error> {
264         self.default_print_def_path(def_id, substs, ns, projections)
265     }
266     fn print_impl_path(
267         self: PrintCx<'_, '_, 'tcx, Self>,
268         impl_def_id: DefId,
269         substs: Option<SubstsRef<'tcx>>,
270         ns: Namespace,
271         self_ty: Ty<'tcx>,
272         trait_ref: Option<ty::TraitRef<'tcx>>,
273     ) -> Result<Self::Path, Self::Error> {
274         self.default_print_impl_path(impl_def_id, substs, ns, self_ty, trait_ref)
275     }
276
277     fn print_region(
278         self: PrintCx<'_, '_, '_, Self>,
279         region: ty::Region<'_>,
280     ) -> Result<Self::Region, Self::Error>;
281
282     fn print_type(
283         self: PrintCx<'_, '_, 'tcx, Self>,
284         ty: Ty<'tcx>,
285     ) -> Result<Self::Type, Self::Error>;
286
287     fn path_crate(
288         self: PrintCx<'_, '_, '_, Self>,
289         cnum: CrateNum,
290     ) -> Result<Self::Path, Self::Error>;
291     fn path_qualified(
292         self: PrintCx<'_, '_, 'tcx, Self>,
293         self_ty: Ty<'tcx>,
294         trait_ref: Option<ty::TraitRef<'tcx>>,
295         ns: Namespace,
296     ) -> Result<Self::Path, Self::Error>;
297
298     fn path_append_impl<'gcx, 'tcx>(
299         self: PrintCx<'_, 'gcx, 'tcx, Self>,
300         print_prefix: impl FnOnce(
301             PrintCx<'_, 'gcx, 'tcx, Self>,
302         ) -> Result<Self::Path, Self::Error>,
303         self_ty: Ty<'tcx>,
304         trait_ref: Option<ty::TraitRef<'tcx>>,
305     ) -> Result<Self::Path, Self::Error>;
306     fn path_append<'gcx, 'tcx>(
307         self: PrintCx<'_, 'gcx, 'tcx, Self>,
308         print_prefix: impl FnOnce(
309             PrintCx<'_, 'gcx, 'tcx, Self>,
310         ) -> Result<Self::Path, Self::Error>,
311         text: &str,
312     ) -> Result<Self::Path, Self::Error>;
313     fn path_generic_args<'gcx, 'tcx>(
314         self: PrintCx<'_, 'gcx, 'tcx, Self>,
315         print_prefix: impl FnOnce(
316             PrintCx<'_, 'gcx, 'tcx, Self>,
317         ) -> Result<Self::Path, Self::Error>,
318         params: &[ty::GenericParamDef],
319         substs: SubstsRef<'tcx>,
320         ns: Namespace,
321         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
322     ) -> Result<Self::Path, Self::Error>;
323 }
324
325 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
326 pub trait PrettyPrinter:
327     Printer<
328         Error = fmt::Error,
329         Path = Self,
330         Region = Self,
331         Type = Self,
332     > +
333     fmt::Write
334 {
335     /// Enter a nested print context, for pretty-printing
336     /// nested components in some larger context.
337     fn nest<'a, 'gcx, 'tcx, E>(
338         self: PrintCx<'a, 'gcx, 'tcx, Self>,
339         f: impl for<'b> FnOnce(PrintCx<'b, 'gcx, 'tcx, Self>) -> Result<Self, E>,
340     ) -> Result<PrintCx<'a, 'gcx, 'tcx, Self>, E> {
341         let printer = f(PrintCx {
342             tcx: self.tcx,
343             printer: self.printer,
344             config: self.config,
345         })?;
346         Ok(PrintCx {
347             tcx: self.tcx,
348             printer,
349             config: self.config,
350         })
351     }
352
353     /// Return `true` if the region should be printed in path generic args
354     /// even when it's `'_`, such as in e.g. `Foo<'_, '_, '_>`.
355     fn always_print_region_in_paths(
356         self: &PrintCx<'_, '_, '_, Self>,
357         _region: ty::Region<'_>,
358     ) -> bool {
359         false
360     }
361
362     // HACK(eddyb) Trying to print a lifetime might not print anything, which
363     // may need special handling in the caller (of `ty::RegionKind::print`).
364     // To avoid printing to a temporary string (which isn't even supported),
365     // the `print_region_outputs_anything` method can instead be used to
366     // determine this, ahead of time.
367     //
368     // NB: this must be kept in sync with the implementation of `print_region`.
369     fn print_region_outputs_anything(
370         self: &PrintCx<'_, '_, '_, Self>,
371         region: ty::Region<'_>,
372     ) -> bool;
373 }
374
375 macro_rules! nest {
376     ($cx:ident, $closure:expr) => {
377         $cx = $cx.nest($closure)?
378     }
379 }
380
381 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
382     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
383     // (but also some things just print a `DefId` generally so maybe we need this?)
384     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
385         match self.def_key(def_id).disambiguated_data.data {
386             DefPathData::ValueNs(..) |
387             DefPathData::EnumVariant(..) |
388             DefPathData::Field(..) |
389             DefPathData::AnonConst |
390             DefPathData::ConstParam(..) |
391             DefPathData::ClosureExpr |
392             DefPathData::StructCtor => Namespace::ValueNS,
393
394             DefPathData::MacroDef(..) => Namespace::MacroNS,
395
396             _ => Namespace::TypeNS,
397         }
398     }
399
400     /// Returns a string identifying this `DefId`. This string is
401     /// suitable for user output.
402     pub fn def_path_str(self, def_id: DefId) -> String {
403         let ns = self.guess_def_namespace(def_id);
404         debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns);
405         let mut s = String::new();
406         let _ = PrintCx::with(self, FmtPrinter::new(&mut s), |cx| {
407             cx.print_def_path(def_id, None, ns, iter::empty())
408         });
409         s
410     }
411 }
412
413 impl<P: Printer> PrintCx<'a, 'gcx, 'tcx, P> {
414     pub fn default_print_def_path(
415         self,
416         def_id: DefId,
417         substs: Option<SubstsRef<'tcx>>,
418         ns: Namespace,
419         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
420     ) -> Result<P::Path, P::Error> {
421         debug!("default_print_def_path: def_id={:?}, substs={:?}, ns={:?}", def_id, substs, ns);
422         let key = self.tcx.def_key(def_id);
423         debug!("default_print_def_path: key={:?}", key);
424
425         match key.disambiguated_data.data {
426             DefPathData::CrateRoot => {
427                 assert!(key.parent.is_none());
428                 self.path_crate(def_id.krate)
429             }
430
431             DefPathData::Impl => {
432                 let mut self_ty = self.tcx.type_of(def_id);
433                 if let Some(substs) = substs {
434                     self_ty = self_ty.subst(self.tcx, substs);
435                 }
436
437                 let mut impl_trait_ref = self.tcx.impl_trait_ref(def_id);
438                 if let Some(substs) = substs {
439                     impl_trait_ref = impl_trait_ref.subst(self.tcx, substs);
440                 }
441                 self.print_impl_path(def_id, substs, ns, self_ty, impl_trait_ref)
442             }
443
444             _ => {
445                 let generics = substs.map(|_| self.tcx.generics_of(def_id));
446                 let generics_parent = generics.as_ref().and_then(|g| g.parent);
447                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
448                 let print_parent_path = |cx: PrintCx<'_, 'gcx, 'tcx, P>| {
449                     if let Some(generics_parent_def_id) = generics_parent {
450                         assert_eq!(parent_def_id, generics_parent_def_id);
451
452                         // FIXME(eddyb) try to move this into the parent's printing
453                         // logic, instead of doing it when printing the child.
454                         let parent_generics = cx.tcx.generics_of(parent_def_id);
455                         let parent_has_own_self =
456                             parent_generics.has_self && parent_generics.parent_count == 0;
457                         if let (Some(substs), true) = (substs, parent_has_own_self) {
458                             let trait_ref = ty::TraitRef::new(parent_def_id, substs);
459                             cx.path_qualified(trait_ref.self_ty(), Some(trait_ref), ns)
460                         } else {
461                             cx.print_def_path(parent_def_id, substs, ns, iter::empty())
462                         }
463                     } else {
464                         cx.print_def_path(parent_def_id, None, ns, iter::empty())
465                     }
466                 };
467                 let print_path = |cx: PrintCx<'_, 'gcx, 'tcx, P>| {
468                     match key.disambiguated_data.data {
469                         // Skip `::{{constructor}}` on tuple/unit structs.
470                         DefPathData::StructCtor => print_parent_path(cx),
471
472                         _ => {
473                             cx.path_append(
474                                 print_parent_path,
475                                 &key.disambiguated_data.data.as_interned_str().as_str(),
476                             )
477                         }
478                     }
479                 };
480
481                 if let (Some(generics), Some(substs)) = (generics, substs) {
482                     let has_own_self = generics.has_self && generics.parent_count == 0;
483                     let params = &generics.params[has_own_self as usize..];
484                     self.path_generic_args(print_path, params, substs, ns, projections)
485                 } else {
486                     print_path(self)
487                 }
488             }
489         }
490     }
491
492     fn default_print_impl_path(
493         self,
494         impl_def_id: DefId,
495         _substs: Option<SubstsRef<'tcx>>,
496         ns: Namespace,
497         self_ty: Ty<'tcx>,
498         impl_trait_ref: Option<ty::TraitRef<'tcx>>,
499     ) -> Result<P::Path, P::Error> {
500         debug!("default_print_impl_path: impl_def_id={:?}, self_ty={}, impl_trait_ref={:?}",
501                impl_def_id, self_ty, impl_trait_ref);
502
503         // Decide whether to print the parent path for the impl.
504         // Logically, since impls are global, it's never needed, but
505         // users may find it useful. Currently, we omit the parent if
506         // the impl is either in the same module as the self-type or
507         // as the trait.
508         let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
509         let in_self_mod = match characteristic_def_id_of_type(self_ty) {
510             None => false,
511             Some(ty_def_id) => self.tcx.parent(ty_def_id) == Some(parent_def_id),
512         };
513         let in_trait_mod = match impl_trait_ref {
514             None => false,
515             Some(trait_ref) => self.tcx.parent(trait_ref.def_id) == Some(parent_def_id),
516         };
517
518         if !in_self_mod && !in_trait_mod {
519             // If the impl is not co-located with either self-type or
520             // trait-type, then fallback to a format that identifies
521             // the module more clearly.
522             self.path_append_impl(
523                 |cx| cx.print_def_path(parent_def_id, None, ns, iter::empty()),
524                 self_ty,
525                 impl_trait_ref,
526             )
527         } else {
528             // Otherwise, try to give a good form that would be valid language
529             // syntax. Preferably using associated item notation.
530             self.path_qualified(self_ty, impl_trait_ref, ns)
531         }
532     }
533 }
534
535 /// As a heuristic, when we see an impl, if we see that the
536 /// 'self type' is a type defined in the same module as the impl,
537 /// we can omit including the path to the impl itself. This
538 /// function tries to find a "characteristic `DefId`" for a
539 /// type. It's just a heuristic so it makes some questionable
540 /// decisions and we may want to adjust it later.
541 pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
542     match ty.sty {
543         ty::Adt(adt_def, _) => Some(adt_def.did),
544
545         ty::Dynamic(data, ..) => data.principal_def_id(),
546
547         ty::Array(subty, _) |
548         ty::Slice(subty) => characteristic_def_id_of_type(subty),
549
550         ty::RawPtr(mt) => characteristic_def_id_of_type(mt.ty),
551
552         ty::Ref(_, ty, _) => characteristic_def_id_of_type(ty),
553
554         ty::Tuple(ref tys) => tys.iter()
555                                    .filter_map(|ty| characteristic_def_id_of_type(ty))
556                                    .next(),
557
558         ty::FnDef(def_id, _) |
559         ty::Closure(def_id, _) |
560         ty::Generator(def_id, _, _) |
561         ty::Foreign(def_id) => Some(def_id),
562
563         ty::Bool |
564         ty::Char |
565         ty::Int(_) |
566         ty::Uint(_) |
567         ty::Str |
568         ty::FnPtr(_) |
569         ty::Projection(_) |
570         ty::Placeholder(..) |
571         ty::UnnormalizedProjection(..) |
572         ty::Param(_) |
573         ty::Opaque(..) |
574         ty::Infer(_) |
575         ty::Bound(..) |
576         ty::Error |
577         ty::GeneratorWitness(..) |
578         ty::Never |
579         ty::Float(_) => None,
580     }
581 }
582
583 pub struct FmtPrinter<F: fmt::Write> {
584     pub(crate) fmt: F,
585     empty: bool,
586     pub region_highlight_mode: RegionHighlightMode,
587 }
588
589 impl<F: fmt::Write> FmtPrinter<F> {
590     pub fn new(fmt: F) -> Self {
591         FmtPrinter {
592             fmt,
593             empty: true,
594             region_highlight_mode: RegionHighlightMode::default(),
595         }
596     }
597 }
598
599 impl<'gcx, 'tcx, P: PrettyPrinter> PrintCx<'_, 'gcx, 'tcx, P> {
600     /// If possible, this returns a global path resolving to `def_id` that is visible
601     /// from at least one local module and returns true. If the crate defining `def_id` is
602     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
603     fn try_print_visible_def_path(
604         mut self,
605         def_id: DefId,
606     ) -> Result<(P, bool), P::Error> {
607         debug!("try_print_visible_def_path: def_id={:?}", def_id);
608
609         // If `def_id` is a direct or injected extern crate, return the
610         // path to the crate followed by the path to the item within the crate.
611         if def_id.index == CRATE_DEF_INDEX {
612             let cnum = def_id.krate;
613
614             if cnum == LOCAL_CRATE {
615                 return Ok((self.path_crate(cnum)?, true));
616             }
617
618             // In local mode, when we encounter a crate other than
619             // LOCAL_CRATE, execution proceeds in one of two ways:
620             //
621             // 1. for a direct dependency, where user added an
622             //    `extern crate` manually, we put the `extern
623             //    crate` as the parent. So you wind up with
624             //    something relative to the current crate.
625             // 2. for an extern inferred from a path or an indirect crate,
626             //    where there is no explicit `extern crate`, we just prepend
627             //    the crate name.
628             match *self.tcx.extern_crate(def_id) {
629                 Some(ExternCrate {
630                     src: ExternCrateSource::Extern(def_id),
631                     direct: true,
632                     span,
633                     ..
634                 }) => {
635                     debug!("try_print_visible_def_path: def_id={:?}", def_id);
636                     return Ok((if !span.is_dummy() {
637                         self.print_def_path(def_id, None, Namespace::TypeNS, iter::empty())?
638                     } else {
639                         self.path_crate(cnum)?
640                     }, true));
641                 }
642                 None => {
643                     return Ok((self.path_crate(cnum)?, true));
644                 }
645                 _ => {},
646             }
647         }
648
649         if def_id.is_local() {
650             return Ok((self.printer, false));
651         }
652
653         let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
654
655         let mut cur_def_key = self.tcx.def_key(def_id);
656         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
657
658         // For a UnitStruct or TupleStruct we want the name of its parent rather than <unnamed>.
659         if let DefPathData::StructCtor = cur_def_key.disambiguated_data.data {
660             let parent = DefId {
661                 krate: def_id.krate,
662                 index: cur_def_key.parent.expect("DefPathData::StructCtor missing a parent"),
663             };
664
665             cur_def_key = self.tcx.def_key(parent);
666         }
667
668         let visible_parent = match visible_parent_map.get(&def_id).cloned() {
669             Some(parent) => parent,
670             None => return Ok((self.printer, false)),
671         };
672         // HACK(eddyb) this uses `nest` to avoid knowing ahead of time whether
673         // the entire path will succeed or not. To support printers that do not
674         // implement `PrettyPrinter`, a `Vec` or linked list on the stack would
675         // need to be built, before starting to print anything.
676         let mut prefix_success = false;
677         nest!(self, |cx| {
678             let (printer, success) = cx.try_print_visible_def_path(visible_parent)?;
679             prefix_success = success;
680             Ok(printer)
681         });
682         if !prefix_success {
683             return Ok((self.printer, false));
684         };
685         let actual_parent = self.tcx.parent(def_id);
686
687         let data = cur_def_key.disambiguated_data.data;
688         debug!(
689             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
690             data, visible_parent, actual_parent,
691         );
692
693         let symbol = match data {
694             // In order to output a path that could actually be imported (valid and visible),
695             // we need to handle re-exports correctly.
696             //
697             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
698             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
699             //
700             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
701             // private so the "true" path to `CommandExt` isn't accessible.
702             //
703             // In this case, the `visible_parent_map` will look something like this:
704             //
705             // (child) -> (parent)
706             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
707             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
708             // `std::sys::unix::ext` -> `std::os`
709             //
710             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
711             // `std::os`.
712             //
713             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
714             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
715             // to the parent - resulting in a mangled path like
716             // `std::os::ext::process::CommandExt`.
717             //
718             // Instead, we must detect that there was a re-export and instead print `unix`
719             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
720             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
721             // the visible parent (`std::os`). If these do not match, then we iterate over
722             // the children of the visible parent (as was done when computing
723             // `visible_parent_map`), looking for the specific child we currently have and then
724             // have access to the re-exported name.
725             DefPathData::Module(actual_name) |
726             DefPathData::TypeNs(actual_name) if Some(visible_parent) != actual_parent => {
727                 self.tcx.item_children(visible_parent)
728                     .iter()
729                     .find(|child| child.def.def_id() == def_id)
730                     .map(|child| child.ident.as_str())
731                     .unwrap_or_else(|| actual_name.as_str())
732             }
733             _ => {
734                 data.get_opt_name().map(|n| n.as_str()).unwrap_or_else(|| {
735                     // Re-exported `extern crate` (#43189).
736                     if let DefPathData::CrateRoot = data {
737                         self.tcx.original_crate_name(def_id.krate).as_str()
738                     } else {
739                         Symbol::intern("<unnamed>").as_str()
740                     }
741                 })
742             },
743         };
744         debug!("try_print_visible_def_path: symbol={:?}", symbol);
745         Ok((self.path_append(|cx| Ok(cx.printer), &symbol)?, true))
746     }
747
748     pub fn pretty_path_qualified(
749         mut self,
750         self_ty: Ty<'tcx>,
751         trait_ref: Option<ty::TraitRef<'tcx>>,
752         ns: Namespace,
753     ) -> Result<P::Path, P::Error> {
754         if trait_ref.is_none() {
755             // Inherent impls. Try to print `Foo::bar` for an inherent
756             // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
757             // anything other than a simple path.
758             match self_ty.sty {
759                 ty::Adt(adt_def, substs) => {
760                     return self.print_def_path(adt_def.did, Some(substs), ns, iter::empty());
761                 }
762                 ty::Foreign(did) => {
763                     return self.print_def_path(did, None, ns, iter::empty());
764                 }
765
766                 ty::Bool | ty::Char | ty::Str |
767                 ty::Int(_) | ty::Uint(_) | ty::Float(_) => {
768                     return self_ty.print_display(self);
769                 }
770
771                 _ => {}
772             }
773         }
774
775         write!(self.printer, "<")?;
776         nest!(self, |cx| self_ty.print_display(cx));
777         if let Some(trait_ref) = trait_ref {
778             write!(self.printer, " as ")?;
779             nest!(self, |cx| cx.print_def_path(
780                 trait_ref.def_id,
781                 Some(trait_ref.substs),
782                 Namespace::TypeNS,
783                 iter::empty(),
784             ));
785         }
786         write!(self.printer, ">")?;
787
788         Ok(self.printer)
789     }
790
791     pub fn pretty_path_append_impl(
792         mut self,
793         print_prefix: impl FnOnce(
794             PrintCx<'_, 'gcx, 'tcx, P>,
795         ) -> Result<P::Path, P::Error>,
796         self_ty: Ty<'tcx>,
797         trait_ref: Option<ty::TraitRef<'tcx>>,
798     ) -> Result<P::Path, P::Error> {
799         // HACK(eddyb) going through `path_append` means symbol name
800         // computation gets to handle its equivalent of `::` correctly.
801         nest!(self, |cx| cx.path_append(print_prefix, "<impl "));
802         if let Some(trait_ref) = trait_ref {
803             nest!(self, |cx| trait_ref.print_display(cx));
804             write!(self.printer, " for ")?;
805         }
806         nest!(self, |cx| self_ty.print_display(cx));
807         write!(self.printer, ">")?;
808
809         Ok(self.printer)
810     }
811
812     pub fn pretty_path_generic_args(
813         mut self,
814         print_prefix: impl FnOnce(
815             PrintCx<'_, 'gcx, 'tcx, P>,
816         ) -> Result<P::Path, P::Error>,
817         params: &[ty::GenericParamDef],
818         substs: SubstsRef<'tcx>,
819         ns: Namespace,
820         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
821     ) -> Result<P::Path, P::Error> {
822         nest!(self, |cx| print_prefix(cx));
823
824         let mut empty = true;
825         let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| {
826             write!(cx.printer, "{}", if empty {
827                 empty = false;
828                 start
829             } else {
830                 cont
831             })
832         };
833
834         let start = if ns == Namespace::ValueNS { "::<" } else { "<" };
835
836         // Don't print `'_` if there's no printed region.
837         let print_regions = params.iter().any(|param| {
838             match substs[param.index as usize].unpack() {
839                 UnpackedKind::Lifetime(r) => {
840                     self.always_print_region_in_paths(r) ||
841                     self.print_region_outputs_anything(r)
842                 }
843                 _ => false,
844             }
845         });
846
847         // Don't print args that are the defaults of their respective parameters.
848         let num_supplied_defaults = if self.config.is_verbose {
849             0
850         } else {
851             params.iter().rev().take_while(|param| {
852                 match param.kind {
853                     ty::GenericParamDefKind::Lifetime => false,
854                     ty::GenericParamDefKind::Type { has_default, .. } => {
855                         has_default && substs[param.index as usize] == Kind::from(
856                             self.tcx.type_of(param.def_id).subst(self.tcx, substs)
857                         )
858                     }
859                     ty::GenericParamDefKind::Const => false, // FIXME(const_generics:defaults)
860                 }
861             }).count()
862         };
863
864         for param in &params[..params.len() - num_supplied_defaults] {
865             match substs[param.index as usize].unpack() {
866                 UnpackedKind::Lifetime(region) => {
867                     if !print_regions {
868                         continue;
869                     }
870                     start_or_continue(&mut self, start, ", ")?;
871                     if !self.print_region_outputs_anything(region) {
872                         // This happens when the value of the region
873                         // parameter is not easily serialized. This may be
874                         // because the user omitted it in the first place,
875                         // or because it refers to some block in the code,
876                         // etc. I'm not sure how best to serialize this.
877                         write!(self.printer, "'_")?;
878                     } else {
879                         nest!(self, |cx| region.print_display(cx));
880                     }
881                 }
882                 UnpackedKind::Type(ty) => {
883                     start_or_continue(&mut self, start, ", ")?;
884                     nest!(self, |cx| ty.print_display(cx));
885                 }
886                 UnpackedKind::Const(ct) => {
887                     start_or_continue(&mut self, start, ", ")?;
888                     nest!(self, |cx| ct.print_display(cx));
889                 }
890             }
891         }
892
893         for projection in projections {
894             start_or_continue(&mut self, start, ", ")?;
895             write!(self.printer, "{}=",
896                    self.tcx.associated_item(projection.item_def_id).ident)?;
897             nest!(self, |cx| projection.ty.print_display(cx));
898         }
899
900         start_or_continue(&mut self, "", ">")?;
901
902         Ok(self.printer)
903     }
904 }
905
906 impl<F: fmt::Write> fmt::Write for FmtPrinter<F> {
907     fn write_str(&mut self, s: &str) -> fmt::Result {
908         self.empty &= s.is_empty();
909         self.fmt.write_str(s)
910     }
911 }
912
913 impl<F: fmt::Write> Printer for FmtPrinter<F> {
914     type Error = fmt::Error;
915
916     type Path = Self;
917     type Region = Self;
918     type Type = Self;
919
920     fn print_def_path(
921         mut self: PrintCx<'_, '_, 'tcx, Self>,
922         def_id: DefId,
923         substs: Option<SubstsRef<'tcx>>,
924         ns: Namespace,
925         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
926     ) -> Result<Self::Path, Self::Error> {
927         // FIXME(eddyb) avoid querying `tcx.generics_of` and `tcx.def_key`
928         // both here and in `default_print_def_path`.
929         let generics = substs.map(|_| self.tcx.generics_of(def_id));
930         if generics.as_ref().and_then(|g| g.parent).is_none() {
931             let mut visible_path_success = false;
932             nest!(self, |cx| {
933                 let (printer, success) = cx.try_print_visible_def_path(def_id)?;
934                 visible_path_success = success;
935                 Ok(printer)
936             });
937             if visible_path_success {
938                 return if let (Some(generics), Some(substs)) = (generics, substs) {
939                     let has_own_self = generics.has_self && generics.parent_count == 0;
940                     let params = &generics.params[has_own_self as usize..];
941                     self.path_generic_args(|cx| Ok(cx.printer), params, substs, ns, projections)
942                 } else {
943                     Ok(self.printer)
944                 };
945             }
946         }
947
948         let key = self.tcx.def_key(def_id);
949         if let DefPathData::Impl = key.disambiguated_data.data {
950             // Always use types for non-local impls, where types are always
951             // available, and filename/line-number is mostly uninteresting.
952             let use_types =
953                 !def_id.is_local() || {
954                     // Otherwise, use filename/line-number if forced.
955                     let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
956                     !force_no_types
957                 };
958
959             if !use_types {
960                 // If no type info is available, fall back to
961                 // pretty printing some span information. This should
962                 // only occur very early in the compiler pipeline.
963                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
964                 let span = self.tcx.def_span(def_id);
965                 return self.path_append(
966                     |cx| cx.print_def_path(parent_def_id, None, ns, iter::empty()),
967                     &format!("<impl at {:?}>", span),
968                 );
969             }
970         }
971
972         self.default_print_def_path(def_id, substs, ns, projections)
973     }
974
975     fn print_region(
976         mut self: PrintCx<'_, '_, '_, Self>,
977         region: ty::Region<'_>,
978     ) -> Result<Self::Region, Self::Error> {
979         // Watch out for region highlights.
980         let highlight = self.printer.region_highlight_mode;
981         if let Some(n) = highlight.region_highlighted(region) {
982             write!(self.printer, "'{}", n)?;
983             return Ok(self.printer);
984         }
985
986         if self.config.is_verbose {
987             return region.print_debug(self);
988         }
989
990         // These printouts are concise.  They do not contain all the information
991         // the user might want to diagnose an error, but there is basically no way
992         // to fit that into a short string.  Hence the recommendation to use
993         // `explain_region()` or `note_and_explain_region()`.
994         match *region {
995             ty::ReEarlyBound(ref data) => {
996                 if data.name != "'_" {
997                     write!(self.printer, "{}", data.name)?;
998                 }
999             }
1000             ty::ReLateBound(_, br) |
1001             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1002             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1003                 if let ty::BrNamed(_, name) = br {
1004                     if name != "" && name != "'_" {
1005                         write!(self.printer, "{}", name)?;
1006                         return Ok(self.printer);
1007                     }
1008                 }
1009
1010                 if let Some((region, counter)) = highlight.highlight_bound_region {
1011                     if br == region {
1012                         write!(self.printer, "'{}", counter)?;
1013                     }
1014                 }
1015             }
1016             ty::ReScope(scope) if self.config.identify_regions => {
1017                 match scope.data {
1018                     region::ScopeData::Node =>
1019                         write!(self.printer, "'{}s", scope.item_local_id().as_usize())?,
1020                     region::ScopeData::CallSite =>
1021                         write!(self.printer, "'{}cs", scope.item_local_id().as_usize())?,
1022                     region::ScopeData::Arguments =>
1023                         write!(self.printer, "'{}as", scope.item_local_id().as_usize())?,
1024                     region::ScopeData::Destruction =>
1025                         write!(self.printer, "'{}ds", scope.item_local_id().as_usize())?,
1026                     region::ScopeData::Remainder(first_statement_index) => write!(self.printer,
1027                         "'{}_{}rs",
1028                         scope.item_local_id().as_usize(),
1029                         first_statement_index.index()
1030                     )?,
1031                 }
1032             }
1033             ty::ReVar(region_vid) if self.config.identify_regions => {
1034                 write!(self.printer, "{:?}", region_vid)?;
1035             }
1036             ty::ReVar(_) => {}
1037             ty::ReScope(_) |
1038             ty::ReErased => {}
1039             ty::ReStatic => write!(self.printer, "'static")?,
1040             ty::ReEmpty => write!(self.printer, "'<empty>")?,
1041
1042             // The user should never encounter these in unsubstituted form.
1043             ty::ReClosureBound(vid) => write!(self.printer, "{:?}", vid)?,
1044         }
1045
1046         Ok(self.printer)
1047     }
1048
1049     fn print_type(
1050         self: PrintCx<'_, '_, 'tcx, Self>,
1051         ty: Ty<'tcx>,
1052     ) -> Result<Self::Type, Self::Error> {
1053         self.pretty_print_type(ty)
1054     }
1055
1056     fn path_crate(
1057         mut self: PrintCx<'_, '_, '_, Self>,
1058         cnum: CrateNum,
1059     ) -> Result<Self::Path, Self::Error> {
1060         if cnum == LOCAL_CRATE {
1061             if self.tcx.sess.rust_2018() {
1062                 // We add the `crate::` keyword on Rust 2018, only when desired.
1063                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
1064                     write!(self.printer, "{}", keywords::Crate.name())?;
1065                 }
1066             }
1067             Ok(self.printer)
1068         } else {
1069             write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
1070             Ok(self.printer)
1071         }
1072     }
1073     fn path_qualified(
1074         self: PrintCx<'_, '_, 'tcx, Self>,
1075         self_ty: Ty<'tcx>,
1076         trait_ref: Option<ty::TraitRef<'tcx>>,
1077         ns: Namespace,
1078     ) -> Result<Self::Path, Self::Error> {
1079         self.pretty_path_qualified(self_ty, trait_ref, ns)
1080     }
1081
1082     fn path_append_impl<'gcx, 'tcx>(
1083         self: PrintCx<'_, 'gcx, 'tcx, Self>,
1084         print_prefix: impl FnOnce(
1085             PrintCx<'_, 'gcx, 'tcx, Self>,
1086         ) -> Result<Self::Path, Self::Error>,
1087         self_ty: Ty<'tcx>,
1088         trait_ref: Option<ty::TraitRef<'tcx>>,
1089     ) -> Result<Self::Path, Self::Error> {
1090         self.pretty_path_append_impl(print_prefix, self_ty, trait_ref)
1091     }
1092     fn path_append<'gcx, 'tcx>(
1093         self: PrintCx<'_, 'gcx, 'tcx, Self>,
1094         print_prefix: impl FnOnce(
1095             PrintCx<'_, 'gcx, 'tcx, Self>,
1096         ) -> Result<Self::Path, Self::Error>,
1097         text: &str,
1098     ) -> Result<Self::Path, Self::Error> {
1099         let mut printer = print_prefix(self)?;
1100
1101         // FIXME(eddyb) `text` should never be empty, but it
1102         // currently is for `extern { ... }` "foreign modules".
1103         if !text.is_empty() {
1104             if !printer.empty {
1105                 write!(printer, "::")?;
1106             }
1107             write!(printer, "{}", text)?;
1108         }
1109
1110         Ok(printer)
1111     }
1112     fn path_generic_args<'gcx, 'tcx>(
1113         self: PrintCx<'_, 'gcx, 'tcx, Self>,
1114         print_prefix: impl FnOnce(
1115             PrintCx<'_, 'gcx, 'tcx, Self>,
1116         ) -> Result<Self::Path, Self::Error>,
1117         params: &[ty::GenericParamDef],
1118         substs: SubstsRef<'tcx>,
1119         ns: Namespace,
1120         projections: impl Iterator<Item = ty::ExistentialProjection<'tcx>>,
1121     ) -> Result<Self::Path, Self::Error> {
1122         self.pretty_path_generic_args(print_prefix, params, substs, ns, projections)
1123     }
1124 }
1125
1126 impl<F: fmt::Write> PrettyPrinter for FmtPrinter<F> {
1127     fn nest<'a, 'gcx, 'tcx, E>(
1128         mut self: PrintCx<'a, 'gcx, 'tcx, Self>,
1129         f: impl for<'b> FnOnce(PrintCx<'b, 'gcx, 'tcx, Self>) -> Result<Self, E>,
1130     ) -> Result<PrintCx<'a, 'gcx, 'tcx, Self>, E> {
1131         let was_empty = std::mem::replace(&mut self.printer.empty, true);
1132         let mut printer = f(PrintCx {
1133             tcx: self.tcx,
1134             printer: self.printer,
1135             config: self.config,
1136         })?;
1137         printer.empty &= was_empty;
1138         Ok(PrintCx {
1139             tcx: self.tcx,
1140             printer,
1141             config: self.config,
1142         })
1143     }
1144
1145     fn always_print_region_in_paths(
1146         self: &PrintCx<'_, '_, '_, Self>,
1147         region: ty::Region<'_>,
1148     ) -> bool {
1149         *region != ty::ReErased
1150     }
1151
1152     fn print_region_outputs_anything(
1153         self: &PrintCx<'_, '_, '_, Self>,
1154         region: ty::Region<'_>,
1155     ) -> bool {
1156         let highlight = self.printer.region_highlight_mode;
1157         if highlight.region_highlighted(region).is_some() {
1158             return true;
1159         }
1160
1161         if self.config.is_verbose {
1162             return true;
1163         }
1164
1165         match *region {
1166             ty::ReEarlyBound(ref data) => {
1167                 data.name != "" && data.name != "'_"
1168             }
1169
1170             ty::ReLateBound(_, br) |
1171             ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
1172             ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
1173                 if let ty::BrNamed(_, name) = br {
1174                     if name != "" && name != "'_" {
1175                         return true;
1176                     }
1177                 }
1178
1179                 if let Some((region, _)) = highlight.highlight_bound_region {
1180                     if br == region {
1181                         return true;
1182                     }
1183                 }
1184
1185                 false
1186             }
1187
1188             ty::ReScope(_) |
1189             ty::ReVar(_) if self.config.identify_regions => true,
1190
1191             ty::ReVar(_) |
1192             ty::ReScope(_) |
1193             ty::ReErased => false,
1194
1195             ty::ReStatic |
1196             ty::ReEmpty |
1197             ty::ReClosureBound(_) => true,
1198         }
1199     }
1200 }