]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/print/mod.rs
drive-by: Fix path spans
[rust.git] / compiler / rustc_middle / src / ty / print / mod.rs
1 use crate::ty::GenericArg;
2 use crate::ty::{self, DefIdTree, Ty, TyCtxt};
3
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_data_structures::sso::SsoHashSet;
6 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
7 use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
8
9 // `pretty` is a separate module only for organization.
10 mod pretty;
11 pub use self::pretty::*;
12
13 // FIXME(eddyb) false positive, the lifetime parameters are used with `P:  Printer<...>`.
14 #[allow(unused_lifetimes)]
15 pub trait Print<'tcx, P> {
16     type Output;
17     type Error;
18
19     fn print(&self, cx: P) -> Result<Self::Output, Self::Error>;
20 }
21
22 /// Interface for outputting user-facing "type-system entities"
23 /// (paths, types, lifetimes, constants, etc.) as a side-effect
24 /// (e.g. formatting, like `PrettyPrinter` implementors do) or by
25 /// constructing some alternative representation (e.g. an AST),
26 /// which the associated types allow passing through the methods.
27 ///
28 /// For pretty-printing/formatting in particular, see `PrettyPrinter`.
29 //
30 // FIXME(eddyb) find a better name; this is more general than "printing".
31 pub trait Printer<'tcx>: Sized {
32     type Error;
33
34     type Path;
35     type Region;
36     type Type;
37     type DynExistential;
38     type Const;
39
40     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
41
42     fn print_def_path(
43         self,
44         def_id: DefId,
45         substs: &'tcx [GenericArg<'tcx>],
46     ) -> Result<Self::Path, Self::Error> {
47         self.default_print_def_path(def_id, substs)
48     }
49
50     fn print_impl_path(
51         self,
52         impl_def_id: DefId,
53         substs: &'tcx [GenericArg<'tcx>],
54         self_ty: Ty<'tcx>,
55         trait_ref: Option<ty::TraitRef<'tcx>>,
56     ) -> Result<Self::Path, Self::Error> {
57         self.default_print_impl_path(impl_def_id, substs, self_ty, trait_ref)
58     }
59
60     fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error>;
61
62     fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error>;
63
64     fn print_dyn_existential(
65         self,
66         predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
67     ) -> Result<Self::DynExistential, Self::Error>;
68
69     fn print_const(self, ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error>;
70
71     fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error>;
72
73     fn path_qualified(
74         self,
75         self_ty: Ty<'tcx>,
76         trait_ref: Option<ty::TraitRef<'tcx>>,
77     ) -> Result<Self::Path, Self::Error>;
78
79     fn path_append_impl(
80         self,
81         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
82         disambiguated_data: &DisambiguatedDefPathData,
83         self_ty: Ty<'tcx>,
84         trait_ref: Option<ty::TraitRef<'tcx>>,
85     ) -> Result<Self::Path, Self::Error>;
86
87     fn path_append(
88         self,
89         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
90         disambiguated_data: &DisambiguatedDefPathData,
91     ) -> Result<Self::Path, Self::Error>;
92
93     fn path_generic_args(
94         self,
95         print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
96         args: &[GenericArg<'tcx>],
97     ) -> Result<Self::Path, Self::Error>;
98
99     // Defaults (should not be overridden):
100
101     #[instrument(skip(self), level = "debug")]
102     fn default_print_def_path(
103         self,
104         def_id: DefId,
105         substs: &'tcx [GenericArg<'tcx>],
106     ) -> Result<Self::Path, Self::Error> {
107         let key = self.tcx().def_key(def_id);
108         debug!(?key);
109
110         match key.disambiguated_data.data {
111             DefPathData::CrateRoot => {
112                 assert!(key.parent.is_none());
113                 self.path_crate(def_id.krate)
114             }
115
116             DefPathData::Impl => {
117                 let generics = self.tcx().generics_of(def_id);
118                 let self_ty = self.tcx().bound_type_of(def_id);
119                 let impl_trait_ref = self.tcx().bound_impl_trait_ref(def_id);
120                 let (self_ty, impl_trait_ref) = if substs.len() >= generics.count() {
121                     (
122                         self_ty.subst(self.tcx(), substs),
123                         impl_trait_ref.map(|i| i.subst(self.tcx(), substs)),
124                     )
125                 } else {
126                     (self_ty.0, impl_trait_ref.map(|i| i.0))
127                 };
128                 self.print_impl_path(def_id, substs, self_ty, impl_trait_ref)
129             }
130
131             _ => {
132                 let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id };
133
134                 let mut parent_substs = substs;
135                 let mut trait_qualify_parent = false;
136                 if !substs.is_empty() {
137                     let generics = self.tcx().generics_of(def_id);
138                     parent_substs = &substs[..generics.parent_count.min(substs.len())];
139
140                     match key.disambiguated_data.data {
141                         // Closures' own generics are only captures, don't print them.
142                         DefPathData::ClosureExpr => {}
143                         // This covers both `DefKind::AnonConst` and `DefKind::InlineConst`.
144                         // Anon consts doesn't have their own generics, and inline consts' own
145                         // generics are their inferred types, so don't print them.
146                         DefPathData::AnonConst => {}
147
148                         // If we have any generic arguments to print, we do that
149                         // on top of the same path, but without its own generics.
150                         _ => {
151                             if !generics.params.is_empty() && substs.len() >= generics.count() {
152                                 let args = generics.own_substs_no_defaults(self.tcx(), substs);
153                                 return self.path_generic_args(
154                                     |cx| cx.print_def_path(def_id, parent_substs),
155                                     args,
156                                 );
157                             }
158                         }
159                     }
160
161                     // FIXME(eddyb) try to move this into the parent's printing
162                     // logic, instead of doing it when printing the child.
163                     trait_qualify_parent = generics.has_self
164                         && generics.parent == Some(parent_def_id)
165                         && parent_substs.len() == generics.parent_count
166                         && self.tcx().generics_of(parent_def_id).parent_count == 0;
167                 }
168
169                 self.path_append(
170                     |cx: Self| {
171                         if trait_qualify_parent {
172                             let trait_ref = ty::TraitRef::new(
173                                 parent_def_id,
174                                 cx.tcx().intern_substs(parent_substs),
175                             );
176                             cx.path_qualified(trait_ref.self_ty(), Some(trait_ref))
177                         } else {
178                             cx.print_def_path(parent_def_id, parent_substs)
179                         }
180                     },
181                     &key.disambiguated_data,
182                 )
183             }
184         }
185     }
186
187     fn default_print_impl_path(
188         self,
189         impl_def_id: DefId,
190         _substs: &'tcx [GenericArg<'tcx>],
191         self_ty: Ty<'tcx>,
192         impl_trait_ref: Option<ty::TraitRef<'tcx>>,
193     ) -> Result<Self::Path, Self::Error> {
194         debug!(
195             "default_print_impl_path: impl_def_id={:?}, self_ty={}, impl_trait_ref={:?}",
196             impl_def_id, self_ty, impl_trait_ref
197         );
198
199         let key = self.tcx().def_key(impl_def_id);
200         let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id };
201
202         // Decide whether to print the parent path for the impl.
203         // Logically, since impls are global, it's never needed, but
204         // users may find it useful. Currently, we omit the parent if
205         // the impl is either in the same module as the self-type or
206         // as the trait.
207         let in_self_mod = match characteristic_def_id_of_type(self_ty) {
208             None => false,
209             Some(ty_def_id) => self.tcx().parent(ty_def_id) == parent_def_id,
210         };
211         let in_trait_mod = match impl_trait_ref {
212             None => false,
213             Some(trait_ref) => self.tcx().parent(trait_ref.def_id) == parent_def_id,
214         };
215
216         if !in_self_mod && !in_trait_mod {
217             // If the impl is not co-located with either self-type or
218             // trait-type, then fallback to a format that identifies
219             // the module more clearly.
220             self.path_append_impl(
221                 |cx| cx.print_def_path(parent_def_id, &[]),
222                 &key.disambiguated_data,
223                 self_ty,
224                 impl_trait_ref,
225             )
226         } else {
227             // Otherwise, try to give a good form that would be valid language
228             // syntax. Preferably using associated item notation.
229             self.path_qualified(self_ty, impl_trait_ref)
230         }
231     }
232 }
233
234 /// As a heuristic, when we see an impl, if we see that the
235 /// 'self type' is a type defined in the same module as the impl,
236 /// we can omit including the path to the impl itself. This
237 /// function tries to find a "characteristic `DefId`" for a
238 /// type. It's just a heuristic so it makes some questionable
239 /// decisions and we may want to adjust it later.
240 ///
241 /// Visited set is needed to avoid full iteration over
242 /// deeply nested tuples that have no DefId.
243 fn characteristic_def_id_of_type_cached<'a>(
244     ty: Ty<'a>,
245     visited: &mut SsoHashSet<Ty<'a>>,
246 ) -> Option<DefId> {
247     match *ty.kind() {
248         ty::Adt(adt_def, _) => Some(adt_def.did()),
249
250         ty::Dynamic(data, ..) => data.principal_def_id(),
251
252         ty::Array(subty, _) | ty::Slice(subty) => {
253             characteristic_def_id_of_type_cached(subty, visited)
254         }
255
256         ty::RawPtr(mt) => characteristic_def_id_of_type_cached(mt.ty, visited),
257
258         ty::Ref(_, ty, _) => characteristic_def_id_of_type_cached(ty, visited),
259
260         ty::Tuple(ref tys) => tys.iter().find_map(|ty| {
261             if visited.insert(ty) {
262                 return characteristic_def_id_of_type_cached(ty, visited);
263             }
264             return None;
265         }),
266
267         ty::FnDef(def_id, _)
268         | ty::Closure(def_id, _)
269         | ty::Generator(def_id, _, _)
270         | ty::Foreign(def_id) => Some(def_id),
271
272         ty::Bool
273         | ty::Char
274         | ty::Int(_)
275         | ty::Uint(_)
276         | ty::Str
277         | ty::FnPtr(_)
278         | ty::Alias(..)
279         | ty::Placeholder(..)
280         | ty::Param(_)
281         | ty::Infer(_)
282         | ty::Bound(..)
283         | ty::Error(_)
284         | ty::GeneratorWitness(..)
285         | ty::Never
286         | ty::Float(_) => None,
287     }
288 }
289 pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
290     characteristic_def_id_of_type_cached(ty, &mut SsoHashSet::new())
291 }
292
293 impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Region<'tcx> {
294     type Output = P::Region;
295     type Error = P::Error;
296     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
297         cx.print_region(*self)
298     }
299 }
300
301 impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> {
302     type Output = P::Type;
303     type Error = P::Error;
304
305     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
306         cx.print_type(*self)
307     }
308 }
309
310 impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
311     type Output = P::DynExistential;
312     type Error = P::Error;
313     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
314         cx.print_dyn_existential(self)
315     }
316 }
317
318 impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for ty::Const<'tcx> {
319     type Output = P::Const;
320     type Error = P::Error;
321     fn print(&self, cx: P) -> Result<Self::Output, Self::Error> {
322         cx.print_const(*self)
323     }
324 }
325
326 // This is only used by query descriptions
327 pub fn describe_as_module(def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
328     if def_id.is_top_level_module() {
329         "top-level module".to_string()
330     } else {
331         format!("module `{}`", tcx.def_path_str(def_id.to_def_id()))
332     }
333 }