1use std::fmt::Write;
15
16use rustc_abi::Integer;
17use rustc_data_structures::fx::FxHashSet;
18use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher};
19use rustc_hir::def_id::DefId;
20use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
21use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, Mutability};
22use rustc_middle::bug;
23use rustc_middle::ty::layout::{IntegerExt, TyAndLayout};
24use rustc_middle::ty::{self, ExistentialProjection, GenericArgKind, GenericArgsRef, Ty, TyCtxt};
25use smallvec::SmallVec;
26
27use crate::debuginfo::wants_c_like_enum_debuginfo;
28
29pub fn compute_debuginfo_type_name<'tcx>(
34 tcx: TyCtxt<'tcx>,
35 t: Ty<'tcx>,
36 qualified: bool,
37) -> String {
38 let _prof = tcx.prof.generic_activity("compute_debuginfo_type_name");
39
40 let mut result = String::with_capacity(64);
41 let mut visited = FxHashSet::default();
42 push_debuginfo_type_name(tcx, t, qualified, &mut result, &mut visited);
43 result
44}
45
46fn push_debuginfo_type_name<'tcx>(
49 tcx: TyCtxt<'tcx>,
50 t: Ty<'tcx>,
51 qualified: bool,
52 output: &mut String,
53 visited: &mut FxHashSet<Ty<'tcx>>,
54) {
55 let cpp_like_debuginfo = cpp_like_debuginfo(tcx);
58
59 match *t.kind() {
60 ty::Bool => output.push_str("bool"),
61 ty::Char => output.push_str("char"),
62 ty::Str => {
63 if cpp_like_debuginfo {
64 output.push_str("str$")
65 } else {
66 output.push_str("str")
67 }
68 }
69 ty::Never => {
70 if cpp_like_debuginfo {
71 output.push_str("never$");
72 } else {
73 output.push('!');
74 }
75 }
76 ty::Int(int_ty) => output.push_str(int_ty.name_str()),
77 ty::Uint(uint_ty) => output.push_str(uint_ty.name_str()),
78 ty::Float(float_ty) => output.push_str(float_ty.name_str()),
79 ty::Foreign(def_id) => push_item_name(tcx, def_id, qualified, output),
80 ty::Adt(def, args) => {
81 let layout_for_cpp_like_fallback = if cpp_like_debuginfo && def.is_enum() {
83 match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(t)) {
84 Ok(layout) => {
85 if !wants_c_like_enum_debuginfo(tcx, layout) {
86 Some(layout)
87 } else {
88 None
91 }
92 }
93 Err(e) => {
94 tcx.dcx().emit_fatal(e.into_diagnostic());
98 }
99 }
100 } else {
101 None
103 };
104
105 if let Some(ty_and_layout) = layout_for_cpp_like_fallback {
106 msvc_enum_fallback(
107 tcx,
108 ty_and_layout,
109 &|output, visited| {
110 push_item_name(tcx, def.did(), true, output);
111 push_generic_params_internal(tcx, args, output, visited);
112 },
113 output,
114 visited,
115 );
116 } else {
117 push_item_name(tcx, def.did(), qualified, output);
118 push_generic_params_internal(tcx, args, output, visited);
119 }
120 }
121 ty::Tuple(component_types) => {
122 if cpp_like_debuginfo {
123 output.push_str("tuple$<");
124 } else {
125 output.push('(');
126 }
127
128 for component_type in component_types {
129 push_debuginfo_type_name(tcx, component_type, true, output, visited);
130 push_arg_separator(cpp_like_debuginfo, output);
131 }
132 if !component_types.is_empty() {
133 pop_arg_separator(output);
134 }
135
136 if cpp_like_debuginfo {
137 push_close_angle_bracket(cpp_like_debuginfo, output);
138 } else {
139 output.push(')');
140 }
141 }
142 ty::RawPtr(inner_type, mutbl) => {
143 if cpp_like_debuginfo {
144 match mutbl {
145 Mutability::Not => output.push_str("ptr_const$<"),
146 Mutability::Mut => output.push_str("ptr_mut$<"),
147 }
148 } else {
149 output.push('*');
150 match mutbl {
151 Mutability::Not => output.push_str("const "),
152 Mutability::Mut => output.push_str("mut "),
153 }
154 }
155
156 push_debuginfo_type_name(tcx, inner_type, qualified, output, visited);
157
158 if cpp_like_debuginfo {
159 push_close_angle_bracket(cpp_like_debuginfo, output);
160 }
161 }
162 ty::Ref(_, inner_type, mutbl) => {
163 if cpp_like_debuginfo {
164 match mutbl {
165 Mutability::Not => output.push_str("ref$<"),
166 Mutability::Mut => output.push_str("ref_mut$<"),
167 }
168 } else {
169 output.push('&');
170 output.push_str(mutbl.prefix_str());
171 }
172
173 push_debuginfo_type_name(tcx, inner_type, qualified, output, visited);
174
175 if cpp_like_debuginfo {
176 push_close_angle_bracket(cpp_like_debuginfo, output);
177 }
178 }
179 ty::Array(inner_type, len) => {
180 if cpp_like_debuginfo {
181 output.push_str("array$<");
182 push_debuginfo_type_name(tcx, inner_type, true, output, visited);
183 match len.kind() {
184 ty::ConstKind::Param(param) => write!(output, ",{}>", param.name).unwrap(),
185 _ => write!(
186 output,
187 ",{}>",
188 len.try_to_target_usize(tcx)
189 .expect("expected monomorphic const in codegen")
190 )
191 .unwrap(),
192 }
193 } else {
194 output.push('[');
195 push_debuginfo_type_name(tcx, inner_type, true, output, visited);
196 match len.kind() {
197 ty::ConstKind::Param(param) => write!(output, "; {}]", param.name).unwrap(),
198 _ => write!(
199 output,
200 "; {}]",
201 len.try_to_target_usize(tcx)
202 .expect("expected monomorphic const in codegen")
203 )
204 .unwrap(),
205 }
206 }
207 }
208 ty::Pat(inner_type, pat) => {
209 if cpp_like_debuginfo {
210 output.push_str("pat$<");
211 push_debuginfo_type_name(tcx, inner_type, true, output, visited);
212 write!(output, ",{:?}>", pat).unwrap();
214 } else {
215 write!(output, "{:?}", t).unwrap();
216 }
217 }
218 ty::Slice(inner_type) => {
219 if cpp_like_debuginfo {
220 output.push_str("slice2$<");
221 } else {
222 output.push('[');
223 }
224
225 push_debuginfo_type_name(tcx, inner_type, true, output, visited);
226
227 if cpp_like_debuginfo {
228 push_close_angle_bracket(cpp_like_debuginfo, output);
229 } else {
230 output.push(']');
231 }
232 }
233 ty::Dynamic(trait_data, ..) => {
234 let auto_traits: SmallVec<[DefId; 4]> = trait_data.auto_traits().collect();
235
236 let has_enclosing_parens = if cpp_like_debuginfo {
237 output.push_str("dyn$<");
238 false
239 } else if trait_data.len() > 1 && auto_traits.len() != 0 {
240 output.push_str("(dyn ");
242 true
243 } else {
244 output.push_str("dyn ");
245 false
246 };
247
248 if let Some(principal) = trait_data.principal() {
249 let principal = tcx.normalize_erasing_late_bound_regions(
250 ty::TypingEnv::fully_monomorphized(),
251 principal,
252 );
253 push_item_name(tcx, principal.def_id, qualified, output);
254 let principal_has_generic_params =
255 push_generic_params_internal(tcx, principal.args, output, visited);
256
257 let projection_bounds: SmallVec<[_; 4]> = trait_data
258 .projection_bounds()
259 .map(|bound| {
260 let ExistentialProjection { def_id: item_def_id, term, .. } =
261 tcx.instantiate_bound_regions_with_erased(bound);
262 (item_def_id, term.expect_type())
264 })
265 .collect();
266
267 if projection_bounds.len() != 0 {
268 if principal_has_generic_params {
269 pop_close_angle_bracket(output);
272 push_arg_separator(cpp_like_debuginfo, output);
275 } else {
276 output.push('<');
279 }
280
281 for (item_def_id, ty) in projection_bounds {
282 if cpp_like_debuginfo {
283 output.push_str("assoc$<");
284 push_item_name(tcx, item_def_id, false, output);
285 push_arg_separator(cpp_like_debuginfo, output);
286 push_debuginfo_type_name(tcx, ty, true, output, visited);
287 push_close_angle_bracket(cpp_like_debuginfo, output);
288 } else {
289 push_item_name(tcx, item_def_id, false, output);
290 output.push('=');
291 push_debuginfo_type_name(tcx, ty, true, output, visited);
292 }
293 push_arg_separator(cpp_like_debuginfo, output);
294 }
295
296 pop_arg_separator(output);
297 push_close_angle_bracket(cpp_like_debuginfo, output);
298 }
299
300 if auto_traits.len() != 0 {
301 push_auto_trait_separator(cpp_like_debuginfo, output);
302 }
303 }
304
305 if auto_traits.len() != 0 {
306 let mut auto_traits: SmallVec<[String; 4]> = auto_traits
307 .into_iter()
308 .map(|def_id| {
309 let mut name = String::with_capacity(20);
310 push_item_name(tcx, def_id, true, &mut name);
311 name
312 })
313 .collect();
314 auto_traits.sort_unstable();
315
316 for auto_trait in auto_traits {
317 output.push_str(&auto_trait);
318 push_auto_trait_separator(cpp_like_debuginfo, output);
319 }
320
321 pop_auto_trait_separator(output);
322 }
323
324 if cpp_like_debuginfo {
325 push_close_angle_bracket(cpp_like_debuginfo, output);
326 } else if has_enclosing_parens {
327 output.push(')');
328 }
329 }
330 ty::FnDef(..) | ty::FnPtr(..) => {
331 if !visited.insert(t) {
345 output.push_str(if cpp_like_debuginfo {
346 "recursive_type$"
347 } else {
348 "<recursive_type>"
349 });
350 return;
351 }
352
353 let sig = tcx.normalize_erasing_late_bound_regions(
354 ty::TypingEnv::fully_monomorphized(),
355 t.fn_sig(tcx),
356 );
357
358 if cpp_like_debuginfo {
359 if sig.output().is_unit() {
361 output.push_str("void");
362 } else {
363 push_debuginfo_type_name(tcx, sig.output(), true, output, visited);
364 }
365 output.push_str(" (*)(");
366 } else {
367 output.push_str(sig.safety.prefix_str());
368
369 if sig.abi != rustc_abi::ExternAbi::Rust {
370 let _ = write!(output, "extern {} ", sig.abi);
371 }
372
373 output.push_str("fn(");
374 }
375
376 if !sig.inputs().is_empty() {
377 for ¶meter_type in sig.inputs() {
378 push_debuginfo_type_name(tcx, parameter_type, true, output, visited);
379 push_arg_separator(cpp_like_debuginfo, output);
380 }
381 pop_arg_separator(output);
382 }
383
384 if sig.c_variadic {
385 if !sig.inputs().is_empty() {
386 output.push_str(", ...");
387 } else {
388 output.push_str("...");
389 }
390 }
391
392 output.push(')');
393
394 if !cpp_like_debuginfo && !sig.output().is_unit() {
395 output.push_str(" -> ");
396 push_debuginfo_type_name(tcx, sig.output(), true, output, visited);
397 }
398
399 visited.remove(&t);
409 }
410 ty::Closure(def_id, args)
411 | ty::CoroutineClosure(def_id, args)
412 | ty::Coroutine(def_id, args, ..) => {
413 if cpp_like_debuginfo && t.is_coroutine() {
418 let ty_and_layout =
419 tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(t)).unwrap();
420 msvc_enum_fallback(
421 tcx,
422 ty_and_layout,
423 &|output, visited| {
424 push_closure_or_coroutine_name(tcx, def_id, args, true, output, visited);
425 },
426 output,
427 visited,
428 );
429 } else {
430 push_closure_or_coroutine_name(tcx, def_id, args, qualified, output, visited);
431 }
432 }
433 ty::UnsafeBinder(_) => todo!("FIXME(unsafe_binders)"),
434 ty::Param(_)
435 | ty::Error(_)
436 | ty::Infer(_)
437 | ty::Placeholder(..)
438 | ty::Alias(..)
439 | ty::Bound(..)
440 | ty::CoroutineWitness(..) => {
441 bug!(
442 "debuginfo: Trying to create type name for \
443 unexpected type: {:?}",
444 t
445 );
446 }
447 }
448
449 fn msvc_enum_fallback<'tcx>(
454 tcx: TyCtxt<'tcx>,
455 ty_and_layout: TyAndLayout<'tcx>,
456 push_inner: &dyn Fn(&mut String, &mut FxHashSet<Ty<'tcx>>),
457 output: &mut String,
458 visited: &mut FxHashSet<Ty<'tcx>>,
459 ) {
460 assert!(!wants_c_like_enum_debuginfo(tcx, ty_and_layout));
461 output.push_str("enum2$<");
462 push_inner(output, visited);
463 push_close_angle_bracket(true, output);
464 }
465
466 const NON_CPP_AUTO_TRAIT_SEPARATOR: &str = " + ";
467
468 fn push_auto_trait_separator(cpp_like_debuginfo: bool, output: &mut String) {
469 if cpp_like_debuginfo {
470 push_arg_separator(cpp_like_debuginfo, output);
471 } else {
472 output.push_str(NON_CPP_AUTO_TRAIT_SEPARATOR);
473 }
474 }
475
476 fn pop_auto_trait_separator(output: &mut String) {
477 if output.ends_with(NON_CPP_AUTO_TRAIT_SEPARATOR) {
478 output.truncate(output.len() - NON_CPP_AUTO_TRAIT_SEPARATOR.len());
479 } else {
480 pop_arg_separator(output);
481 }
482 }
483}
484
485pub enum VTableNameKind {
486 GlobalVariable,
488 Type,
490}
491
492pub fn compute_debuginfo_vtable_name<'tcx>(
506 tcx: TyCtxt<'tcx>,
507 t: Ty<'tcx>,
508 trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
509 kind: VTableNameKind,
510) -> String {
511 let cpp_like_debuginfo = cpp_like_debuginfo(tcx);
512
513 let mut vtable_name = String::with_capacity(64);
514
515 if cpp_like_debuginfo {
516 vtable_name.push_str("impl$<");
517 } else {
518 vtable_name.push('<');
519 }
520
521 let mut visited = FxHashSet::default();
522 push_debuginfo_type_name(tcx, t, true, &mut vtable_name, &mut visited);
523
524 if cpp_like_debuginfo {
525 vtable_name.push_str(", ");
526 } else {
527 vtable_name.push_str(" as ");
528 }
529
530 if let Some(trait_ref) = trait_ref {
531 let trait_ref =
532 tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), trait_ref);
533 push_item_name(tcx, trait_ref.def_id, true, &mut vtable_name);
534 visited.clear();
535 push_generic_params_internal(tcx, trait_ref.args, &mut vtable_name, &mut visited);
536 } else {
537 vtable_name.push('_');
538 }
539
540 push_close_angle_bracket(cpp_like_debuginfo, &mut vtable_name);
541
542 let suffix = match (cpp_like_debuginfo, kind) {
543 (true, VTableNameKind::GlobalVariable) => "::vtable$",
544 (false, VTableNameKind::GlobalVariable) => "::{vtable}",
545 (true, VTableNameKind::Type) => "::vtable_type$",
546 (false, VTableNameKind::Type) => "::{vtable_type}",
547 };
548
549 vtable_name.reserve_exact(suffix.len());
550 vtable_name.push_str(suffix);
551
552 vtable_name
553}
554
555pub fn push_item_name(tcx: TyCtxt<'_>, def_id: DefId, qualified: bool, output: &mut String) {
556 let def_key = tcx.def_key(def_id);
557 if qualified {
558 if let Some(parent) = def_key.parent {
559 push_item_name(tcx, DefId { krate: def_id.krate, index: parent }, true, output);
560 output.push_str("::");
561 }
562 }
563
564 push_unqualified_item_name(tcx, def_id, def_key.disambiguated_data, output);
565}
566
567fn coroutine_kind_label(coroutine_kind: Option<CoroutineKind>) -> &'static str {
568 use CoroutineDesugaring::*;
569 use CoroutineKind::*;
570 use CoroutineSource::*;
571 match coroutine_kind {
572 Some(Desugared(Gen, Block)) => "gen_block",
573 Some(Desugared(Gen, Closure)) => "gen_closure",
574 Some(Desugared(Gen, Fn)) => "gen_fn",
575 Some(Desugared(Async, Block)) => "async_block",
576 Some(Desugared(Async, Closure)) => "async_closure",
577 Some(Desugared(Async, Fn)) => "async_fn",
578 Some(Desugared(AsyncGen, Block)) => "async_gen_block",
579 Some(Desugared(AsyncGen, Closure)) => "async_gen_closure",
580 Some(Desugared(AsyncGen, Fn)) => "async_gen_fn",
581 Some(Coroutine(_)) => "coroutine",
582 None => "closure",
583 }
584}
585
586fn push_disambiguated_special_name(
587 label: &str,
588 disambiguator: u32,
589 cpp_like_debuginfo: bool,
590 output: &mut String,
591) {
592 if cpp_like_debuginfo {
593 write!(output, "{label}${disambiguator}").unwrap();
594 } else {
595 write!(output, "{{{label}#{disambiguator}}}").unwrap();
596 }
597}
598
599fn push_unqualified_item_name(
600 tcx: TyCtxt<'_>,
601 def_id: DefId,
602 disambiguated_data: DisambiguatedDefPathData,
603 output: &mut String,
604) {
605 match disambiguated_data.data {
606 DefPathData::CrateRoot => {
607 output.push_str(tcx.crate_name(def_id.krate).as_str());
608 }
609 DefPathData::Closure => {
610 let label = coroutine_kind_label(tcx.coroutine_kind(def_id));
611
612 push_disambiguated_special_name(
613 label,
614 disambiguated_data.disambiguator,
615 cpp_like_debuginfo(tcx),
616 output,
617 );
618 }
619 _ => match disambiguated_data.data.name() {
620 DefPathDataName::Named(name) => {
621 output.push_str(name.as_str());
622 }
623 DefPathDataName::Anon { namespace } => {
624 push_disambiguated_special_name(
625 namespace.as_str(),
626 disambiguated_data.disambiguator,
627 cpp_like_debuginfo(tcx),
628 output,
629 );
630 }
631 },
632 };
633}
634
635fn push_generic_params_internal<'tcx>(
636 tcx: TyCtxt<'tcx>,
637 args: GenericArgsRef<'tcx>,
638 output: &mut String,
639 visited: &mut FxHashSet<Ty<'tcx>>,
640) -> bool {
641 assert_eq!(args, tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), args));
642 let mut args = args.non_erasable_generics().peekable();
643 if args.peek().is_none() {
644 return false;
645 }
646 let cpp_like_debuginfo = cpp_like_debuginfo(tcx);
647
648 output.push('<');
649
650 for type_parameter in args {
651 match type_parameter {
652 GenericArgKind::Type(type_parameter) => {
653 push_debuginfo_type_name(tcx, type_parameter, true, output, visited);
654 }
655 GenericArgKind::Const(ct) => {
656 push_const_param(tcx, ct, output);
657 }
658 other => bug!("Unexpected non-erasable generic: {:?}", other),
659 }
660
661 push_arg_separator(cpp_like_debuginfo, output);
662 }
663 pop_arg_separator(output);
664 push_close_angle_bracket(cpp_like_debuginfo, output);
665
666 true
667}
668
669fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut String) {
670 match ct.kind() {
671 ty::ConstKind::Param(param) => {
672 write!(output, "{}", param.name)
673 }
674 ty::ConstKind::Value(cv) => {
675 match cv.ty.kind() {
676 ty::Int(ity) => {
677 let bits = cv
678 .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
679 .expect("expected monomorphic const in codegen");
680 let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
681 write!(output, "{val}")
682 }
683 ty::Uint(_) => {
684 let val = cv
685 .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
686 .expect("expected monomorphic const in codegen");
687 write!(output, "{val}")
688 }
689 ty::Bool => {
690 let val = cv.try_to_bool().expect("expected monomorphic const in codegen");
691 write!(output, "{val}")
692 }
693 _ => {
694 let hash_short = tcx.with_stable_hashing_context(|mut hcx| {
701 let mut hasher = StableHasher::new();
702 hcx.while_hashing_spans(false, |hcx| cv.hash_stable(hcx, &mut hasher));
703 hasher.finish::<Hash64>()
704 });
705
706 if cpp_like_debuginfo(tcx) {
707 write!(output, "CONST${hash_short:x}")
708 } else {
709 write!(output, "{{CONST#{hash_short:x}}}")
710 }
711 }
712 }
713 }
714 _ => bug!("Invalid `Const` during codegen: {:?}", ct),
715 }
716 .unwrap();
717}
718
719pub fn push_generic_params<'tcx>(
720 tcx: TyCtxt<'tcx>,
721 args: GenericArgsRef<'tcx>,
722 output: &mut String,
723) {
724 let _prof = tcx.prof.generic_activity("compute_debuginfo_type_name");
725 let mut visited = FxHashSet::default();
726 push_generic_params_internal(tcx, args, output, &mut visited);
727}
728
729fn push_closure_or_coroutine_name<'tcx>(
730 tcx: TyCtxt<'tcx>,
731 def_id: DefId,
732 args: GenericArgsRef<'tcx>,
733 qualified: bool,
734 output: &mut String,
735 visited: &mut FxHashSet<Ty<'tcx>>,
736) {
737 let def_key = tcx.def_key(def_id);
740 let coroutine_kind = tcx.coroutine_kind(def_id);
741
742 if qualified {
743 let parent_def_id = DefId { index: def_key.parent.unwrap(), ..def_id };
744 push_item_name(tcx, parent_def_id, true, output);
745 output.push_str("::");
746 }
747
748 let mut label = String::with_capacity(20);
749 write!(&mut label, "{}_env", coroutine_kind_label(coroutine_kind)).unwrap();
750
751 push_disambiguated_special_name(
752 &label,
753 def_key.disambiguated_data.disambiguator,
754 cpp_like_debuginfo(tcx),
755 output,
756 );
757
758 let enclosing_fn_def_id = tcx.typeck_root_def_id(def_id);
764 let generics = tcx.generics_of(enclosing_fn_def_id);
765
766 let args = args.truncate_to(tcx, generics);
771 push_generic_params_internal(tcx, args, output, visited);
772}
773
774fn push_close_angle_bracket(cpp_like_debuginfo: bool, output: &mut String) {
775 if cpp_like_debuginfo && output.ends_with('>') {
778 output.push(' ')
779 };
780
781 output.push('>');
782}
783
784fn pop_close_angle_bracket(output: &mut String) {
785 assert!(output.ends_with('>'), "'output' does not end with '>': {output}");
786 output.pop();
787 if output.ends_with(' ') {
788 output.pop();
789 }
790}
791
792fn push_arg_separator(cpp_like_debuginfo: bool, output: &mut String) {
793 if cpp_like_debuginfo {
797 output.push(',');
798 } else {
799 output.push_str(", ");
800 };
801}
802
803fn pop_arg_separator(output: &mut String) {
804 if output.ends_with(' ') {
805 output.pop();
806 }
807
808 assert!(output.ends_with(','));
809
810 output.pop();
811}
812
813pub fn cpp_like_debuginfo(tcx: TyCtxt<'_>) -> bool {
815 tcx.sess.target.is_like_msvc
816}