Skip to content

Commit c6622d1

Browse files
committed
Auto merge of #76176 - marmeladema:fix-closure-path-printing, r=eddyb
Move from {{closure}}#0 syntax to {closure#0} for (def) path components Part of #70334 I followed the approach described by `@eddyb` and introduced a `DefPathDataName` enum. To preserve compatibility, in various places, I had to rely on formatting manually by calling `format!("{{{{{}}}}}", namespace)`. My questions are: * Do we want to convert for places to use the new naming scheme? Or shall I re-add `DefPathData::as_symbol` but renamed as `DefPathData::as_legacy_symbol` to avoid manually allocating the legacy symbols? * Do we want to `impl Display for DisambiguatedDefPathData` to avoid manually calling `write!(s, "{{{}#{}}}", namespace, component.disambiguator)`? * We might also want to improve naming for `DefPathDataName` and `DefPathData::get_name` r? `@eddyb`
2 parents 043f6d7 + 5946c12 commit c6622d1

File tree

99 files changed

+299
-281
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

99 files changed

+299
-281
lines changed

compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,18 @@ pub fn item_namespace(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope {
2727
.parent
2828
.map(|parent| item_namespace(cx, DefId { krate: def_id.krate, index: parent }));
2929

30+
let crate_name_as_str;
31+
let name_to_string;
3032
let namespace_name = match def_key.disambiguated_data.data {
31-
DefPathData::CrateRoot => cx.tcx.crate_name(def_id.krate),
32-
data => data.as_symbol(),
33+
DefPathData::CrateRoot => {
34+
crate_name_as_str = cx.tcx.crate_name(def_id.krate).as_str();
35+
&*crate_name_as_str
36+
}
37+
data => {
38+
name_to_string = data.to_string();
39+
&*name_to_string
40+
}
3341
};
34-
let namespace_name = namespace_name.as_str();
3542

3643
let scope = unsafe {
3744
llvm::LLVMRustDIBuilderCreateNameSpace(

compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use rustc_hir as hir;
55
use rustc_hir::def_id::DefId;
66
use rustc_middle::ty::{self, subst::SubstsRef, Ty, TyCtxt};
77

8+
use std::fmt::Write;
9+
810
// Compute the name of the type as it should be stored in debuginfo. Does not do
911
// any caching, i.e., calling the function twice with the same type will also do
1012
// the work twice. The `qualified` parameter only affects the first level of the
@@ -228,8 +230,7 @@ pub fn push_debuginfo_type_name<'tcx>(
228230
if qualified {
229231
output.push_str(&tcx.crate_name(def_id.krate).as_str());
230232
for path_element in tcx.def_path(def_id).data {
231-
output.push_str("::");
232-
output.push_str(&path_element.data.as_symbol().as_str());
233+
write!(output, "::{}", path_element.data).unwrap();
233234
}
234235
} else {
235236
output.push_str(&tcx.item_name(def_id).as_str());

compiler/rustc_hir/src/definitions.rs

+54-42
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ use rustc_data_structures::fx::FxHashMap;
1313
use rustc_data_structures::stable_hasher::StableHasher;
1414
use rustc_index::vec::IndexVec;
1515
use rustc_span::hygiene::ExpnId;
16-
use rustc_span::symbol::{sym, Symbol};
16+
use rustc_span::symbol::{kw, sym, Symbol};
1717

18-
use std::fmt::Write;
18+
use std::fmt::{self, Write};
1919
use std::hash::Hash;
2020
use tracing::debug;
2121

@@ -155,6 +155,29 @@ pub struct DisambiguatedDefPathData {
155155
pub disambiguator: u32,
156156
}
157157

158+
impl DisambiguatedDefPathData {
159+
pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
160+
match self.data.name() {
161+
DefPathDataName::Named(name) => {
162+
if verbose && self.disambiguator != 0 {
163+
write!(writer, "{}#{}", name, self.disambiguator)
164+
} else {
165+
writer.write_str(&name.as_str())
166+
}
167+
}
168+
DefPathDataName::Anon { namespace } => {
169+
write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
170+
}
171+
}
172+
}
173+
}
174+
175+
impl fmt::Display for DisambiguatedDefPathData {
176+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177+
self.fmt_maybe_verbose(f, true)
178+
}
179+
}
180+
158181
#[derive(Clone, Debug, Encodable, Decodable)]
159182
pub struct DefPath {
160183
/// The path leading from the crate root to the item.
@@ -198,33 +221,11 @@ impl DefPath {
198221
/// Returns a string representation of the `DefPath` without
199222
/// the crate-prefix. This method is useful if you don't have
200223
/// a `TyCtxt` available.
201-
pub fn to_string_no_crate(&self) -> String {
224+
pub fn to_string_no_crate_verbose(&self) -> String {
202225
let mut s = String::with_capacity(self.data.len() * 16);
203226

204227
for component in &self.data {
205-
write!(s, "::{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
206-
}
207-
208-
s
209-
}
210-
211-
/// Returns a filename-friendly string for the `DefPath`, with the
212-
/// crate-prefix.
213-
pub fn to_string_friendly<F>(&self, crate_imported_name: F) -> String
214-
where
215-
F: FnOnce(CrateNum) -> Symbol,
216-
{
217-
let crate_name_str = crate_imported_name(self.krate).as_str();
218-
let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
219-
220-
write!(s, "::{}", crate_name_str).unwrap();
221-
222-
for component in &self.data {
223-
if component.disambiguator == 0 {
224-
write!(s, "::{}", component.data.as_symbol()).unwrap();
225-
} else {
226-
write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
227-
}
228+
write!(s, "::{}", component).unwrap();
228229
}
229230

230231
s
@@ -240,12 +241,9 @@ impl DefPath {
240241
for component in &self.data {
241242
s.extend(opt_delimiter);
242243
opt_delimiter = Some('-');
243-
if component.disambiguator == 0 {
244-
write!(s, "{}", component.data.as_symbol()).unwrap();
245-
} else {
246-
write!(s, "{}[{}]", component.data.as_symbol(), component.disambiguator).unwrap();
247-
}
244+
write!(s, "{}", component).unwrap();
248245
}
246+
249247
s
250248
}
251249
}
@@ -427,6 +425,12 @@ impl Definitions {
427425
}
428426
}
429427

428+
#[derive(Copy, Clone, PartialEq, Debug)]
429+
pub enum DefPathDataName {
430+
Named(Symbol),
431+
Anon { namespace: Symbol },
432+
}
433+
430434
impl DefPathData {
431435
pub fn get_opt_name(&self) -> Option<Symbol> {
432436
use self::DefPathData::*;
@@ -437,22 +441,30 @@ impl DefPathData {
437441
}
438442
}
439443

440-
pub fn as_symbol(&self) -> Symbol {
444+
pub fn name(&self) -> DefPathDataName {
441445
use self::DefPathData::*;
442446
match *self {
443-
TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => name,
447+
TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => {
448+
DefPathDataName::Named(name)
449+
}
444450
// Note that this does not show up in user print-outs.
445-
CrateRoot => sym::double_braced_crate,
446-
Impl => sym::double_braced_impl,
447-
Misc => sym::double_braced_misc,
448-
ClosureExpr => sym::double_braced_closure,
449-
Ctor => sym::double_braced_constructor,
450-
AnonConst => sym::double_braced_constant,
451-
ImplTrait => sym::double_braced_opaque,
451+
CrateRoot => DefPathDataName::Anon { namespace: kw::Crate },
452+
Impl => DefPathDataName::Anon { namespace: kw::Impl },
453+
Misc => DefPathDataName::Anon { namespace: sym::misc },
454+
ClosureExpr => DefPathDataName::Anon { namespace: sym::closure },
455+
Ctor => DefPathDataName::Anon { namespace: sym::constructor },
456+
AnonConst => DefPathDataName::Anon { namespace: sym::constant },
457+
ImplTrait => DefPathDataName::Anon { namespace: sym::opaque },
452458
}
453459
}
460+
}
454461

455-
pub fn to_string(&self) -> String {
456-
self.as_symbol().to_string()
462+
impl fmt::Display for DefPathData {
463+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464+
match self.name() {
465+
DefPathDataName::Named(name) => f.write_str(&name.as_str()),
466+
// FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc
467+
DefPathDataName::Anon { namespace } => write!(f, "{{{{{}}}}}", namespace),
468+
}
457469
}
458470
}

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
531531
disambiguated_data: &DisambiguatedDefPathData,
532532
) -> Result<Self::Path, Self::Error> {
533533
let mut path = print_prefix(self)?;
534-
path.push(disambiguated_data.data.as_symbol().to_string());
534+
path.push(disambiguated_data.to_string());
535535
Ok(path)
536536
}
537537
fn path_generic_args(

compiler/rustc_lint/src/context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -846,7 +846,7 @@ impl<'tcx> LateContext<'tcx> {
846846
return Ok(path);
847847
}
848848

849-
path.push(disambiguated_data.data.as_symbol());
849+
path.push(Symbol::intern(&disambiguated_data.data.to_string()));
850850
Ok(path)
851851
}
852852

compiler/rustc_middle/src/hir/map/collector.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
244244
if cfg!(debug_assertions) {
245245
if hir_id.owner != self.current_dep_node_owner {
246246
let node_str = match self.definitions.opt_hir_id_to_local_def_id(hir_id) {
247-
Some(def_id) => self.definitions.def_path(def_id).to_string_no_crate(),
247+
Some(def_id) => self.definitions.def_path(def_id).to_string_no_crate_verbose(),
248248
None => format!("{:?}", node),
249249
};
250250

@@ -254,9 +254,11 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
254254
current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
255255
self.source_map.span_to_string(span),
256256
node_str,
257-
self.definitions.def_path(self.current_dep_node_owner).to_string_no_crate(),
257+
self.definitions
258+
.def_path(self.current_dep_node_owner)
259+
.to_string_no_crate_verbose(),
258260
self.current_dep_node_owner,
259-
self.definitions.def_path(hir_id.owner).to_string_no_crate(),
261+
self.definitions.def_path(hir_id.owner).to_string_no_crate_verbose(),
260262
hir_id.owner,
261263
)
262264
}

compiler/rustc_middle/src/hir/map/mod.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -1002,11 +1002,7 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
10021002
let def_id = map.local_def_id(id);
10031003
tcx.def_path_str(def_id.to_def_id())
10041004
} else if let Some(path) = map.def_path_from_hir_id(id) {
1005-
path.data
1006-
.into_iter()
1007-
.map(|elem| elem.data.to_string())
1008-
.collect::<Vec<_>>()
1009-
.join("::")
1005+
path.data.into_iter().map(|elem| elem.to_string()).collect::<Vec<_>>().join("::")
10101006
} else {
10111007
String::from("<missing path>")
10121008
}

compiler/rustc_middle/src/ty/context.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1272,7 +1272,7 @@ impl<'tcx> TyCtxt<'tcx> {
12721272
// Don't print the whole crate disambiguator. That's just
12731273
// annoying in debug output.
12741274
&(crate_disambiguator.to_fingerprint().to_hex())[..4],
1275-
self.def_path(def_id).to_string_no_crate()
1275+
self.def_path(def_id).to_string_no_crate_verbose()
12761276
)
12771277
}
12781278

compiler/rustc_middle/src/ty/print/pretty.rs

+10-14
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_data_structures::fx::FxHashMap;
1111
use rustc_hir as hir;
1212
use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
1313
use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, CRATE_DEF_INDEX, LOCAL_CRATE};
14-
use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
14+
use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
1515
use rustc_hir::ItemKind;
1616
use rustc_session::config::TrimmedDefPaths;
1717
use rustc_span::symbol::{kw, Ident, Symbol};
@@ -1498,25 +1498,21 @@ impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
14981498

14991499
// FIXME(eddyb) `name` should never be empty, but it
15001500
// currently is for `extern { ... }` "foreign modules".
1501-
let name = disambiguated_data.data.as_symbol();
1502-
if name != kw::Invalid {
1501+
let name = disambiguated_data.data.name();
1502+
if name != DefPathDataName::Named(kw::Invalid) {
15031503
if !self.empty_path {
15041504
write!(self, "::")?;
15051505
}
1506-
if Ident::with_dummy_span(name).is_raw_guess() {
1507-
write!(self, "r#")?;
1508-
}
1509-
write!(self, "{}", name)?;
15101506

1511-
// FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it
1512-
// might be nicer to use something else, e.g. `{closure#3}`.
1513-
let dis = disambiguated_data.disambiguator;
1514-
let print_dis = disambiguated_data.data.get_opt_name().is_none()
1515-
|| dis != 0 && self.tcx.sess.verbose();
1516-
if print_dis {
1517-
write!(self, "#{}", dis)?;
1507+
if let DefPathDataName::Named(name) = name {
1508+
if Ident::with_dummy_span(name).is_raw_guess() {
1509+
write!(self, "r#")?;
1510+
}
15181511
}
15191512

1513+
let verbose = self.tcx.sess.verbose();
1514+
disambiguated_data.fmt_maybe_verbose(&mut self, verbose)?;
1515+
15201516
self.empty_path = false;
15211517
}
15221518

compiler/rustc_middle/src/ty/query/profiling_support.rs

+6-3
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,22 @@ impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> {
5555
};
5656

5757
let dis_buffer = &mut [0u8; 16];
58+
let crate_name;
59+
let other_name;
5860
let name;
5961
let dis;
6062
let end_index;
6163

6264
match def_key.disambiguated_data.data {
6365
DefPathData::CrateRoot => {
64-
name = self.tcx.original_crate_name(def_id.krate);
66+
crate_name = self.tcx.original_crate_name(def_id.krate).as_str();
67+
name = &*crate_name;
6568
dis = "";
6669
end_index = 3;
6770
}
6871
other => {
69-
name = other.as_symbol();
72+
other_name = other.to_string();
73+
name = other_name.as_str();
7074
if def_key.disambiguated_data.disambiguator == 0 {
7175
dis = "";
7276
end_index = 3;
@@ -80,7 +84,6 @@ impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> {
8084
}
8185
}
8286

83-
let name = &*name.as_str();
8487
let components = [
8588
StringComponent::Ref(parent_string_id),
8689
StringComponent::Value("::"),

compiler/rustc_mir/src/interpret/intrinsics/type_name.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,8 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
132132
return Ok(self);
133133
}
134134

135-
self.path.push_str("::");
135+
write!(self.path, "::{}", disambiguated_data.data).unwrap();
136136

137-
self.path.push_str(&disambiguated_data.data.as_symbol().as_str());
138137
Ok(self)
139138
}
140139

compiler/rustc_mir/src/monomorphize/partitioning/default.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::collections::hash_map::Entry;
33
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
44
use rustc_hir::def::DefKind;
55
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
6+
use rustc_hir::definitions::DefPathDataName;
67
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
78
use rustc_middle::middle::exported_symbols::SymbolExportLevel;
89
use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, Linkage, Visibility};
@@ -354,7 +355,10 @@ fn compute_codegen_unit_name(
354355
*cache.entry((cgu_def_id, volatile)).or_insert_with(|| {
355356
let def_path = tcx.def_path(cgu_def_id);
356357

357-
let components = def_path.data.iter().map(|part| part.data.as_symbol());
358+
let components = def_path.data.iter().map(|part| match part.data.name() {
359+
DefPathDataName::Named(name) => name,
360+
DefPathDataName::Anon { .. } => unreachable!(),
361+
});
358362

359363
let volatile_suffix = volatile.then_some("volatile");
360364

compiler/rustc_passes/src/hir_id_validator.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -112,14 +112,14 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
112112
missing_items.push(format!(
113113
"[local_id: {}, owner: {}]",
114114
local_id,
115-
self.hir_map.def_path(owner).to_string_no_crate()
115+
self.hir_map.def_path(owner).to_string_no_crate_verbose()
116116
));
117117
}
118118
self.error(|| {
119119
format!(
120120
"ItemLocalIds not assigned densely in {}. \
121121
Max ItemLocalId = {}, missing IDs = {:?}; seens IDs = {:?}",
122-
self.hir_map.def_path(owner).to_string_no_crate(),
122+
self.hir_map.def_path(owner).to_string_no_crate_verbose(),
123123
max,
124124
missing_items,
125125
self.hir_ids_seen
@@ -148,8 +148,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
148148
format!(
149149
"HirIdValidator: The recorded owner of {} is {} instead of {}",
150150
self.hir_map.node_to_string(hir_id),
151-
self.hir_map.def_path(hir_id.owner).to_string_no_crate(),
152-
self.hir_map.def_path(owner).to_string_no_crate()
151+
self.hir_map.def_path(hir_id.owner).to_string_no_crate_verbose(),
152+
self.hir_map.def_path(owner).to_string_no_crate_verbose()
153153
)
154154
});
155155
}

0 commit comments

Comments
 (0)