Skip to content

Commit c0eee71

Browse files
committed
Auto merge of #143922 - nnethercote:join_path, r=<try>
Improve path segment joining r? `@ghost`
2 parents ad635e5 + f0a57ad commit c0eee71

File tree

23 files changed

+140
-126
lines changed

23 files changed

+140
-126
lines changed

compiler/rustc_ast/src/ast.rs

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
//! - [`Attribute`]: Metadata associated with item.
1919
//! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators.
2020
21-
use std::borrow::Cow;
21+
use std::borrow::{Borrow, Cow};
2222
use std::{cmp, fmt};
2323

2424
pub use GenericArgs::*;
@@ -155,6 +155,57 @@ impl Path {
155155
}
156156
}
157157

158+
/// Joins multiple symbols with "::" into a path, e.g. "a::b::c". If the first
159+
/// segment is `kw::PathRoot` it will be printed as empty, e.g. "::b::c".
160+
///
161+
/// The generics on the `path` argument mean it can accept many forms, such as:
162+
/// - `&[Symbol]`
163+
/// - `Vec<Symbol>`
164+
/// - `Vec<&Symbol>`
165+
/// - `impl Iterator<Item = Symbol>`
166+
/// - `impl Iterator<Item = &Symbol>`
167+
///
168+
/// Panics if `path` is empty or a segment after the first is `kw::PathRoot`.
169+
pub fn join_path_syms(path: impl IntoIterator<Item = impl Borrow<Symbol>>) -> String {
170+
// This is a guess at the needed capacity that works well in practice. It is slightly faster
171+
// than (a) starting with an empty string, or (b) computing the exact capacity required.
172+
let mut iter = path.into_iter();
173+
let len_hint = iter.size_hint().1.unwrap_or(1);
174+
let mut s = String::with_capacity(len_hint * 8);
175+
176+
let first_sym = *iter.next().unwrap().borrow();
177+
if first_sym != kw::PathRoot {
178+
s.push_str(first_sym.as_str());
179+
}
180+
for sym in iter {
181+
let sym = *sym.borrow();
182+
debug_assert_ne!(sym, kw::PathRoot);
183+
s.push_str("::");
184+
s.push_str(sym.as_str());
185+
}
186+
s
187+
}
188+
189+
/// Like `join_path_syms`, but for `Ident`s. This function is necessary because
190+
/// `Ident::to_string` does more than just print the symbol in the `name` field.
191+
pub fn join_path_idents(path: impl IntoIterator<Item = impl Borrow<Ident>>) -> String {
192+
let mut iter = path.into_iter();
193+
let len_hint = iter.size_hint().1.unwrap_or(1);
194+
let mut s = String::with_capacity(len_hint * 8);
195+
196+
let first_ident = *iter.next().unwrap().borrow();
197+
if first_ident.name != kw::PathRoot {
198+
s.push_str(&first_ident.to_string());
199+
}
200+
for ident in iter {
201+
let ident = *ident.borrow();
202+
debug_assert_ne!(ident.name, kw::PathRoot);
203+
s.push_str("::");
204+
s.push_str(&ident.to_string());
205+
}
206+
s
207+
}
208+
158209
/// A segment of a path: an identifier, an optional lifetime, and a set of types.
159210
///
160211
/// E.g., `std`, `String` or `Box<T>`.

compiler/rustc_builtin_macros/src/source_util.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ use std::sync::Arc;
44

55
use rustc_ast as ast;
66
use rustc_ast::ptr::P;
7-
use rustc_ast::token;
87
use rustc_ast::tokenstream::TokenStream;
8+
use rustc_ast::{join_path_idents, token};
99
use rustc_ast_pretty::pprust;
1010
use rustc_expand::base::{
1111
DummyResult, ExpandResult, ExtCtxt, MacEager, MacResult, MacroExpanderResult, resolve_path,
@@ -100,7 +100,7 @@ pub(crate) fn expand_mod(
100100
let sp = cx.with_def_site_ctxt(sp);
101101
check_zero_tts(cx, sp, tts, "module_path!");
102102
let mod_path = &cx.current_expansion.module.mod_path;
103-
let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
103+
let string = join_path_idents(mod_path);
104104

105105
ExpandResult::Ready(MacEager::expr(cx.expr_str(sp, Symbol::intern(&string))))
106106
}

compiler/rustc_builtin_macros/src/test.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::assert_matches::assert_matches;
55
use std::iter;
66

77
use rustc_ast::ptr::P;
8-
use rustc_ast::{self as ast, GenericParamKind, attr};
8+
use rustc_ast::{self as ast, GenericParamKind, attr, join_path_idents};
99
use rustc_ast_pretty::pprust;
1010
use rustc_errors::{Applicability, Diag, Level};
1111
use rustc_expand::base::*;
@@ -446,12 +446,7 @@ fn get_location_info(cx: &ExtCtxt<'_>, fn_: &ast::Fn) -> (Symbol, usize, usize,
446446
}
447447

448448
fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String {
449-
mod_path
450-
.iter()
451-
.chain(iter::once(item_ident))
452-
.map(|x| x.to_string())
453-
.collect::<Vec<String>>()
454-
.join("::")
449+
join_path_idents(mod_path.iter().chain(iter::once(item_ident)))
455450
}
456451

457452
enum ShouldPanic {

compiler/rustc_hir/src/definitions.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -181,32 +181,26 @@ pub struct DisambiguatedDefPathData {
181181
}
182182

183183
impl DisambiguatedDefPathData {
184-
pub fn fmt_maybe_verbose(&self, writer: &mut impl Write, verbose: bool) -> fmt::Result {
184+
pub fn as_sym(&self, verbose: bool) -> Symbol {
185185
match self.data.name() {
186186
DefPathDataName::Named(name) => {
187187
if verbose && self.disambiguator != 0 {
188-
write!(writer, "{}#{}", name, self.disambiguator)
188+
Symbol::intern(&format!("{}#{}", name, self.disambiguator))
189189
} else {
190-
writer.write_str(name.as_str())
190+
name
191191
}
192192
}
193193
DefPathDataName::Anon { namespace } => {
194194
if let DefPathData::AnonAssocTy(method) = self.data {
195-
write!(writer, "{}::{{{}#{}}}", method, namespace, self.disambiguator)
195+
Symbol::intern(&format!("{}::{{{}#{}}}", method, namespace, self.disambiguator))
196196
} else {
197-
write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
197+
Symbol::intern(&format!("{{{}#{}}}", namespace, self.disambiguator))
198198
}
199199
}
200200
}
201201
}
202202
}
203203

204-
impl fmt::Display for DisambiguatedDefPathData {
205-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206-
self.fmt_maybe_verbose(f, true)
207-
}
208-
}
209-
210204
#[derive(Clone, Debug, Encodable, Decodable)]
211205
pub struct DefPath {
212206
/// The path leading from the crate root to the item.
@@ -250,7 +244,7 @@ impl DefPath {
250244
let mut s = String::with_capacity(self.data.len() * 16);
251245

252246
for component in &self.data {
253-
write!(s, "::{component}").unwrap();
247+
write!(s, "::{}", component.as_sym(true)).unwrap();
254248
}
255249

256250
s
@@ -266,7 +260,7 @@ impl DefPath {
266260
for component in &self.data {
267261
s.extend(opt_delimiter);
268262
opt_delimiter = Some('-');
269-
write!(s, "{component}").unwrap();
263+
write!(s, "{}", component.as_sym(true)).unwrap();
270264
}
271265

272266
s

compiler/rustc_hir/src/hir.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_ast::token::CommentKind;
77
use rustc_ast::util::parser::ExprPrecedence;
88
use rustc_ast::{
99
self as ast, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece, IntTy, Label, LitIntType,
10-
LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind,
10+
LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind, join_path_idents,
1111
};
1212
pub use rustc_ast::{
1313
AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
@@ -1168,7 +1168,7 @@ impl AttrPath {
11681168

11691169
impl fmt::Display for AttrPath {
11701170
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171-
write!(f, "{}", self.segments.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("::"))
1171+
write!(f, "{}", join_path_idents(&self.segments))
11721172
}
11731173
}
11741174

compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::fmt::Write;
22

33
use hir::def_id::DefId;
44
use hir::{HirId, ItemKind};
5+
use rustc_ast::join_path_idents;
56
use rustc_errors::Applicability;
67
use rustc_hir as hir;
78
use rustc_lint::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER};
@@ -383,13 +384,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
383384
// All that is left is `_`! We need to use the full path. It doesn't matter which one we
384385
// pick, so just take the first one.
385386
match import_items[0].kind {
386-
ItemKind::Use(path, _) => Some(
387-
path.segments
388-
.iter()
389-
.map(|segment| segment.ident.to_string())
390-
.collect::<Vec<_>>()
391-
.join("::"),
392-
),
387+
ItemKind::Use(path, _) => {
388+
Some(join_path_idents(path.segments.iter().map(|seg| seg.ident)))
389+
}
393390
_ => {
394391
span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind);
395392
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2430,7 +2430,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> {
24302430
}
24312431

24322432
let verbose = self.should_print_verbose();
2433-
disambiguated_data.fmt_maybe_verbose(self, verbose)?;
2433+
write!(self, "{}", disambiguated_data.as_sym(verbose))?;
24342434

24352435
self.empty_path = false;
24362436

compiler/rustc_passes/src/check_attr.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::collections::hash_map::Entry;
1010
use std::slice;
1111

1212
use rustc_abi::{Align, ExternAbi, Size};
13-
use rustc_ast::{AttrStyle, LitKind, MetaItemInner, MetaItemKind, ast};
13+
use rustc_ast::{AttrStyle, LitKind, MetaItemInner, MetaItemKind, ast, join_path_syms};
1414
use rustc_attr_data_structures::{AttributeKind, InlineAttr, ReprAttr, find_attr};
1515
use rustc_attr_parsing::{AttributeParser, Late};
1616
use rustc_data_structures::fx::FxHashMap;
@@ -673,9 +673,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
673673
allowed_target: Target,
674674
) {
675675
if target != allowed_target {
676-
let path = attr.path();
677-
let path: Vec<_> = path.iter().map(|s| s.as_str()).collect();
678-
let attr_name = path.join("::");
676+
let attr_name = join_path_syms(attr.path());
679677
self.tcx.emit_node_span_lint(
680678
UNUSED_ATTRIBUTES,
681679
hir_id,

compiler/rustc_resolve/src/diagnostics.rs

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ use rustc_ast::expand::StrippedCfgItem;
22
use rustc_ast::ptr::P;
33
use rustc_ast::visit::{self, Visitor};
44
use rustc_ast::{
5-
self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemInner, MetaItemKind, ModKind, NodeId, Path,
5+
self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemInner, MetaItemKind, ModKind, NodeId,
6+
Path, join_path_idents,
67
};
78
use rustc_ast_pretty::pprust;
89
use rustc_attr_data_structures::{self as attr, AttributeKind, Stability, find_attr};
@@ -2019,7 +2020,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
20192020
}
20202021
}
20212022

2022-
let mut sugg_paths = vec![];
2023+
let mut sugg_paths: Vec<(Vec<Ident>, bool)> = vec![];
20232024
if let Some(mut def_id) = res.opt_def_id() {
20242025
// We can't use `def_path_str` in resolve.
20252026
let mut path = vec![def_id];
@@ -2032,16 +2033,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
20322033
}
20332034
}
20342035
// We will only suggest importing directly if it is accessible through that path.
2035-
let path_names: Option<Vec<String>> = path
2036+
let path_names: Option<Vec<Ident>> = path
20362037
.iter()
20372038
.rev()
20382039
.map(|def_id| {
2039-
self.tcx.opt_item_name(*def_id).map(|n| {
2040-
if def_id.is_top_level_module() {
2041-
"crate".to_string()
2040+
self.tcx.opt_item_name(*def_id).map(|name| {
2041+
Ident::with_dummy_span(if def_id.is_top_level_module() {
2042+
kw::Crate
20422043
} else {
2043-
n.to_string()
2044-
}
2044+
name
2045+
})
20452046
})
20462047
})
20472048
.collect();
@@ -2085,13 +2086,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
20852086
match binding.kind {
20862087
NameBindingKind::Import { import, .. } => {
20872088
for segment in import.module_path.iter().skip(1) {
2088-
path.push(segment.ident.to_string());
2089+
path.push(segment.ident);
20892090
}
20902091
sugg_paths.push((
2091-
path.iter()
2092-
.cloned()
2093-
.chain(vec![ident.to_string()].into_iter())
2094-
.collect::<Vec<_>>(),
2092+
path.iter().cloned().chain(vec![ident].into_iter()).collect::<Vec<_>>(),
20952093
true, // re-export
20962094
));
20972095
}
@@ -2127,7 +2125,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
21272125
err.subdiagnostic(note);
21282126
}
21292127
// We prioritize shorter paths, non-core imports and direct imports over the alternatives.
2130-
sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0] == "core", *reexport));
2128+
sugg_paths.sort_by_key(|(p, reexport)| (p.len(), p[0].name == sym::core, *reexport));
21312129
for (sugg, reexport) in sugg_paths {
21322130
if not_publicly_reexported {
21332131
break;
@@ -2137,7 +2135,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
21372135
// `tests/ui/imports/issue-55884-2.rs`
21382136
continue;
21392137
}
2140-
let path = sugg.join("::");
2138+
let path = join_path_idents(sugg);
21412139
let sugg = if reexport {
21422140
errors::ImportIdent::ThroughReExport { span: dedup_span, ident, path }
21432141
} else {

compiler/rustc_resolve/src/rustdoc.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use pulldown_cmark::{
77
};
88
use rustc_ast as ast;
99
use rustc_ast::attr::AttributeExt;
10+
use rustc_ast::join_path_syms;
1011
use rustc_ast::util::comments::beautify_doc_string;
1112
use rustc_data_structures::fx::FxIndexMap;
1213
use rustc_data_structures::unord::UnordSet;
@@ -259,7 +260,7 @@ pub fn main_body_opts() -> Options {
259260
| Options::ENABLE_SMART_PUNCTUATION
260261
}
261262

262-
fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<String, MalformedGenerics> {
263+
fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<Symbol, MalformedGenerics> {
263264
let mut stripped_segment = String::new();
264265
let mut param_depth = 0;
265266

@@ -284,7 +285,7 @@ fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<String, Malfor
284285
}
285286

286287
if param_depth == 0 {
287-
Ok(stripped_segment)
288+
Ok(Symbol::intern(&stripped_segment))
288289
} else {
289290
// The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
290291
Err(MalformedGenerics::UnbalancedAngleBrackets)
@@ -346,9 +347,8 @@ pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGen
346347

347348
debug!("path_str: {path_str:?}\nstripped segments: {stripped_segments:?}");
348349

349-
let stripped_path = stripped_segments.join("::");
350-
351-
if !stripped_path.is_empty() {
350+
if !stripped_segments.is_empty() {
351+
let stripped_path = join_path_syms(stripped_segments);
352352
Ok(stripped_path.into())
353353
} else {
354354
Err(MalformedGenerics::MissingType)

0 commit comments

Comments
 (0)