rustc_middle/ty/print/
mod.rs

1use hir::def::Namespace;
2use rustc_data_structures::fx::FxHashSet;
3use rustc_data_structures::sso::SsoHashSet;
4use rustc_hir as hir;
5use rustc_hir::def_id::{CrateNum, DefId};
6use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
7use tracing::{debug, instrument, trace};
8
9use crate::ty::{self, GenericArg, Ty, TyCtxt};
10
11// `pretty` is a separate module only for organization.
12mod pretty;
13pub use self::pretty::*;
14use super::Lift;
15
16pub type PrintError = std::fmt::Error;
17
18pub trait Print<'tcx, P> {
19    fn print(&self, p: &mut P) -> Result<(), PrintError>;
20}
21
22/// A trait that "prints" user-facing type system entities: paths, types, lifetimes, constants,
23/// etc. "Printing" here means building up a representation of the entity's path, usually as a
24/// `String` (e.g. "std::io::Read") or a `Vec<Symbol>` (e.g. `[sym::std, sym::io, sym::Read]`). The
25/// representation is built up by appending one or more pieces. The specific details included in
26/// the built-up representation depend on the purpose of the printer. The more advanced printers
27/// also rely on the `PrettyPrinter` sub-trait.
28pub trait Printer<'tcx>: Sized {
29    fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
30
31    /// Appends a representation of an entity with a normal path, e.g. "std::io::Read".
32    fn print_def_path(
33        &mut self,
34        def_id: DefId,
35        args: &'tcx [GenericArg<'tcx>],
36    ) -> Result<(), PrintError> {
37        self.default_print_def_path(def_id, args)
38    }
39
40    /// Like `print_def_path`, but for `DefPathData::Impl`.
41    fn print_impl_path(
42        &mut self,
43        impl_def_id: DefId,
44        args: &'tcx [GenericArg<'tcx>],
45    ) -> Result<(), PrintError> {
46        let tcx = self.tcx();
47        let self_ty = tcx.type_of(impl_def_id);
48        let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
49        let (self_ty, impl_trait_ref) = if tcx.generics_of(impl_def_id).count() <= args.len() {
50            (
51                self_ty.instantiate(tcx, args),
52                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate(tcx, args)),
53            )
54        } else {
55            // We are probably printing a nested item inside of an impl.
56            // Use the identity substitutions for the impl.
57            (
58                self_ty.instantiate_identity(),
59                impl_trait_ref.map(|impl_trait_ref| impl_trait_ref.instantiate_identity()),
60            )
61        };
62
63        self.default_print_impl_path(impl_def_id, self_ty, impl_trait_ref)
64    }
65
66    /// Appends a representation of a region.
67    fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError>;
68
69    /// Appends a representation of a type.
70    fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError>;
71
72    /// Appends a representation of a list of `PolyExistentialPredicate`s.
73    fn print_dyn_existential(
74        &mut self,
75        predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
76    ) -> Result<(), PrintError>;
77
78    /// Appends a representation of a const.
79    fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError>;
80
81    /// Appends a representation of a crate name, e.g. `std`, or even ``.
82    fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError>;
83
84    /// Appends a representation of a (full or partial) simple path, in two parts. `print_prefix`,
85    /// when called, appends the representation of the leading segments. The rest of the method
86    /// appends the representation of the final segment, the details of which are in
87    /// `disambiguated_data`.
88    ///
89    /// E.g. `std::io` + `Read` -> `std::io::Read`.
90    fn print_path_with_simple(
91        &mut self,
92        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
93        disambiguated_data: &DisambiguatedDefPathData,
94    ) -> Result<(), PrintError>;
95
96    /// Similar to `print_path_with_simple`, but the final segment is an `impl` segment.
97    ///
98    /// E.g. `slice` + `<impl [T]>` -> `slice::<impl [T]>`, which may then be further appended to,
99    /// giving a longer path representation such as `slice::<impl [T]>::to_vec_in::ConvertVec`.
100    fn print_path_with_impl(
101        &mut self,
102        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
103        self_ty: Ty<'tcx>,
104        trait_ref: Option<ty::TraitRef<'tcx>>,
105    ) -> Result<(), PrintError>;
106
107    /// Appends a representation of a path ending in generic args, in two parts. `print_prefix`,
108    /// when called, appends the leading segments. The rest of the method appends the
109    /// representation of the generic args. (Some printers choose to skip appending the generic
110    /// args.)
111    ///
112    /// E.g. `ImplementsTraitForUsize` + `<usize>` -> `ImplementsTraitForUsize<usize>`.
113    fn print_path_with_generic_args(
114        &mut self,
115        print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>,
116        args: &[GenericArg<'tcx>],
117    ) -> Result<(), PrintError>;
118
119    /// Appends a representation of a qualified path segment, e.g. `<OsString as From<&T>>`.
120    /// If `trait_ref` is `None`, it may fall back to simpler forms, e.g. `<Vec<T>>` or just `Foo`.
121    fn print_path_with_qualified(
122        &mut self,
123        self_ty: Ty<'tcx>,
124        trait_ref: Option<ty::TraitRef<'tcx>>,
125    ) -> Result<(), PrintError>;
126
127    fn print_coroutine_with_kind(
128        &mut self,
129        def_id: DefId,
130        parent_args: &'tcx [GenericArg<'tcx>],
131        kind: Ty<'tcx>,
132    ) -> Result<(), PrintError> {
133        self.print_path_with_generic_args(|p| p.print_def_path(def_id, parent_args), &[kind.into()])
134    }
135
136    // Defaults (should not be overridden):
137
138    #[instrument(skip(self), level = "debug")]
139    fn default_print_def_path(
140        &mut self,
141        def_id: DefId,
142        args: &'tcx [GenericArg<'tcx>],
143    ) -> Result<(), PrintError> {
144        let key = self.tcx().def_key(def_id);
145        debug!(?key);
146
147        match key.disambiguated_data.data {
148            DefPathData::CrateRoot => {
149                assert!(key.parent.is_none());
150                self.print_crate_name(def_id.krate)
151            }
152
153            DefPathData::Impl => self.print_impl_path(def_id, args),
154
155            _ => {
156                let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
157
158                let mut parent_args = args;
159                let mut trait_qualify_parent = false;
160                if !args.is_empty() {
161                    let generics = self.tcx().generics_of(def_id);
162                    parent_args = &args[..generics.parent_count.min(args.len())];
163
164                    match key.disambiguated_data.data {
165                        DefPathData::Closure => {
166                            // We need to additionally print the `kind` field of a coroutine if
167                            // it is desugared from a coroutine-closure.
168                            if let Some(hir::CoroutineKind::Desugared(
169                                _,
170                                hir::CoroutineSource::Closure,
171                            )) = self.tcx().coroutine_kind(def_id)
172                                && args.len() > parent_args.len()
173                            {
174                                return self.print_coroutine_with_kind(
175                                    def_id,
176                                    parent_args,
177                                    args[parent_args.len()].expect_ty(),
178                                );
179                            } else {
180                                // Closures' own generics are only captures, don't print them.
181                            }
182                        }
183                        DefPathData::SyntheticCoroutineBody => {
184                            // Synthetic coroutine bodies have no distinct generics, since like
185                            // closures they're all just internal state of the coroutine.
186                        }
187                        // This covers both `DefKind::AnonConst` and `DefKind::InlineConst`.
188                        // Anon consts doesn't have their own generics, and inline consts' own
189                        // generics are their inferred types, so don't print them.
190                        DefPathData::AnonConst => {}
191
192                        // If we have any generic arguments to print, we do that
193                        // on top of the same path, but without its own generics.
194                        _ => {
195                            if !generics.is_own_empty() && args.len() >= generics.count() {
196                                let args = generics.own_args_no_defaults(self.tcx(), args);
197                                return self.print_path_with_generic_args(
198                                    |p| p.print_def_path(def_id, parent_args),
199                                    args,
200                                );
201                            }
202                        }
203                    }
204
205                    // FIXME(eddyb) try to move this into the parent's printing
206                    // logic, instead of doing it when printing the child.
207                    trait_qualify_parent = generics.has_self
208                        && generics.parent == Some(parent_def_id)
209                        && parent_args.len() == generics.parent_count
210                        && self.tcx().generics_of(parent_def_id).parent_count == 0;
211                }
212
213                self.print_path_with_simple(
214                    |p: &mut Self| {
215                        if trait_qualify_parent {
216                            let trait_ref = ty::TraitRef::new(
217                                p.tcx(),
218                                parent_def_id,
219                                parent_args.iter().copied(),
220                            );
221                            p.print_path_with_qualified(trait_ref.self_ty(), Some(trait_ref))
222                        } else {
223                            p.print_def_path(parent_def_id, parent_args)
224                        }
225                    },
226                    &key.disambiguated_data,
227                )
228            }
229        }
230    }
231
232    fn default_print_impl_path(
233        &mut self,
234        impl_def_id: DefId,
235        self_ty: Ty<'tcx>,
236        impl_trait_ref: Option<ty::TraitRef<'tcx>>,
237    ) -> Result<(), PrintError> {
238        debug!(
239            "default_print_impl_path: impl_def_id={:?}, self_ty={}, impl_trait_ref={:?}",
240            impl_def_id, self_ty, impl_trait_ref
241        );
242
243        let key = self.tcx().def_key(impl_def_id);
244        let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
245
246        // Decide whether to print the parent path for the impl.
247        // Logically, since impls are global, it's never needed, but
248        // users may find it useful. Currently, we omit the parent if
249        // the impl is either in the same module as the self-type or
250        // as the trait.
251        let in_self_mod = match characteristic_def_id_of_type(self_ty) {
252            None => false,
253            Some(ty_def_id) => self.tcx().parent(ty_def_id) == parent_def_id,
254        };
255        let in_trait_mod = match impl_trait_ref {
256            None => false,
257            Some(trait_ref) => self.tcx().parent(trait_ref.def_id) == parent_def_id,
258        };
259
260        if !in_self_mod && !in_trait_mod {
261            // If the impl is not co-located with either self-type or
262            // trait-type, then fallback to a format that identifies
263            // the module more clearly.
264            self.print_path_with_impl(
265                |p| p.print_def_path(parent_def_id, &[]),
266                self_ty,
267                impl_trait_ref,
268            )
269        } else {
270            // Otherwise, try to give a good form that would be valid language
271            // syntax. Preferably using associated item notation.
272            self.print_path_with_qualified(self_ty, impl_trait_ref)
273        }
274    }
275}
276
277/// As a heuristic, when we see an impl, if we see that the
278/// 'self type' is a type defined in the same module as the impl,
279/// we can omit including the path to the impl itself. This
280/// function tries to find a "characteristic `DefId`" for a
281/// type. It's just a heuristic so it makes some questionable
282/// decisions and we may want to adjust it later.
283///
284/// Visited set is needed to avoid full iteration over
285/// deeply nested tuples that have no DefId.
286fn characteristic_def_id_of_type_cached<'a>(
287    ty: Ty<'a>,
288    visited: &mut SsoHashSet<Ty<'a>>,
289) -> Option<DefId> {
290    match *ty.kind() {
291        ty::Adt(adt_def, _) => Some(adt_def.did()),
292
293        ty::Dynamic(data, ..) => data.principal_def_id(),
294
295        ty::Pat(subty, _) | ty::Array(subty, _) | ty::Slice(subty) => {
296            characteristic_def_id_of_type_cached(subty, visited)
297        }
298
299        ty::RawPtr(ty, _) => characteristic_def_id_of_type_cached(ty, visited),
300
301        ty::Ref(_, ty, _) => characteristic_def_id_of_type_cached(ty, visited),
302
303        ty::Tuple(tys) => tys.iter().find_map(|ty| {
304            if visited.insert(ty) {
305                return characteristic_def_id_of_type_cached(ty, visited);
306            }
307            return None;
308        }),
309
310        ty::FnDef(def_id, _)
311        | ty::Closure(def_id, _)
312        | ty::CoroutineClosure(def_id, _)
313        | ty::Coroutine(def_id, _)
314        | ty::CoroutineWitness(def_id, _)
315        | ty::Foreign(def_id) => Some(def_id),
316
317        ty::Bool
318        | ty::Char
319        | ty::Int(_)
320        | ty::Uint(_)
321        | ty::Str
322        | ty::FnPtr(..)
323        | ty::UnsafeBinder(_)
324        | ty::Alias(..)
325        | ty::Placeholder(..)
326        | ty::Param(_)
327        | ty::Infer(_)
328        | ty::Bound(..)
329        | ty::Error(_)
330        | ty::Never
331        | ty::Float(_) => None,
332    }
333}
334pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
335    characteristic_def_id_of_type_cached(ty, &mut SsoHashSet::new())
336}
337
338impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Region<'tcx> {
339    fn print(&self, p: &mut P) -> Result<(), PrintError> {
340        p.print_region(*self)
341    }
342}
343
344impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> {
345    fn print(&self, p: &mut P) -> Result<(), PrintError> {
346        p.print_type(*self)
347    }
348}
349
350impl<'tcx, P: Printer<'tcx> + std::fmt::Write> Print<'tcx, P> for ty::Instance<'tcx> {
351    fn print(&self, cx: &mut P) -> Result<(), PrintError> {
352        cx.print_def_path(self.def_id(), self.args)?;
353        match self.def {
354            ty::InstanceKind::Item(_) => {}
355            ty::InstanceKind::VTableShim(_) => cx.write_str(" - shim(vtable)")?,
356            ty::InstanceKind::ReifyShim(_, None) => cx.write_str(" - shim(reify)")?,
357            ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::FnPtr)) => {
358                cx.write_str(" - shim(reify-fnptr)")?
359            }
360            ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::Vtable)) => {
361                cx.write_str(" - shim(reify-vtable)")?
362            }
363            ty::InstanceKind::ThreadLocalShim(_) => cx.write_str(" - shim(tls)")?,
364            ty::InstanceKind::Intrinsic(_) => cx.write_str(" - intrinsic")?,
365            ty::InstanceKind::Virtual(_, num) => cx.write_str(&format!(" - virtual#{num}"))?,
366            ty::InstanceKind::FnPtrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
367            ty::InstanceKind::ClosureOnceShim { .. } => cx.write_str(" - shim")?,
368            ty::InstanceKind::ConstructCoroutineInClosureShim { .. } => cx.write_str(" - shim")?,
369            ty::InstanceKind::DropGlue(_, None) => cx.write_str(" - shim(None)")?,
370            ty::InstanceKind::DropGlue(_, Some(ty)) => {
371                cx.write_str(&format!(" - shim(Some({ty}))"))?
372            }
373            ty::InstanceKind::CloneShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
374            ty::InstanceKind::FnPtrAddrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
375            ty::InstanceKind::FutureDropPollShim(_, proxy_ty, impl_ty) => {
376                cx.write_str(&format!(" - dropshim({proxy_ty}-{impl_ty})"))?
377            }
378            ty::InstanceKind::AsyncDropGlue(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
379            ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
380                cx.write_str(&format!(" - shim(Some({ty}))"))?
381            }
382        };
383        Ok(())
384    }
385}
386
387impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
388    fn print(&self, p: &mut P) -> Result<(), PrintError> {
389        p.print_dyn_existential(self)
390    }
391}
392
393impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> {
394    fn print(&self, p: &mut P) -> Result<(), PrintError> {
395        p.print_const(*self)
396    }
397}
398
399impl<T> rustc_type_ir::ir_print::IrPrint<T> for TyCtxt<'_>
400where
401    T: Copy + for<'a, 'tcx> Lift<TyCtxt<'tcx>, Lifted: Print<'tcx, FmtPrinter<'a, 'tcx>>>,
402{
403    fn print(t: &T, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        ty::tls::with(|tcx| {
405            let mut p = FmtPrinter::new(tcx, Namespace::TypeNS);
406            tcx.lift(*t).expect("could not lift for printing").print(&mut p)?;
407            fmt.write_str(&p.into_buffer())?;
408            Ok(())
409        })
410    }
411
412    fn print_debug(t: &T, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413        with_no_trimmed_paths!(Self::print(t, fmt))
414    }
415}