1
Fork 0

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

Replace String with Symbol where possible

The same as #80047 but on different types. Might be interesting to run some perf comparison.

r? `@jyn514`
This commit is contained in:
bors 2020-12-17 06:00:12 +00:00
commit bdd0a78582
11 changed files with 109 additions and 106 deletions

View file

@ -333,10 +333,9 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
match br { match br {
// We only care about named late bound regions, as we need to add them // We only care about named late bound regions, as we need to add them
// to the 'for<>' section // to the 'for<>' section
ty::BrNamed(_, name) => Some(GenericParamDef { ty::BrNamed(_, name) => {
name: name.to_string(), Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
kind: GenericParamDefKind::Lifetime, }
}),
_ => None, _ => None,
} }
}) })
@ -569,7 +568,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
} }
WherePredicate::EqPredicate { lhs, rhs } => { WherePredicate::EqPredicate { lhs, rhs } => {
match lhs { match lhs {
Type::QPath { name: ref left_name, ref self_type, ref trait_ } => { Type::QPath { name: left_name, ref self_type, ref trait_ } => {
let ty = &*self_type; let ty = &*self_type;
match **trait_ { match **trait_ {
Type::ResolvedPath { Type::ResolvedPath {
@ -580,7 +579,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
} => { } => {
let mut new_trait_path = trait_path.clone(); let mut new_trait_path = trait_path.clone();
if self.is_fn_ty(tcx, trait_) && left_name == FN_OUTPUT_NAME { if self.is_fn_ty(tcx, trait_) && left_name == sym::Output {
ty_to_fn ty_to_fn
.entry(*ty.clone()) .entry(*ty.clone())
.and_modify(|e| *e = (e.0.clone(), Some(rhs.clone()))) .and_modify(|e| *e = (e.0.clone(), Some(rhs.clone())))

View file

@ -12,7 +12,7 @@ use rustc_metadata::creader::LoadedMacro;
use rustc_middle::ty; use rustc_middle::ty;
use rustc_mir::const_eval::is_min_const_fn; use rustc_mir::const_eval::is_min_const_fn;
use rustc_span::hygiene::MacroKind; use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{sym, Symbol}; use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::Span; use rustc_span::Span;
use crate::clean::{self, Attributes, GetDefId, ToSource, TypeKind}; use crate::clean::{self, Attributes, GetDefId, ToSource, TypeKind};
@ -583,7 +583,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean:
for pred in &mut g.where_predicates { for pred in &mut g.where_predicates {
match *pred { match *pred {
clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds } clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
if *s == "Self" => if *s == kw::SelfUpper =>
{ {
bounds.retain(|bound| match *bound { bounds.retain(|bound| match *bound {
clean::GenericBound::TraitBound( clean::GenericBound::TraitBound(
@ -606,7 +606,7 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean:
name: ref _name, name: ref _name,
}, },
ref bounds, ref bounds,
} => !(bounds.is_empty() || *s == "Self" && did == trait_did), } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
_ => true, _ => true,
}); });
g g
@ -621,7 +621,7 @@ fn separate_supertrait_bounds(
let mut ty_bounds = Vec::new(); let mut ty_bounds = Vec::new();
g.where_predicates.retain(|pred| match *pred { g.where_predicates.retain(|pred| match *pred {
clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds } clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
if *s == "Self" => if *s == kw::SelfUpper =>
{ {
ty_bounds.extend(bounds.iter().cloned()); ty_bounds.extend(bounds.iter().cloned());
false false

View file

@ -48,8 +48,6 @@ crate use self::types::Type::*;
crate use self::types::Visibility::{Inherited, Public}; crate use self::types::Visibility::{Inherited, Public};
crate use self::types::*; crate use self::types::*;
const FN_OUTPUT_NAME: &str = "Output";
crate trait Clean<T> { crate trait Clean<T> {
fn clean(&self, cx: &DocContext<'_>) -> T; fn clean(&self, cx: &DocContext<'_>) -> T;
} }
@ -329,10 +327,9 @@ impl Clean<GenericBound> for (ty::PolyTraitRef<'_>, &[TypeBinding]) {
.collect_referenced_late_bound_regions(&poly_trait_ref) .collect_referenced_late_bound_regions(&poly_trait_ref)
.into_iter() .into_iter()
.filter_map(|br| match br { .filter_map(|br| match br {
ty::BrNamed(_, name) => Some(GenericParamDef { ty::BrNamed(_, name) => {
name: name.to_string(), Some(GenericParamDef { name, kind: GenericParamDefKind::Lifetime })
kind: GenericParamDefKind::Lifetime, }
}),
_ => None, _ => None,
}) })
.collect(); .collect();
@ -546,7 +543,7 @@ impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"),
}; };
Type::QPath { Type::QPath {
name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx), name: cx.tcx.associated_item(self.item_def_id).ident.name,
self_type: box self.self_ty().clean(cx), self_type: box self.self_ty().clean(cx),
trait_: box trait_, trait_: box trait_,
} }
@ -556,14 +553,12 @@ impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
impl Clean<GenericParamDef> for ty::GenericParamDef { impl Clean<GenericParamDef> for ty::GenericParamDef {
fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef { fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef {
let (name, kind) = match self.kind { let (name, kind) = match self.kind {
ty::GenericParamDefKind::Lifetime => { ty::GenericParamDefKind::Lifetime => (self.name, GenericParamDefKind::Lifetime),
(self.name.to_string(), GenericParamDefKind::Lifetime)
}
ty::GenericParamDefKind::Type { has_default, synthetic, .. } => { ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
let default = let default =
if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None }; if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None };
( (
self.name.clean(cx), self.name,
GenericParamDefKind::Type { GenericParamDefKind::Type {
did: self.def_id, did: self.def_id,
bounds: vec![], // These are filled in from the where-clauses. bounds: vec![], // These are filled in from the where-clauses.
@ -573,7 +568,7 @@ impl Clean<GenericParamDef> for ty::GenericParamDef {
) )
} }
ty::GenericParamDefKind::Const { .. } => ( ty::GenericParamDefKind::Const { .. } => (
self.name.clean(cx), self.name,
GenericParamDefKind::Const { GenericParamDefKind::Const {
did: self.def_id, did: self.def_id,
ty: cx.tcx.type_of(self.def_id).clean(cx), ty: cx.tcx.type_of(self.def_id).clean(cx),
@ -599,14 +594,14 @@ impl Clean<GenericParamDef> for hir::GenericParam<'_> {
for bound in bounds { for bound in bounds {
s.push_str(&format!(" + {}", bound.name.ident())); s.push_str(&format!(" + {}", bound.name.ident()));
} }
s Symbol::intern(&s)
} else { } else {
self.name.ident().to_string() self.name.ident().name
}; };
(name, GenericParamDefKind::Lifetime) (name, GenericParamDefKind::Lifetime)
} }
hir::GenericParamKind::Type { ref default, synthetic } => ( hir::GenericParamKind::Type { ref default, synthetic } => (
self.name.ident().name.clean(cx), self.name.ident().name,
GenericParamDefKind::Type { GenericParamDefKind::Type {
did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(), did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
bounds: self.bounds.clean(cx), bounds: self.bounds.clean(cx),
@ -615,7 +610,7 @@ impl Clean<GenericParamDef> for hir::GenericParam<'_> {
}, },
), ),
hir::GenericParamKind::Const { ref ty } => ( hir::GenericParamKind::Const { ref ty } => (
self.name.ident().name.clean(cx), self.name.ident().name,
GenericParamDefKind::Const { GenericParamDefKind::Const {
did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(), did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
ty: ty.clean(cx), ty: ty.clean(cx),
@ -730,7 +725,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
.collect::<Vec<GenericParamDef>>(); .collect::<Vec<GenericParamDef>>();
// param index -> [(DefId of trait, associated type name, type)] // param index -> [(DefId of trait, associated type name, type)]
let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, String, Ty<'tcx>)>>::default(); let mut impl_trait_proj = FxHashMap::<u32, Vec<(DefId, Symbol, Ty<'tcx>)>>::default();
let where_predicates = preds let where_predicates = preds
.predicates .predicates
@ -778,11 +773,10 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
if let Some(((_, trait_did, name), rhs)) = if let Some(((_, trait_did, name), rhs)) =
proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs))) proj.as_ref().and_then(|(lhs, rhs)| Some((lhs.projection()?, rhs)))
{ {
impl_trait_proj.entry(param_idx).or_default().push(( impl_trait_proj
trait_did, .entry(param_idx)
name.to_string(), .or_default()
rhs, .push((trait_did, name, rhs));
));
} }
return None; return None;
@ -800,7 +794,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
if let crate::core::ImplTraitParam::ParamIndex(idx) = param { if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
if let Some(proj) = impl_trait_proj.remove(&idx) { if let Some(proj) = impl_trait_proj.remove(&idx) {
for (trait_did, name, rhs) in proj { for (trait_did, name, rhs) in proj {
simplify::merge_bounds(cx, &mut bounds, trait_did, &name, &rhs.clean(cx)); simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs.clean(cx));
} }
} }
} else { } else {
@ -936,9 +930,9 @@ impl<'a> Clean<Arguments> for (&'a [hir::Ty<'a>], &'a [Ident]) {
.iter() .iter()
.enumerate() .enumerate()
.map(|(i, ty)| { .map(|(i, ty)| {
let mut name = self.1.get(i).map(|ident| ident.to_string()).unwrap_or_default(); let mut name = self.1.get(i).map(|ident| ident.name).unwrap_or(kw::Invalid);
if name.is_empty() { if name.is_empty() {
name = "_".to_string(); name = kw::Underscore;
} }
Argument { name, type_: ty.clean(cx) } Argument { name, type_: ty.clean(cx) }
}) })
@ -995,7 +989,7 @@ impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
.iter() .iter()
.map(|t| Argument { .map(|t| Argument {
type_: t.clean(cx), type_: t.clean(cx),
name: names.next().map_or_else(|| String::new(), |name| name.to_string()), name: names.next().map(|i| i.name).unwrap_or(kw::Invalid),
}) })
.collect(), .collect(),
}, },
@ -1150,12 +1144,12 @@ impl Clean<Item> for ty::AssocItem {
}; };
let self_arg_ty = sig.input(0).skip_binder(); let self_arg_ty = sig.input(0).skip_binder();
if self_arg_ty == self_ty { if self_arg_ty == self_ty {
decl.inputs.values[0].type_ = Generic(String::from("Self")); decl.inputs.values[0].type_ = Generic(kw::SelfUpper);
} else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() { } else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
if ty == self_ty { if ty == self_ty {
match decl.inputs.values[0].type_ { match decl.inputs.values[0].type_ {
BorrowedRef { ref mut type_, .. } => { BorrowedRef { ref mut type_, .. } => {
**type_ = Generic(String::from("Self")) **type_ = Generic(kw::SelfUpper)
} }
_ => unreachable!(), _ => unreachable!(),
} }
@ -1210,7 +1204,7 @@ impl Clean<Item> for ty::AssocItem {
} }
} }
ty::AssocKind::Type => { ty::AssocKind::Type => {
let my_name = self.ident.name.clean(cx); let my_name = self.ident.name;
if let ty::TraitContainer(_) = self.container { if let ty::TraitContainer(_) = self.container {
let bounds = cx.tcx.explicit_item_bounds(self.def_id); let bounds = cx.tcx.explicit_item_bounds(self.def_id);
@ -1235,7 +1229,7 @@ impl Clean<Item> for ty::AssocItem {
_ => return None, _ => return None,
} }
match **self_type { match **self_type {
Generic(ref s) if *s == "Self" => {} Generic(ref s) if *s == kw::SelfUpper => {}
_ => return None, _ => return None,
} }
Some(bounds) Some(bounds)
@ -1408,7 +1402,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
segments: trait_segments.clean(cx), segments: trait_segments.clean(cx),
}; };
Type::QPath { Type::QPath {
name: p.segments.last().expect("segments were empty").ident.name.clean(cx), name: p.segments.last().expect("segments were empty").ident.name,
self_type: box qself.clean(cx), self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path, hir_id), trait_: box resolve_type(cx, trait_path, hir_id),
} }
@ -1422,7 +1416,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
}; };
let trait_path = hir::Path { span, res, segments: &[] }; let trait_path = hir::Path { span, res, segments: &[] };
Type::QPath { Type::QPath {
name: segment.ident.name.clean(cx), name: segment.ident.name,
self_type: box qself.clean(cx), self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path.clean(cx), hir_id), trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
} }
@ -1625,7 +1619,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
let mut bindings = vec![]; let mut bindings = vec![];
for pb in obj.projection_bounds() { for pb in obj.projection_bounds() {
bindings.push(TypeBinding { bindings.push(TypeBinding {
name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx), name: cx.tcx.associated_item(pb.item_def_id()).ident.name,
kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) }, kind: TypeBindingKind::Equality { ty: pb.skip_binder().ty.clean(cx) },
}); });
} }
@ -1644,7 +1638,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) { if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&p.index.into()) {
ImplTrait(bounds) ImplTrait(bounds)
} else { } else {
Generic(p.name.to_string()) Generic(p.name)
} }
} }
@ -1702,8 +1696,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
.tcx .tcx
.associated_item(proj.projection_ty.item_def_id) .associated_item(proj.projection_ty.item_def_id)
.ident .ident
.name .name,
.clean(cx),
kind: TypeBindingKind::Equality { kind: TypeBindingKind::Equality {
ty: proj.ty.clean(cx), ty: proj.ty.clean(cx),
}, },
@ -2339,7 +2332,7 @@ impl Clean<Item> for (&hir::MacroDef<'_>, Option<Symbol>) {
impl Clean<TypeBinding> for hir::TypeBinding<'_> { impl Clean<TypeBinding> for hir::TypeBinding<'_> {
fn clean(&self, cx: &DocContext<'_>) -> TypeBinding { fn clean(&self, cx: &DocContext<'_>) -> TypeBinding {
TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx) } TypeBinding { name: self.ident.name, kind: self.kind.clean(cx) }
} }
} }

View file

@ -15,6 +15,7 @@ use std::collections::BTreeMap;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_middle::ty; use rustc_middle::ty;
use rustc_span::Symbol;
use crate::clean; use crate::clean;
use crate::clean::GenericArgs as PP; use crate::clean::GenericArgs as PP;
@ -78,7 +79,7 @@ crate fn merge_bounds(
cx: &clean::DocContext<'_>, cx: &clean::DocContext<'_>,
bounds: &mut Vec<clean::GenericBound>, bounds: &mut Vec<clean::GenericBound>,
trait_did: DefId, trait_did: DefId,
name: &str, name: Symbol,
rhs: &clean::Type, rhs: &clean::Type,
) -> bool { ) -> bool {
!bounds.iter_mut().any(|b| { !bounds.iter_mut().any(|b| {
@ -100,7 +101,7 @@ crate fn merge_bounds(
match last.args { match last.args {
PP::AngleBracketed { ref mut bindings, .. } => { PP::AngleBracketed { ref mut bindings, .. } => {
bindings.push(clean::TypeBinding { bindings.push(clean::TypeBinding {
name: name.to_string(), name,
kind: clean::TypeBindingKind::Equality { ty: rhs.clone() }, kind: clean::TypeBindingKind::Equality { ty: rhs.clone() },
}); });
} }

View file

@ -949,7 +949,7 @@ impl GenericParamDefKind {
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug, Hash)]
crate struct GenericParamDef { crate struct GenericParamDef {
crate name: String, crate name: Symbol,
crate kind: GenericParamDefKind, crate kind: GenericParamDefKind,
} }
@ -1037,7 +1037,7 @@ crate struct Arguments {
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug, Hash)]
crate struct Argument { crate struct Argument {
crate type_: Type, crate type_: Type,
crate name: String, crate name: Symbol,
} }
#[derive(Clone, PartialEq, Debug)] #[derive(Clone, PartialEq, Debug)]
@ -1049,7 +1049,7 @@ crate enum SelfTy {
impl Argument { impl Argument {
crate fn to_self(&self) -> Option<SelfTy> { crate fn to_self(&self) -> Option<SelfTy> {
if self.name != "self" { if self.name != kw::SelfLower {
return None; return None;
} }
if self.type_.is_self_type() { if self.type_.is_self_type() {
@ -1117,7 +1117,7 @@ crate enum Type {
}, },
/// For parameterized types, so the consumer of the JSON don't go /// For parameterized types, so the consumer of the JSON don't go
/// looking for types which don't exist anywhere. /// looking for types which don't exist anywhere.
Generic(String), Generic(Symbol),
/// Primitives are the fixed-size numeric types (plus int/usize/float), char, /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
/// arrays, slices, and tuples. /// arrays, slices, and tuples.
Primitive(PrimitiveType), Primitive(PrimitiveType),
@ -1136,7 +1136,7 @@ crate enum Type {
// `<Type as Trait>::Name` // `<Type as Trait>::Name`
QPath { QPath {
name: String, name: Symbol,
self_type: Box<Type>, self_type: Box<Type>,
trait_: Box<Type>, trait_: Box<Type>,
}, },
@ -1237,7 +1237,7 @@ impl Type {
crate fn is_self_type(&self) -> bool { crate fn is_self_type(&self) -> bool {
match *self { match *self {
Generic(ref name) => name == "Self", Generic(name) => name == kw::SelfUpper,
_ => false, _ => false,
} }
} }
@ -1282,16 +1282,16 @@ impl Type {
} }
} }
crate fn projection(&self) -> Option<(&Type, DefId, &str)> { crate fn projection(&self) -> Option<(&Type, DefId, Symbol)> {
let (self_, trait_, name) = match self { let (self_, trait_, name) = match self {
QPath { ref self_type, ref trait_, ref name } => (self_type, trait_, name), QPath { ref self_type, ref trait_, name } => (self_type, trait_, name),
_ => return None, _ => return None,
}; };
let trait_did = match **trait_ { let trait_did = match **trait_ {
ResolvedPath { did, .. } => did, ResolvedPath { did, .. } => did,
_ => return None, _ => return None,
}; };
Some((&self_, trait_did, name)) Some((&self_, trait_did, *name))
} }
} }
@ -1816,7 +1816,7 @@ crate struct ProcMacro {
/// `A: Send + Sync` in `Foo<A: Send + Sync>`). /// `A: Send + Sync` in `Foo<A: Send + Sync>`).
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug, Hash)]
crate struct TypeBinding { crate struct TypeBinding {
crate name: String, crate name: Symbol,
crate kind: TypeBindingKind, crate kind: TypeBindingKind,
} }

View file

@ -170,13 +170,13 @@ crate fn get_real_types(
cx: &DocContext<'_>, cx: &DocContext<'_>,
recurse: i32, recurse: i32,
) -> FxHashSet<(Type, TypeKind)> { ) -> FxHashSet<(Type, TypeKind)> {
let arg_s = arg.print().to_string();
let mut res = FxHashSet::default(); let mut res = FxHashSet::default();
if recurse >= 10 { if recurse >= 10 {
// FIXME: remove this whole recurse thing when the recursion bug is fixed // FIXME: remove this whole recurse thing when the recursion bug is fixed
return res; return res;
} }
if arg.is_full_generic() { if arg.is_full_generic() {
let arg_s = Symbol::intern(&arg.print().to_string());
if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g { if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g {
&WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(),
_ => false, _ => false,
@ -375,13 +375,13 @@ impl ToSource for rustc_span::Span {
} }
} }
crate fn name_from_pat(p: &hir::Pat<'_>) -> String { crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
use rustc_hir::*; use rustc_hir::*;
debug!("trying to get a name from pattern: {:?}", p); debug!("trying to get a name from pattern: {:?}", p);
match p.kind { Symbol::intern(&match p.kind {
PatKind::Wild => "_".to_string(), PatKind::Wild => return kw::Underscore,
PatKind::Binding(_, _, ident, _) => ident.to_string(), PatKind::Binding(_, _, ident, _) => return ident.name,
PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
PatKind::Struct(ref name, ref fields, etc) => format!( PatKind::Struct(ref name, ref fields, etc) => format!(
"{} {{ {}{} }}", "{} {{ {}{} }}",
@ -393,32 +393,37 @@ crate fn name_from_pat(p: &hir::Pat<'_>) -> String {
.join(", "), .join(", "),
if etc { ", .." } else { "" } if etc { ", .." } else { "" }
), ),
PatKind::Or(ref pats) => { PatKind::Or(ref pats) => pats
pats.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(" | ") .iter()
} .map(|p| name_from_pat(&**p).to_string())
.collect::<Vec<String>>()
.join(" | "),
PatKind::Tuple(ref elts, _) => format!( PatKind::Tuple(ref elts, _) => format!(
"({})", "({})",
elts.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(", ") elts.iter()
.map(|p| name_from_pat(&**p).to_string())
.collect::<Vec<String>>()
.join(", ")
), ),
PatKind::Box(ref p) => name_from_pat(&**p), PatKind::Box(ref p) => return name_from_pat(&**p),
PatKind::Ref(ref p, _) => name_from_pat(&**p), PatKind::Ref(ref p, _) => return name_from_pat(&**p),
PatKind::Lit(..) => { PatKind::Lit(..) => {
warn!( warn!(
"tried to get argument name from PatKind::Lit, which is silly in function arguments" "tried to get argument name from PatKind::Lit, which is silly in function arguments"
); );
"()".to_string() return Symbol::intern("()");
} }
PatKind::Range(..) => panic!( PatKind::Range(..) => panic!(
"tried to get argument name from PatKind::Range, \ "tried to get argument name from PatKind::Range, \
which is not allowed in function arguments" which is not allowed in function arguments"
), ),
PatKind::Slice(ref begin, ref mid, ref end) => { PatKind::Slice(ref begin, ref mid, ref end) => {
let begin = begin.iter().map(|p| name_from_pat(&**p)); let begin = begin.iter().map(|p| name_from_pat(&**p).to_string());
let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
let end = end.iter().map(|p| name_from_pat(&**p)); let end = end.iter().map(|p| name_from_pat(&**p).to_string());
format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", ")) format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
} }
} })
} }
crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
@ -534,10 +539,10 @@ crate fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
let is_generic = match path.res { let is_generic = match path.res {
Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)), Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
Res::SelfTy(..) if path.segments.len() == 1 => { Res::SelfTy(..) if path.segments.len() == 1 => {
return Generic(kw::SelfUpper.to_string()); return Generic(kw::SelfUpper);
} }
Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
return Generic(format!("{:#}", path.print())); return Generic(Symbol::intern(&format!("{:#}", path.print())));
} }
Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true, Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
_ => false, _ => false,

View file

@ -172,7 +172,7 @@ impl clean::GenericParamDef {
display_fn(move |f| match self.kind { display_fn(move |f| match self.kind {
clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name), clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => { clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
f.write_str(&self.name)?; f.write_str(&*self.name.as_str())?;
if !bounds.is_empty() { if !bounds.is_empty() {
if f.alternate() { if f.alternate() {
@ -193,13 +193,10 @@ impl clean::GenericParamDef {
Ok(()) Ok(())
} }
clean::GenericParamDefKind::Const { ref ty, .. } => { clean::GenericParamDefKind::Const { ref ty, .. } => {
f.write_str("const ")?;
f.write_str(&self.name)?;
if f.alternate() { if f.alternate() {
write!(f, ": {:#}", ty.print()) write!(f, "const {}: {:#}", self.name, ty.print())
} else { } else {
write!(f, ":&nbsp;{}", ty.print()) write!(f, "const {}:&nbsp;{}", self.name, ty.print())
} }
} }
}) })
@ -638,7 +635,7 @@ crate fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result { fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
match *t { match *t {
clean::Generic(ref name) => f.write_str(name), clean::Generic(name) => write!(f, "{}", name),
clean::ResolvedPath { did, ref param_names, ref path, is_generic } => { clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
if param_names.is_some() { if param_names.is_some() {
f.write_str("dyn ")?; f.write_str("dyn ")?;
@ -1203,7 +1200,7 @@ impl clean::ImportSource {
impl clean::TypeBinding { impl clean::TypeBinding {
crate fn print(&self) -> impl fmt::Display + '_ { crate fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| { display_fn(move |f| {
f.write_str(&self.name)?; f.write_str(&*self.name.as_str())?;
match self.kind { match self.kind {
clean::TypeBindingKind::Equality { ref ty } => { clean::TypeBindingKind::Equality { ref ty } => {
if f.alternate() { if f.alternate() {

View file

@ -208,7 +208,7 @@ fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option
}); });
Some(path_segment.name.clone()) Some(path_segment.name.clone())
} }
clean::Generic(ref s) if accept_generic => Some(s.clone()), clean::Generic(s) if accept_generic => Some(s.to_string()),
clean::Primitive(ref p) => Some(format!("{:?}", p)), clean::Primitive(ref p) => Some(format!("{:?}", p)),
clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic), clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
// FIXME: add all from clean::Type. // FIXME: add all from clean::Type.

View file

@ -136,7 +136,7 @@ impl From<clean::Constant> for Constant {
impl From<clean::TypeBinding> for TypeBinding { impl From<clean::TypeBinding> for TypeBinding {
fn from(binding: clean::TypeBinding) -> Self { fn from(binding: clean::TypeBinding) -> Self {
TypeBinding { name: binding.name, binding: binding.kind.into() } TypeBinding { name: binding.name.to_string(), binding: binding.kind.into() }
} }
} }
@ -275,7 +275,7 @@ impl From<clean::Generics> for Generics {
impl From<clean::GenericParamDef> for GenericParamDef { impl From<clean::GenericParamDef> for GenericParamDef {
fn from(generic_param: clean::GenericParamDef) -> Self { fn from(generic_param: clean::GenericParamDef) -> Self {
GenericParamDef { name: generic_param.name, kind: generic_param.kind.into() } GenericParamDef { name: generic_param.name.to_string(), kind: generic_param.kind.into() }
} }
} }
@ -351,7 +351,7 @@ impl From<clean::Type> for Type {
.map(|v| v.into_iter().map(Into::into).collect()) .map(|v| v.into_iter().map(Into::into).collect())
.unwrap_or_default(), .unwrap_or_default(),
}, },
Generic(s) => Type::Generic(s), Generic(s) => Type::Generic(s.to_string()),
Primitive(p) => Type::Primitive(p.as_str().to_string()), Primitive(p) => Type::Primitive(p.as_str().to_string()),
BareFunction(f) => Type::FunctionPointer(Box::new((*f).into())), BareFunction(f) => Type::FunctionPointer(Box::new((*f).into())),
Tuple(t) => Type::Tuple(t.into_iter().map(Into::into).collect()), Tuple(t) => Type::Tuple(t.into_iter().map(Into::into).collect()),
@ -370,7 +370,7 @@ impl From<clean::Type> for Type {
type_: Box::new((*type_).into()), type_: Box::new((*type_).into()),
}, },
QPath { name, self_type, trait_ } => Type::QualifiedPath { QPath { name, self_type, trait_ } => Type::QualifiedPath {
name, name: name.to_string(),
self_type: Box::new((*self_type).into()), self_type: Box::new((*self_type).into()),
trait_: Box::new((*trait_).into()), trait_: Box::new((*trait_).into()),
}, },
@ -394,7 +394,11 @@ impl From<clean::FnDecl> for FnDecl {
fn from(decl: clean::FnDecl) -> Self { fn from(decl: clean::FnDecl) -> Self {
let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl; let clean::FnDecl { inputs, output, c_variadic, attrs: _ } = decl;
FnDecl { FnDecl {
inputs: inputs.values.into_iter().map(|arg| (arg.name, arg.type_.into())).collect(), inputs: inputs
.values
.into_iter()
.map(|arg| (arg.name.to_string(), arg.type_.into()))
.collect(),
output: match output { output: match output {
clean::FnRetTy::Return(t) => Some(t.into()), clean::FnRetTy::Return(t) => Some(t.into()),
clean::FnRetTy::DefaultReturn => None, clean::FnRetTy::DefaultReturn => None,

View file

@ -753,11 +753,14 @@ fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> Fx
/// ///
/// These are common and we should just resolve to the trait in that case. /// These are common and we should just resolve to the trait in that case.
fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool { fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
matches!(*ns, PerNS { matches!(
*ns,
PerNS {
type_ns: Ok((Res::Def(DefKind::Trait, _), _)), type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)), macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
.. ..
}) }
)
} }
impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> { impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {

View file

@ -58,7 +58,8 @@ impl crate::doctest::Tester for Tests {
} }
crate fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool { crate fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool {
if matches!(item.kind, if matches!(
item.kind,
clean::StructFieldItem(_) clean::StructFieldItem(_)
| clean::VariantItem(_) | clean::VariantItem(_)
| clean::AssocConstItem(_, _) | clean::AssocConstItem(_, _)