Auto merge of #80119 - GuillaumeGomez:str-to-symbol, r=jyn514

Continue String to Symbol conversion in rustdoc

Follow-up of https://github.com/rust-lang/rust/pull/80091.

This PR is already big enough so I'll stop here before the next one.

r? `@jyn514`
This commit is contained in:
bors 2020-12-18 05:55:24 +00:00
commit fee693d08e
9 changed files with 74 additions and 69 deletions

View File

@ -61,10 +61,10 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
.params
.iter()
.filter_map(|param| match param.kind {
ty::GenericParamDefKind::Lifetime => Some(param.name.to_string()),
ty::GenericParamDefKind::Lifetime => Some(param.name),
_ => None,
})
.map(|name| (name.clone(), Lifetime(name)))
.map(|name| (name, Lifetime(name)))
.collect();
let lifetime_predicates = self.handle_lifetimes(&region_data, &names_map);
let new_generics = self.param_env_to_generics(
@ -145,21 +145,21 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
fn get_lifetime(
&self,
region: Region<'_>,
names_map: &FxHashMap<String, Lifetime>,
names_map: &FxHashMap<Symbol, Lifetime>,
) -> Lifetime {
self.region_name(region)
.map(|name| {
names_map.get(&name).unwrap_or_else(|| {
panic!("Missing lifetime with name {:?} for {:?}", name, region)
panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
})
})
.unwrap_or(&Lifetime::statik())
.clone()
}
fn region_name(&self, region: Region<'_>) -> Option<String> {
fn region_name(&self, region: Region<'_>) -> Option<Symbol> {
match region {
&ty::ReEarlyBound(r) => Some(r.name.to_string()),
&ty::ReEarlyBound(r) => Some(r.name),
_ => None,
}
}
@ -177,7 +177,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
fn handle_lifetimes<'cx>(
&self,
regions: &RegionConstraintData<'cx>,
names_map: &FxHashMap<String, Lifetime>,
names_map: &FxHashMap<Symbol, Lifetime>,
) -> Vec<WherePredicate> {
// Our goal is to 'flatten' the list of constraints by eliminating
// all intermediate RegionVids. At the end, all constraints should

View File

@ -486,13 +486,13 @@ fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>)
const_stability: None,
deprecation: None,
kind: clean::ImportItem(clean::Import::new_simple(
item.ident.to_string(),
item.ident.name,
clean::ImportSource {
path: clean::Path {
global: false,
res: item.res,
segments: vec![clean::PathSegment {
name: clean::PrimitiveType::from(p).as_str().to_string(),
name: clean::PrimitiveType::from(p).as_sym(),
args: clean::GenericArgs::AngleBracketed {
args: Vec::new(),
bindings: Vec::new(),
@ -562,11 +562,11 @@ fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind
.collect::<String>()
);
clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from).clean(cx) })
clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
}
LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
kind: ext.macro_kind(),
helpers: ext.helper_attrs.clean(cx),
helpers: ext.helper_attrs,
}),
}
}

View File

@ -379,7 +379,7 @@ impl Clean<Lifetime> for hir::Lifetime {
}
_ => {}
}
Lifetime(self.name.ident().to_string())
Lifetime(self.name.ident().name)
}
}
@ -397,9 +397,9 @@ impl Clean<Lifetime> for hir::GenericParam<'_> {
for bound in bounds {
s.push_str(&format!(" + {}", bound.name.ident()));
}
Lifetime(s)
Lifetime(Symbol::intern(&s))
} else {
Lifetime(self.name.ident().to_string())
Lifetime(self.name.ident().name)
}
}
_ => panic!(),
@ -423,16 +423,16 @@ impl Clean<Constant> for hir::ConstArg {
impl Clean<Lifetime> for ty::GenericParamDef {
fn clean(&self, _cx: &DocContext<'_>) -> Lifetime {
Lifetime(self.name.to_string())
Lifetime(self.name)
}
}
impl Clean<Option<Lifetime>> for ty::RegionKind {
fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> {
fn clean(&self, _cx: &DocContext<'_>) -> Option<Lifetime> {
match *self {
ty::ReStatic => Some(Lifetime::statik()),
ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name)),
ty::ReEarlyBound(ref data) => Some(Lifetime(data.name)),
ty::ReLateBound(..)
| ty::ReFree(..)
@ -897,7 +897,7 @@ fn clean_fn_or_proc_macro(
}
}
}
ProcMacroItem(ProcMacro { kind, helpers: helpers.clean(cx) })
ProcMacroItem(ProcMacro { kind, helpers })
}
None => {
let mut func = (sig, generics, body_id).clean(cx);
@ -1914,7 +1914,7 @@ impl Clean<GenericArgs> for hir::GenericArgs<'_> {
impl Clean<PathSegment> for hir::PathSegment<'_> {
fn clean(&self, cx: &DocContext<'_>) -> PathSegment {
PathSegment { name: self.ident.name.clean(cx), args: self.generic_args().clean(cx) }
PathSegment { name: self.ident.name, args: self.generic_args().clean(cx) }
}
}
@ -2132,7 +2132,6 @@ fn clean_extern_crate(
return items;
}
}
let path = orig_name.map(|x| x.to_string());
// FIXME: using `from_def_id_and_kind` breaks `rustdoc/masked` for some reason
vec![Item {
name: None,
@ -2143,7 +2142,7 @@ fn clean_extern_crate(
stability: None,
const_stability: None,
deprecation: None,
kind: ExternCrateItem(name.clean(cx), path),
kind: ExternCrateItem(name, orig_name),
}]
}
@ -2215,7 +2214,7 @@ impl Clean<Vec<Item>> for doctree::Import<'_> {
const_stability: None,
deprecation: None,
kind: ImportItem(Import::new_simple(
self.name.clean(cx),
self.name,
resolve_use_source(cx, path),
false,
)),
@ -2223,7 +2222,7 @@ impl Clean<Vec<Item>> for doctree::Import<'_> {
return items;
}
}
Import::new_simple(name.clean(cx), resolve_use_source(cx, path), true)
Import::new_simple(name, resolve_use_source(cx, path), true)
};
vec![Item {

View File

@ -295,7 +295,7 @@ impl Item {
#[derive(Clone, Debug)]
crate enum ItemKind {
ExternCrateItem(String, Option<String>),
ExternCrateItem(Symbol, Option<Symbol>),
ImportItem(Import),
StructItem(Struct),
UnionItem(Union),
@ -877,21 +877,19 @@ impl GenericBound {
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
crate struct Lifetime(pub String);
crate struct Lifetime(pub Symbol);
impl Lifetime {
crate fn get_ref<'a>(&'a self) -> &'a str {
let Lifetime(ref s) = *self;
let s: &'a str = s;
s
crate fn get_ref(&self) -> SymbolStr {
self.0.as_str()
}
crate fn statik() -> Lifetime {
Lifetime("'static".to_string())
Lifetime(kw::StaticLifetime)
}
crate fn elided() -> Lifetime {
Lifetime("'_".to_string())
Lifetime(kw::UnderscoreLifetime)
}
}
@ -1675,13 +1673,17 @@ crate struct Path {
}
impl Path {
crate fn last_name(&self) -> &str {
crate fn last(&self) -> Symbol {
self.segments.last().expect("segments were empty").name
}
crate fn last_name(&self) -> SymbolStr {
self.segments.last().expect("segments were empty").name.as_str()
}
crate fn whole_name(&self) -> String {
String::from(if self.global { "::" } else { "" })
+ &self.segments.iter().map(|s| s.name.clone()).collect::<Vec<_>>().join("::")
+ &self.segments.iter().map(|s| s.name.to_string()).collect::<Vec<_>>().join("::")
}
}
@ -1700,7 +1702,7 @@ crate enum GenericArgs {
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
crate struct PathSegment {
crate name: String,
crate name: Symbol,
crate args: GenericArgs,
}
@ -1777,7 +1779,7 @@ crate struct Import {
}
impl Import {
crate fn new_simple(name: String, source: ImportSource, should_be_displayed: bool) -> Self {
crate fn new_simple(name: Symbol, source: ImportSource, should_be_displayed: bool) -> Self {
Self { kind: ImportKind::Simple(name), source, should_be_displayed }
}
@ -1789,7 +1791,7 @@ impl Import {
#[derive(Clone, Debug)]
crate enum ImportKind {
// use source as str;
Simple(String),
Simple(Symbol),
// use source::*;
Glob,
}
@ -1803,13 +1805,13 @@ crate struct ImportSource {
#[derive(Clone, Debug)]
crate struct Macro {
crate source: String,
crate imported_from: Option<String>,
crate imported_from: Option<Symbol>,
}
#[derive(Clone, Debug)]
crate struct ProcMacro {
crate kind: MacroKind,
crate helpers: Vec<String>,
crate helpers: Vec<Symbol>,
}
/// An type binding on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or

View File

@ -153,7 +153,7 @@ pub(super) fn external_path(
global: false,
res: Res::Err,
segments: vec![PathSegment {
name: name.to_string(),
name,
args: external_generic_args(cx, trait_did, has_self, bindings, substs),
}],
}

View File

@ -308,7 +308,7 @@ impl<'a> fmt::Display for WhereClause<'a> {
}
impl clean::Lifetime {
crate fn print(&self) -> &str {
crate fn print(&self) -> impl fmt::Display + '_ {
self.get_ref()
}
}
@ -445,11 +445,10 @@ impl clean::GenericArgs {
impl clean::PathSegment {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| {
f.write_str(&self.name)?;
if f.alternate() {
write!(f, "{:#}", self.args.print())
write!(f, "{}{:#}", self.name, self.args.print())
} else {
write!(f, "{}", self.args.print())
write!(f, "{}{}", self.name, self.args.print())
}
})
}
@ -544,7 +543,7 @@ fn resolved_path(
last.name.to_string()
}
} else {
anchor(did, &last.name).to_string()
anchor(did, &*last.name.as_str()).to_string()
};
write!(w, "{}{}", path, last.args.print())?;
}
@ -1159,11 +1158,11 @@ impl PrintWithSpace for hir::Mutability {
impl clean::Import {
crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| match self.kind {
clean::ImportKind::Simple(ref name) => {
if *name == self.source.path.last_name() {
clean::ImportKind::Simple(name) => {
if name == self.source.path.last() {
write!(f, "use {};", self.source.print())
} else {
write!(f, "use {} as {};", self.source.print(), *name)
write!(f, "use {} as {};", self.source.print(), name)
}
}
clean::ImportKind::Glob => {
@ -1187,7 +1186,7 @@ impl clean::ImportSource {
}
let name = self.path.last_name();
if let hir::def::Res::PrimTy(p) = self.path.res {
primitive_link(f, PrimitiveType::from(p), name)?;
primitive_link(f, PrimitiveType::from(p), &*name)?;
} else {
write!(f, "{}", name)?;
}

View File

@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use std::path::Path;
use rustc_data_structures::fx::FxHashMap;
use rustc_span::symbol::sym;
use rustc_span::symbol::{sym, Symbol};
use serde::Serialize;
use crate::clean::types::GetDefId;
@ -191,12 +191,12 @@ fn get_index_type(clean_type: &clean::Type) -> RenderType {
RenderType {
ty: clean_type.def_id(),
idx: None,
name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
name: get_index_type_name(clean_type, true).map(|s| s.as_str().to_ascii_lowercase()),
generics: get_generics(clean_type),
}
}
fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<Symbol> {
match *clean_type {
clean::ResolvedPath { ref path, .. } => {
let segments = &path.segments;
@ -206,10 +206,10 @@ fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option
clean_type, accept_generic
)
});
Some(path_segment.name.clone())
Some(path_segment.name)
}
clean::Generic(s) if accept_generic => Some(s.to_string()),
clean::Primitive(ref p) => Some(format!("{:?}", p)),
clean::Generic(s) if accept_generic => Some(s),
clean::Primitive(ref p) => Some(p.as_sym()),
clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
// FIXME: add all from clean::Type.
_ => None,
@ -222,7 +222,7 @@ fn get_generics(clean_type: &clean::Type) -> Option<Vec<Generic>> {
.iter()
.filter_map(|t| {
get_index_type_name(t, false).map(|name| Generic {
name: name.to_ascii_lowercase(),
name: name.as_str().to_ascii_lowercase(),
defid: t.def_id(),
idx: None,
})

View File

@ -2141,14 +2141,14 @@ fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean:
w,
"<tr><td><code>{}extern crate {} as {};",
myitem.visibility.print_with_space(),
anchor(myitem.def_id, src),
anchor(myitem.def_id, &*src.as_str()),
name
),
None => write!(
w,
"<tr><td><code>{}extern crate {};",
myitem.visibility.print_with_space(),
anchor(myitem.def_id, name)
anchor(myitem.def_id, &*name.as_str())
),
}
write!(w, "</code></td></tr>");
@ -2448,7 +2448,7 @@ fn render_implementor(
implementor: &Impl,
parent: &clean::Item,
w: &mut Buffer,
implementor_dups: &FxHashMap<&str, (DefId, bool)>,
implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
aliases: &[String],
cache: &Cache,
) {
@ -2459,7 +2459,7 @@ fn render_implementor(
| clean::BorrowedRef {
type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
..
} => implementor_dups[path.last_name()].1,
} => implementor_dups[&path.last()].1,
_ => false,
};
render_impl(
@ -2708,7 +2708,7 @@ fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait,
if let Some(implementors) = cache.implementors.get(&it.def_id) {
// The DefId is for the first Type found with that name. The bool is
// if any Types with the same name but different DefId have been found.
let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
for implementor in implementors {
match implementor.inner_impl().for_ {
clean::ResolvedPath { ref path, did, is_generic: false, .. }
@ -2717,7 +2717,7 @@ fn item_trait(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Trait,
..
} => {
let &mut (prev_did, ref mut has_duplicates) =
implementor_dups.entry(path.last_name()).or_insert((did, false));
implementor_dups.entry(path.last()).or_insert((did, false));
if prev_did != did {
*has_duplicates = true;
}

View File

@ -120,7 +120,7 @@ impl From<clean::GenericArg> for GenericArg {
fn from(arg: clean::GenericArg) -> Self {
use clean::GenericArg::*;
match arg {
Lifetime(l) => GenericArg::Lifetime(l.0),
Lifetime(l) => GenericArg::Lifetime(l.0.to_string()),
Type(t) => GenericArg::Type(t.into()),
Const(c) => GenericArg::Const(c.into()),
}
@ -163,7 +163,9 @@ impl From<clean::ItemKind> for ItemEnum {
use clean::ItemKind::*;
match item {
ModuleItem(m) => ItemEnum::ModuleItem(m.into()),
ExternCrateItem(c, a) => ItemEnum::ExternCrateItem { name: c, rename: a },
ExternCrateItem(c, a) => {
ItemEnum::ExternCrateItem { name: c.to_string(), rename: a.map(|x| x.to_string()) }
}
ImportItem(i) => ItemEnum::ImportItem(i.into()),
StructItem(s) => ItemEnum::StructItem(s.into()),
UnionItem(u) => ItemEnum::StructItem(u.into()),
@ -302,7 +304,7 @@ impl From<clean::WherePredicate> for WherePredicate {
bounds: bounds.into_iter().map(Into::into).collect(),
},
RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate {
lifetime: lifetime.0,
lifetime: lifetime.0.to_string(),
bounds: bounds.into_iter().map(Into::into).collect(),
},
EqPredicate { lhs, rhs } => {
@ -323,7 +325,7 @@ impl From<clean::GenericBound> for GenericBound {
modifier: modifier.into(),
}
}
Outlives(lifetime) => GenericBound::Outlives(lifetime.0),
Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
}
}
}
@ -365,7 +367,7 @@ impl From<clean::Type> for Type {
type_: Box::new((*type_).into()),
},
BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef {
lifetime: lifetime.map(|l| l.0),
lifetime: lifetime.map(|l| l.0.to_string()),
mutable: mutability == ast::Mutability::Mut,
type_: Box::new((*type_).into()),
},
@ -503,7 +505,7 @@ impl From<clean::Import> for Import {
match import.kind {
Simple(s) => Import {
span: import.source.path.whole_name(),
name: s,
name: s.to_string(),
id: import.source.did.map(Into::into),
glob: false,
},
@ -519,7 +521,10 @@ impl From<clean::Import> for Import {
impl From<clean::ProcMacro> for ProcMacro {
fn from(mac: clean::ProcMacro) -> Self {
ProcMacro { kind: mac.kind.into(), helpers: mac.helpers }
ProcMacro {
kind: mac.kind.into(),
helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
}
}
}