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
11mod 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
22pub trait Printer<'tcx>: Sized {
29 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
30
31 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 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 (
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 fn print_region(&mut self, region: ty::Region<'tcx>) -> Result<(), PrintError>;
68
69 fn print_type(&mut self, ty: Ty<'tcx>) -> Result<(), PrintError>;
71
72 fn print_dyn_existential(
74 &mut self,
75 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
76 ) -> Result<(), PrintError>;
77
78 fn print_const(&mut self, ct: ty::Const<'tcx>) -> Result<(), PrintError>;
80
81 fn print_crate_name(&mut self, cnum: CrateNum) -> Result<(), PrintError>;
83
84 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 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 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 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 #[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 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 }
182 }
183 DefPathData::SyntheticCoroutineBody => {
184 }
187 DefPathData::AnonConst => {}
191
192 _ => {
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 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 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 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 self.print_path_with_qualified(self_ty, impl_trait_ref)
273 }
274 }
275}
276
277fn 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}