]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/print.rs
rustc: integrate LocalPathPrinter's behavior into FmtPrinter.
[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::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable};
5 use crate::ty::subst::{Subst, SubstsRef};
6 use crate::middle::cstore::{ExternCrate, ExternCrateSource};
7 use syntax::ast;
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::ops::Deref;
16
17 thread_local! {
18     static FORCE_ABSOLUTE: Cell<bool> = Cell::new(false);
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 /// Enforces that def_path_str always returns an absolute path and
24 /// also enables "type-based" impl paths. This is used when building
25 /// symbols that contain types, where we want the crate name to be
26 /// part of the symbol.
27 pub fn with_forced_absolute_paths<F: FnOnce() -> R, R>(f: F) -> R {
28     FORCE_ABSOLUTE.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 /// Force us to name impls with just the filename/line number. We
38 /// normally try to use types. But at some points, notably while printing
39 /// cycle errors, this can result in extra or suboptimal error output,
40 /// so this variable disables that check.
41 pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R {
42     FORCE_IMPL_FILENAME_LINE.with(|force| {
43         let old = force.get();
44         force.set(true);
45         let result = f();
46         force.set(old);
47         result
48     })
49 }
50
51 /// Adds the `crate::` prefix to paths where appropriate.
52 pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R {
53     SHOULD_PREFIX_WITH_CRATE.with(|flag| {
54         let old = flag.get();
55         flag.set(true);
56         let result = f();
57         flag.set(old);
58         result
59     })
60 }
61
62 // FIXME(eddyb) this module uses `pub(crate)` for things used only
63 // from `ppaux` - when that is removed, they can be re-privatized.
64
65 struct LateBoundRegionNameCollector(FxHashSet<InternedString>);
66 impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector {
67     fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
68         match *r {
69             ty::ReLateBound(_, ty::BrNamed(_, name)) => {
70                 self.0.insert(name);
71             },
72             _ => {},
73         }
74         r.super_visit_with(self)
75     }
76 }
77
78 pub struct PrintCx<'a, 'gcx, 'tcx, P> {
79     pub tcx: TyCtxt<'a, 'gcx, 'tcx>,
80     pub printer: P,
81     pub(crate) is_debug: bool,
82     pub(crate) is_verbose: bool,
83     pub(crate) identify_regions: bool,
84     pub(crate) used_region_names: Option<FxHashSet<InternedString>>,
85     pub(crate) region_index: usize,
86     pub(crate) binder_depth: usize,
87 }
88
89 // HACK(eddyb) this is solely for `self: &mut PrintCx<Self>`, e.g. to
90 // implement traits on the printer and call the methods on the context.
91 impl<P> Deref for PrintCx<'_, '_, '_, P> {
92     type Target = P;
93     fn deref(&self) -> &P {
94         &self.printer
95     }
96 }
97
98 impl<P> PrintCx<'a, 'gcx, 'tcx, P> {
99     pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>, printer: P) -> Self {
100         PrintCx {
101             tcx,
102             printer,
103             is_debug: false,
104             is_verbose: tcx.sess.verbose(),
105             identify_regions: tcx.sess.opts.debugging_opts.identify_regions,
106             used_region_names: None,
107             region_index: 0,
108             binder_depth: 0,
109         }
110     }
111
112     pub(crate) fn with<R>(printer: P, f: impl FnOnce(PrintCx<'_, '_, '_, P>) -> R) -> R {
113         ty::tls::with(|tcx| f(PrintCx::new(tcx, printer)))
114     }
115     pub(crate) fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>)
116     where T: TypeFoldable<'tcx>
117     {
118         let mut collector = LateBoundRegionNameCollector(Default::default());
119         value.visit_with(&mut collector);
120         self.used_region_names = Some(collector.0);
121         self.region_index = 0;
122     }
123 }
124
125 pub trait Print<'tcx, P> {
126     type Output;
127
128     fn print(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output;
129     fn print_display(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output {
130         let old_debug = cx.is_debug;
131         cx.is_debug = false;
132         let result = self.print(cx);
133         cx.is_debug = old_debug;
134         result
135     }
136     fn print_debug(&self, cx: &mut PrintCx<'_, '_, 'tcx, P>) -> Self::Output {
137         let old_debug = cx.is_debug;
138         cx.is_debug = true;
139         let result = self.print(cx);
140         cx.is_debug = old_debug;
141         result
142     }
143 }
144
145 pub trait Printer: Sized {
146     type Path;
147
148     #[must_use]
149     fn print_def_path(
150         self: &mut PrintCx<'_, '_, 'tcx, Self>,
151         def_id: DefId,
152         substs: Option<SubstsRef<'tcx>>,
153         ns: Namespace,
154     ) -> Self::Path {
155         self.default_print_def_path(def_id, substs, ns)
156     }
157     #[must_use]
158     fn print_impl_path(
159         self: &mut PrintCx<'_, '_, 'tcx, Self>,
160         impl_def_id: DefId,
161         substs: Option<SubstsRef<'tcx>>,
162         ns: Namespace,
163     ) -> Self::Path {
164         self.default_print_impl_path(impl_def_id, substs, ns)
165     }
166
167     #[must_use]
168     fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path;
169     #[must_use]
170     fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path;
171     #[must_use]
172     fn path_append(
173         self: &mut PrintCx<'_, '_, '_, Self>,
174         path: Self::Path,
175         text: &str,
176     ) -> Self::Path;
177 }
178
179 #[must_use]
180 pub struct PrettyPath {
181     pub empty: bool,
182 }
183
184 /// Trait for printers that pretty-print using `fmt::Write` to the printer.
185 pub trait PrettyPrinter: Printer<Path = Result<PrettyPath, fmt::Error>> + fmt::Write {}
186
187 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
188     // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always
189     // (but also some things just print a `DefId` generally so maybe we need this?)
190     fn guess_def_namespace(self, def_id: DefId) -> Namespace {
191         match self.def_key(def_id).disambiguated_data.data {
192             DefPathData::ValueNs(..) |
193             DefPathData::EnumVariant(..) |
194             DefPathData::Field(..) |
195             DefPathData::AnonConst |
196             DefPathData::ClosureExpr |
197             DefPathData::StructCtor => Namespace::ValueNS,
198
199             DefPathData::MacroDef(..) => Namespace::MacroNS,
200
201             _ => Namespace::TypeNS,
202         }
203     }
204
205     /// Returns a string identifying this `DefId`. This string is
206     /// suitable for user output. It is relative to the current crate
207     /// root, unless with_forced_absolute_paths was used.
208     pub fn def_path_str_with_substs_and_ns(
209         self,
210         def_id: DefId,
211         substs: Option<SubstsRef<'tcx>>,
212         ns: Namespace,
213     ) -> String {
214         debug!("def_path_str: def_id={:?}, substs={:?}, ns={:?}", def_id, substs, ns);
215         if FORCE_ABSOLUTE.with(|force| force.get()) {
216             PrintCx::new(self, AbsolutePathPrinter).print_def_path(def_id, substs, ns)
217         } else {
218             let mut s = String::new();
219             let _ = PrintCx::new(self, FmtPrinter { fmt: &mut s })
220                 .print_def_path(def_id, substs, ns);
221             s
222         }
223     }
224
225     /// Returns a string identifying this `DefId`. This string is
226     /// suitable for user output. It is relative to the current crate
227     /// root, unless with_forced_absolute_paths was used.
228     pub fn def_path_str(self, def_id: DefId) -> String {
229         let ns = self.guess_def_namespace(def_id);
230         self.def_path_str_with_substs_and_ns(def_id, None, ns)
231     }
232
233     /// Returns a string identifying this local node-id.
234     // FIXME(eddyb) remove in favor of calling `def_path_str` directly.
235     pub fn node_path_str(self, id: ast::NodeId) -> String {
236         self.def_path_str(self.hir().local_def_id(id))
237     }
238
239     /// Returns a string identifying this `DefId`. This string is
240     /// suitable for user output. It always begins with a crate identifier.
241     pub fn absolute_def_path_str(self, def_id: DefId) -> String {
242         debug!("absolute_def_path_str: def_id={:?}", def_id);
243         let ns = self.guess_def_namespace(def_id);
244         PrintCx::new(self, AbsolutePathPrinter).print_def_path(def_id, None, ns)
245     }
246 }
247
248 impl<P: Printer> PrintCx<'a, 'gcx, 'tcx, P> {
249     pub fn default_print_def_path(
250         &mut self,
251         def_id: DefId,
252         substs: Option<SubstsRef<'tcx>>,
253         ns: Namespace,
254     ) -> P::Path {
255         debug!("default_print_def_path: def_id={:?}, substs={:?}, ns={:?}", def_id, substs, ns);
256         let key = self.tcx.def_key(def_id);
257         debug!("default_print_def_path: key={:?}", key);
258         match key.disambiguated_data.data {
259             DefPathData::CrateRoot => {
260                 assert!(key.parent.is_none());
261                 self.path_crate(def_id.krate)
262             }
263
264             DefPathData::Impl => {
265                 self.print_impl_path(def_id, substs, ns)
266             }
267
268             // Unclear if there is any value in distinguishing these.
269             // Probably eventually (and maybe we would even want
270             // finer-grained distinctions, e.g., between enum/struct).
271             data @ DefPathData::Misc |
272             data @ DefPathData::TypeNs(..) |
273             data @ DefPathData::Trait(..) |
274             data @ DefPathData::TraitAlias(..) |
275             data @ DefPathData::AssocTypeInTrait(..) |
276             data @ DefPathData::AssocTypeInImpl(..) |
277             data @ DefPathData::AssocExistentialInImpl(..) |
278             data @ DefPathData::ValueNs(..) |
279             data @ DefPathData::Module(..) |
280             data @ DefPathData::TypeParam(..) |
281             data @ DefPathData::LifetimeParam(..) |
282             data @ DefPathData::ConstParam(..) |
283             data @ DefPathData::EnumVariant(..) |
284             data @ DefPathData::Field(..) |
285             data @ DefPathData::AnonConst |
286             data @ DefPathData::MacroDef(..) |
287             data @ DefPathData::ClosureExpr |
288             data @ DefPathData::ImplTrait |
289             data @ DefPathData::GlobalMetaData(..) => {
290                 let parent_did = self.tcx.parent(def_id).unwrap();
291                 let path = self.print_def_path(parent_did, None, ns);
292                 self.path_append(path, &data.as_interned_str().as_symbol().as_str())
293             },
294
295             DefPathData::StructCtor => { // present `X` instead of `X::{{constructor}}`
296                 let parent_def_id = self.tcx.parent(def_id).unwrap();
297                 self.print_def_path(parent_def_id, substs, ns)
298             }
299         }
300     }
301
302     fn default_print_impl_path(
303         &mut self,
304         impl_def_id: DefId,
305         substs: Option<SubstsRef<'tcx>>,
306         ns: Namespace,
307     ) -> P::Path {
308         debug!("default_print_impl_path: impl_def_id={:?}", impl_def_id);
309         let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
310
311         // Decide whether to print the parent path for the impl.
312         // Logically, since impls are global, it's never needed, but
313         // users may find it useful. Currently, we omit the parent if
314         // the impl is either in the same module as the self-type or
315         // as the trait.
316         let mut self_ty = self.tcx.type_of(impl_def_id);
317         if let Some(substs) = substs {
318             self_ty = self_ty.subst(self.tcx, substs);
319         }
320         let in_self_mod = match characteristic_def_id_of_type(self_ty) {
321             None => false,
322             Some(ty_def_id) => self.tcx.parent(ty_def_id) == Some(parent_def_id),
323         };
324
325         let mut impl_trait_ref = self.tcx.impl_trait_ref(impl_def_id);
326         if let Some(substs) = substs {
327             impl_trait_ref = impl_trait_ref.subst(self.tcx, substs);
328         }
329         let in_trait_mod = match impl_trait_ref {
330             None => false,
331             Some(trait_ref) => self.tcx.parent(trait_ref.def_id) == Some(parent_def_id),
332         };
333
334         if !in_self_mod && !in_trait_mod {
335             // If the impl is not co-located with either self-type or
336             // trait-type, then fallback to a format that identifies
337             // the module more clearly.
338             let path = self.print_def_path(parent_def_id, None, ns);
339             if let Some(trait_ref) = impl_trait_ref {
340                 return self.path_append(path, &format!("<impl {} for {}>", trait_ref, self_ty));
341             } else {
342                 return self.path_append(path, &format!("<impl {}>", self_ty));
343             }
344         }
345
346         // Otherwise, try to give a good form that would be valid language
347         // syntax. Preferably using associated item notation.
348
349         if let Some(trait_ref) = impl_trait_ref {
350             // Trait impls.
351             return self.path_impl(&format!("<{} as {}>", self_ty, trait_ref));
352         }
353
354         // Inherent impls. Try to print `Foo::bar` for an inherent
355         // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is
356         // anything other than a simple path.
357         match self_ty.sty {
358             ty::Adt(adt_def, substs) => {
359                 // FIXME(eddyb) this should recurse to build the path piecewise.
360                 // self.print_def_path(adt_def.did, Some(substs), ns)
361                 let mut s = String::new();
362                 crate::util::ppaux::parameterized(&mut s, adt_def.did, substs, ns).unwrap();
363                 self.path_impl(&s)
364             }
365
366             ty::Foreign(did) => self.print_def_path(did, None, ns),
367
368             ty::Bool |
369             ty::Char |
370             ty::Int(_) |
371             ty::Uint(_) |
372             ty::Float(_) |
373             ty::Str => {
374                 self.path_impl(&self_ty.to_string())
375             }
376
377             _ => {
378                 self.path_impl(&format!("<{}>", self_ty))
379             }
380         }
381     }
382 }
383
384 /// As a heuristic, when we see an impl, if we see that the
385 /// 'self type' is a type defined in the same module as the impl,
386 /// we can omit including the path to the impl itself. This
387 /// function tries to find a "characteristic `DefId`" for a
388 /// type. It's just a heuristic so it makes some questionable
389 /// decisions and we may want to adjust it later.
390 pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
391     match ty.sty {
392         ty::Adt(adt_def, _) => Some(adt_def.did),
393
394         ty::Dynamic(data, ..) => data.principal_def_id(),
395
396         ty::Array(subty, _) |
397         ty::Slice(subty) => characteristic_def_id_of_type(subty),
398
399         ty::RawPtr(mt) => characteristic_def_id_of_type(mt.ty),
400
401         ty::Ref(_, ty, _) => characteristic_def_id_of_type(ty),
402
403         ty::Tuple(ref tys) => tys.iter()
404                                    .filter_map(|ty| characteristic_def_id_of_type(ty))
405                                    .next(),
406
407         ty::FnDef(def_id, _) |
408         ty::Closure(def_id, _) |
409         ty::Generator(def_id, _, _) |
410         ty::Foreign(def_id) => Some(def_id),
411
412         ty::Bool |
413         ty::Char |
414         ty::Int(_) |
415         ty::Uint(_) |
416         ty::Str |
417         ty::FnPtr(_) |
418         ty::Projection(_) |
419         ty::Placeholder(..) |
420         ty::UnnormalizedProjection(..) |
421         ty::Param(_) |
422         ty::Opaque(..) |
423         ty::Infer(_) |
424         ty::Bound(..) |
425         ty::Error |
426         ty::GeneratorWitness(..) |
427         ty::Never |
428         ty::Float(_) => None,
429     }
430 }
431
432 // FIXME(eddyb) remove, alongside `FORCE_ABSOLUTE` and `absolute_def_path_str`.
433 struct AbsolutePathPrinter;
434
435 impl Printer for AbsolutePathPrinter {
436     type Path = String;
437
438     fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path {
439         self.tcx.original_crate_name(cnum).to_string()
440     }
441     fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path {
442         text.to_string()
443     }
444     fn path_append(
445         self: &mut PrintCx<'_, '_, '_, Self>,
446         mut path: Self::Path,
447         text: &str,
448     ) -> Self::Path {
449         if !path.is_empty() {
450             path.push_str("::");
451         }
452         path.push_str(text);
453         path
454     }
455 }
456
457 pub struct FmtPrinter<F: fmt::Write> {
458     pub fmt: F,
459 }
460
461 impl<F: fmt::Write> FmtPrinter<F> {
462     /// If possible, this returns a global path resolving to `def_id` that is visible
463     /// from at least one local module and returns true. If the crate defining `def_id` is
464     /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`.
465     fn try_print_visible_def_path(
466         self: &mut PrintCx<'_, '_, '_, Self>,
467         def_id: DefId,
468         ns: Namespace,
469     ) -> Option<<Self as Printer>::Path> {
470         debug!("try_print_visible_def_path: def_id={:?}", def_id);
471
472         // If `def_id` is a direct or injected extern crate, return the
473         // path to the crate followed by the path to the item within the crate.
474         if def_id.index == CRATE_DEF_INDEX {
475             let cnum = def_id.krate;
476
477             if cnum == LOCAL_CRATE {
478                 return Some(self.path_crate(cnum));
479             }
480
481             // In local mode, when we encounter a crate other than
482             // LOCAL_CRATE, execution proceeds in one of two ways:
483             //
484             // 1. for a direct dependency, where user added an
485             //    `extern crate` manually, we put the `extern
486             //    crate` as the parent. So you wind up with
487             //    something relative to the current crate.
488             // 2. for an extern inferred from a path or an indirect crate,
489             //    where there is no explicit `extern crate`, we just prepend
490             //    the crate name.
491             match *self.tcx.extern_crate(def_id) {
492                 Some(ExternCrate {
493                     src: ExternCrateSource::Extern(def_id),
494                     direct: true,
495                     span,
496                     ..
497                 }) => {
498                     debug!("try_print_visible_def_path: def_id={:?}", def_id);
499                     let path = if !span.is_dummy() {
500                         self.print_def_path(def_id, None, ns)
501                     } else {
502                         self.path_crate(cnum)
503                     };
504                     return Some(path);
505                 }
506                 None => {
507                     return Some(self.path_crate(cnum));
508                 }
509                 _ => {},
510             }
511         }
512
513         if def_id.is_local() {
514             return None;
515         }
516
517         let visible_parent_map = self.tcx.visible_parent_map(LOCAL_CRATE);
518
519         let mut cur_def_key = self.tcx.def_key(def_id);
520         debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key);
521
522         // For a UnitStruct or TupleStruct we want the name of its parent rather than <unnamed>.
523         if let DefPathData::StructCtor = cur_def_key.disambiguated_data.data {
524             let parent = DefId {
525                 krate: def_id.krate,
526                 index: cur_def_key.parent.expect("DefPathData::StructCtor missing a parent"),
527             };
528
529             cur_def_key = self.tcx.def_key(parent);
530         }
531
532         let visible_parent = visible_parent_map.get(&def_id).cloned()?;
533         let path = self.try_print_visible_def_path(visible_parent, ns)?;
534         let actual_parent = self.tcx.parent(def_id);
535
536         let data = cur_def_key.disambiguated_data.data;
537         debug!(
538             "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}",
539             data, visible_parent, actual_parent,
540         );
541
542         let symbol = match data {
543             // In order to output a path that could actually be imported (valid and visible),
544             // we need to handle re-exports correctly.
545             //
546             // For example, take `std::os::unix::process::CommandExt`, this trait is actually
547             // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing).
548             //
549             // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is
550             // private so the "true" path to `CommandExt` isn't accessible.
551             //
552             // In this case, the `visible_parent_map` will look something like this:
553             //
554             // (child) -> (parent)
555             // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process`
556             // `std::sys::unix::ext::process` -> `std::sys::unix::ext`
557             // `std::sys::unix::ext` -> `std::os`
558             //
559             // This is correct, as the visible parent of `std::sys::unix::ext` is in fact
560             // `std::os`.
561             //
562             // When printing the path to `CommandExt` and looking at the `cur_def_key` that
563             // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go
564             // to the parent - resulting in a mangled path like
565             // `std::os::ext::process::CommandExt`.
566             //
567             // Instead, we must detect that there was a re-export and instead print `unix`
568             // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To
569             // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with
570             // the visible parent (`std::os`). If these do not match, then we iterate over
571             // the children of the visible parent (as was done when computing
572             // `visible_parent_map`), looking for the specific child we currently have and then
573             // have access to the re-exported name.
574             DefPathData::Module(actual_name) |
575             DefPathData::TypeNs(actual_name) if Some(visible_parent) != actual_parent => {
576                 self.tcx.item_children(visible_parent)
577                     .iter()
578                     .find(|child| child.def.def_id() == def_id)
579                     .map(|child| child.ident.as_str())
580                     .unwrap_or_else(|| actual_name.as_str())
581             }
582             _ => {
583                 data.get_opt_name().map(|n| n.as_str()).unwrap_or_else(|| {
584                     // Re-exported `extern crate` (#43189).
585                     if let DefPathData::CrateRoot = data {
586                         self.tcx.original_crate_name(def_id.krate).as_str()
587                     } else {
588                         Symbol::intern("<unnamed>").as_str()
589                     }
590                 })
591             },
592         };
593         debug!("try_print_visible_def_path: symbol={:?}", symbol);
594         Some(self.path_append(path, &symbol))
595     }
596 }
597
598 impl<F: fmt::Write> fmt::Write for FmtPrinter<F> {
599     fn write_str(&mut self, s: &str) -> fmt::Result {
600         self.fmt.write_str(s)
601     }
602 }
603
604 impl<F: fmt::Write> Printer for FmtPrinter<F> {
605     type Path = Result<PrettyPath, fmt::Error>;
606
607     fn print_def_path(
608         self: &mut PrintCx<'_, '_, 'tcx, Self>,
609         def_id: DefId,
610         substs: Option<SubstsRef<'tcx>>,
611         ns: Namespace,
612     ) -> Self::Path {
613         self.try_print_visible_def_path(def_id, ns)
614             .unwrap_or_else(|| self.default_print_def_path(def_id, substs, ns))
615     }
616     fn print_impl_path(
617         self: &mut PrintCx<'_, '_, 'tcx, Self>,
618         impl_def_id: DefId,
619         substs: Option<SubstsRef<'tcx>>,
620         ns: Namespace,
621     ) -> Self::Path {
622         // Always use types for non-local impls, where types are always
623         // available, and filename/line-number is mostly uninteresting.
624         let use_types = !impl_def_id.is_local() || {
625             // Otherwise, use filename/line-number if forced.
626             let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get());
627             !force_no_types
628         };
629
630         if !use_types {
631             // If no type info is available, fall back to
632             // pretty printing some span information. This should
633             // only occur very early in the compiler pipeline.
634             let parent_def_id = self.tcx.parent(impl_def_id).unwrap();
635             let path = self.print_def_path(parent_def_id, None, ns);
636             let span = self.tcx.def_span(impl_def_id);
637             return self.path_append(path, &format!("<impl at {:?}>", span));
638         }
639
640         self.default_print_impl_path(impl_def_id, substs, ns)
641     }
642
643     fn path_crate(self: &mut PrintCx<'_, '_, '_, Self>, cnum: CrateNum) -> Self::Path {
644         if cnum == LOCAL_CRATE {
645             if self.tcx.sess.rust_2018() {
646                 // We add the `crate::` keyword on Rust 2018, only when desired.
647                 if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) {
648                     write!(self.printer, "{}", keywords::Crate.name())?;
649                     return Ok(PrettyPath { empty: false });
650                 }
651             }
652             Ok(PrettyPath { empty: true })
653         } else {
654             write!(self.printer, "{}", self.tcx.crate_name(cnum))?;
655             Ok(PrettyPath { empty: false })
656         }
657     }
658     fn path_impl(self: &mut PrintCx<'_, '_, '_, Self>, text: &str) -> Self::Path {
659         write!(self.printer, "{}", text)?;
660         Ok(PrettyPath { empty: false })
661     }
662     fn path_append(
663         self: &mut PrintCx<'_, '_, '_, Self>,
664         path: Self::Path,
665         text: &str,
666     ) -> Self::Path {
667         let path = path?;
668
669         // FIXME(eddyb) this shouldn't happen, but is currently
670         // the case for `extern { ... }` "foreign modules".
671         if text.is_empty() {
672             return Ok(path);
673         }
674
675         if !path.empty {
676             write!(self.printer, "::")?;
677         }
678         write!(self.printer, "{}", text)?;
679         Ok(PrettyPath { empty: false })
680     }
681 }
682
683 impl<F: fmt::Write> PrettyPrinter for FmtPrinter<F> {}