1
Fork 0

Rollup merge of #88810 - camelid:cleanup-pt1, r=jyn514

rustdoc: Cleanup `clean` part 1

Split out from #88379.

These commits are completely independent of each other, and each is a fairly
small change (the last few are new commits; they are not from #88379):

- Remove unnecessary `Cache.*_did` fields
- rustdoc: Get symbol for `TyParam` directly
- Create a valid `Res` in `external_path()`
- Remove unused `hir_id` parameter from `resolve_type`
- Fix redundant arguments in `external_path()`
- Remove unnecessary `is_trait` argument
- rustdoc: Cleanup a pattern match in `external_generic_args()`

r? ``@jyn514``
This commit is contained in:
Manish Goregaokar 2021-09-12 03:44:58 -07:00 committed by GitHub
commit b3af37ac7b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 59 additions and 84 deletions

View file

@ -164,14 +164,7 @@ impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {
); );
} }
inline::record_extern_fqn(cx, trait_ref.def_id, kind); inline::record_extern_fqn(cx, trait_ref.def_id, kind);
let path = external_path( let path = external_path(cx, trait_ref.def_id, true, bounds.to_vec(), trait_ref.substs);
cx,
cx.tcx.item_name(trait_ref.def_id),
Some(trait_ref.def_id),
true,
bounds.to_vec(),
trait_ref.substs,
);
debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs); debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);
@ -906,7 +899,7 @@ impl Clean<bool> for hir::IsAuto {
impl Clean<Type> for hir::TraitRef<'_> { impl Clean<Type> for hir::TraitRef<'_> {
fn clean(&self, cx: &mut DocContext<'_>) -> Type { fn clean(&self, cx: &mut DocContext<'_>) -> Type {
let path = self.path.clean(cx); let path = self.path.clean(cx);
resolve_type(cx, path, self.hir_ref_id) resolve_type(cx, path)
} }
} }
@ -1164,7 +1157,7 @@ impl Clean<Item> for ty::AssocItem {
fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type { fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
use rustc_hir::GenericParamCount; use rustc_hir::GenericParamCount;
let hir::Ty { hir_id, span, ref kind } = *hir_ty; let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
let qpath = match kind { let qpath = match kind {
hir::TyKind::Path(qpath) => qpath, hir::TyKind::Path(qpath) => qpath,
_ => unreachable!(), _ => unreachable!(),
@ -1271,7 +1264,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx)); return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
} }
let path = path.clean(cx); let path = path.clean(cx);
resolve_type(cx, path, hir_id) resolve_type(cx, path)
} }
hir::QPath::Resolved(Some(ref qself), ref p) => { hir::QPath::Resolved(Some(ref qself), ref p) => {
// Try to normalize `<X as Y>::T` to a type // Try to normalize `<X as Y>::T` to a type
@ -1292,7 +1285,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
name: p.segments.last().expect("segments were empty").ident.name, name: p.segments.last().expect("segments were empty").ident.name,
self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)), self_def_id: Some(DefId::local(qself.hir_id.owner.local_def_index)),
self_type: Box::new(qself.clean(cx)), self_type: Box::new(qself.clean(cx)),
trait_: Box::new(resolve_type(cx, trait_path, hir_id)), trait_: Box::new(resolve_type(cx, trait_path)),
} }
} }
hir::QPath::TypeRelative(ref qself, ref segment) => { hir::QPath::TypeRelative(ref qself, ref segment) => {
@ -1308,7 +1301,7 @@ fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
name: segment.ident.name, name: segment.ident.name,
self_def_id: res.opt_def_id(), self_def_id: res.opt_def_id(),
self_type: Box::new(qself.clean(cx)), self_type: Box::new(qself.clean(cx)),
trait_: Box::new(resolve_type(cx, trait_path, hir_id)), trait_: Box::new(resolve_type(cx, trait_path)),
} }
} }
hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"), hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
@ -1448,19 +1441,12 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
AdtKind::Enum => ItemType::Enum, AdtKind::Enum => ItemType::Enum,
}; };
inline::record_extern_fqn(cx, did, kind); inline::record_extern_fqn(cx, did, kind);
let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs); let path = external_path(cx, did, false, vec![], substs);
ResolvedPath { path, did, is_generic: false } ResolvedPath { path, did, is_generic: false }
} }
ty::Foreign(did) => { ty::Foreign(did) => {
inline::record_extern_fqn(cx, did, ItemType::ForeignType); inline::record_extern_fqn(cx, did, ItemType::ForeignType);
let path = external_path( let path = external_path(cx, did, false, vec![], InternalSubsts::empty());
cx,
cx.tcx.item_name(did),
None,
false,
vec![],
InternalSubsts::empty(),
);
ResolvedPath { path, did, is_generic: false } ResolvedPath { path, did, is_generic: false }
} }
ty::Dynamic(ref obj, ref reg) => { ty::Dynamic(ref obj, ref reg) => {
@ -1484,8 +1470,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
for did in dids { for did in dids {
let empty = cx.tcx.intern_substs(&[]); let empty = cx.tcx.intern_substs(&[]);
let path = let path = external_path(cx, did, false, vec![], empty);
external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
inline::record_extern_fqn(cx, did, ItemType::Trait); inline::record_extern_fqn(cx, did, ItemType::Trait);
let bound = PolyTrait { let bound = PolyTrait {
trait_: ResolvedPath { path, did, is_generic: false }, trait_: ResolvedPath { path, did, is_generic: false },
@ -1502,8 +1487,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
}); });
} }
let path = let path = external_path(cx, did, false, bindings, substs);
external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
bounds.insert( bounds.insert(
0, 0,
PolyTrait { PolyTrait {

View file

@ -1111,7 +1111,7 @@ impl GenericBound {
crate fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound { crate fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound {
let did = cx.tcx.require_lang_item(LangItem::Sized, None); let did = cx.tcx.require_lang_item(LangItem::Sized, None);
let empty = cx.tcx.intern_substs(&[]); let empty = cx.tcx.intern_substs(&[]);
let path = external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty); let path = external_path(cx, did, false, vec![], empty);
inline::record_extern_fqn(cx, did, ItemType::Trait); inline::record_extern_fqn(cx, did, ItemType::Trait);
GenericBound::TraitBound( GenericBound::TraitBound(
PolyTrait { PolyTrait {

View file

@ -29,10 +29,6 @@ crate fn krate(cx: &mut DocContext<'_>) -> Crate {
let krate = cx.tcx.hir().krate(); let krate = cx.tcx.hir().krate();
let module = crate::visit_ast::RustdocVisitor::new(cx).visit(krate); let module = crate::visit_ast::RustdocVisitor::new(cx).visit(krate);
cx.cache.deref_trait_did = cx.tcx.lang_items().deref_trait();
cx.cache.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
cx.cache.owned_box_did = cx.tcx.lang_items().owned_box();
let mut externs = Vec::new(); let mut externs = Vec::new();
for &cnum in cx.tcx.crates(()).iter() { for &cnum in cx.tcx.crates(()).iter() {
externs.push(ExternalCrate { crate_num: cnum }); externs.push(ExternalCrate { crate_num: cnum });
@ -97,7 +93,7 @@ crate fn krate(cx: &mut DocContext<'_>) -> Crate {
fn external_generic_args( fn external_generic_args(
cx: &mut DocContext<'_>, cx: &mut DocContext<'_>,
trait_did: Option<DefId>, did: DefId,
has_self: bool, has_self: bool,
bindings: Vec<TypeBinding>, bindings: Vec<TypeBinding>,
substs: SubstsRef<'_>, substs: SubstsRef<'_>,
@ -125,42 +121,38 @@ fn external_generic_args(
}) })
.collect(); .collect();
match trait_did { if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() {
// Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C let inputs = match ty_kind.unwrap() {
Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => { ty::Tuple(tys) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
assert!(ty_kind.is_some()); _ => return GenericArgs::AngleBracketed { args, bindings },
let inputs = match ty_kind { };
Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(), let output = None;
_ => return GenericArgs::AngleBracketed { args, bindings }, // FIXME(#20299) return type comes from a projection now
}; // match types[1].kind {
let output = None; // ty::Tuple(ref v) if v.is_empty() => None, // -> ()
// FIXME(#20299) return type comes from a projection now // _ => Some(types[1].clean(cx))
// match types[1].kind { // };
// ty::Tuple(ref v) if v.is_empty() => None, // -> () GenericArgs::Parenthesized { inputs, output }
// _ => Some(types[1].clean(cx)) } else {
// }; GenericArgs::AngleBracketed { args, bindings }
GenericArgs::Parenthesized { inputs, output }
}
_ => GenericArgs::AngleBracketed { args, bindings },
} }
} }
// trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
// from Fn<(A, B,), C> to Fn(A, B) -> C
pub(super) fn external_path( pub(super) fn external_path(
cx: &mut DocContext<'_>, cx: &mut DocContext<'_>,
name: Symbol, did: DefId,
trait_did: Option<DefId>,
has_self: bool, has_self: bool,
bindings: Vec<TypeBinding>, bindings: Vec<TypeBinding>,
substs: SubstsRef<'_>, substs: SubstsRef<'_>,
) -> Path { ) -> Path {
let def_kind = cx.tcx.def_kind(did);
let name = cx.tcx.item_name(did);
Path { Path {
global: false, global: false,
res: Res::Err, res: Res::Def(def_kind, did),
segments: vec![PathSegment { segments: vec![PathSegment {
name, name,
args: external_generic_args(cx, trait_did, has_self, bindings, substs), args: external_generic_args(cx, did, has_self, bindings, substs),
}], }],
} }
} }
@ -409,8 +401,8 @@ crate fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {
} }
/// Given a type Path, resolve it to a Type using the TyCtxt /// Given a type Path, resolve it to a Type using the TyCtxt
crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Type { crate fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
debug!("resolve_type({:?},{:?})", path, id); debug!("resolve_type({:?})", path);
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)),
@ -418,7 +410,7 @@ crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Ty
return Generic(kw::SelfUpper); return Generic(kw::SelfUpper);
} }
Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
return Generic(Symbol::intern(&path.whole_name())); return Generic(path.segments[0].name);
} }
Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true, Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
_ => false, _ => false,

View file

@ -98,9 +98,6 @@ crate struct Cache {
stripped_mod: bool, stripped_mod: bool,
crate search_index: Vec<IndexItem>, crate search_index: Vec<IndexItem>,
crate deref_trait_did: Option<DefId>,
crate deref_mut_trait_did: Option<DefId>,
crate owned_box_did: Option<DefId>,
// In rare case where a structure is defined in one module but implemented // In rare case where a structure is defined in one module but implemented
// in another, if the implementing module is parsed before defining module, // in another, if the implementing module is parsed before defining module,

View file

@ -51,6 +51,7 @@ use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::Mutability; use rustc_hir::Mutability;
use rustc_middle::middle::stability; use rustc_middle::middle::stability;
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::symbol::{kw, sym, Symbol};
use serde::ser::SerializeSeq; use serde::ser::SerializeSeq;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
@ -1067,13 +1068,13 @@ fn render_assoc_items(
return; return;
} }
if !traits.is_empty() { if !traits.is_empty() {
let deref_impl = traits let deref_impl = traits.iter().find(|t| {
.iter() t.inner_impl().trait_.def_id_full(cache) == cx.tcx().lang_items().deref_trait()
.find(|t| t.inner_impl().trait_.def_id_full(cache) == cache.deref_trait_did); });
if let Some(impl_) = deref_impl { if let Some(impl_) = deref_impl {
let has_deref_mut = traits let has_deref_mut = traits.iter().any(|t| {
.iter() t.inner_impl().trait_.def_id_full(cache) == cx.tcx().lang_items().deref_mut_trait()
.any(|t| t.inner_impl().trait_.def_id_full(cache) == cache.deref_mut_trait_did); });
render_deref_methods(w, cx, impl_, containing_item, has_deref_mut); render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
} }
let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
@ -1163,7 +1164,7 @@ fn render_deref_methods(
} }
} }
fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool { fn should_render_item(item: &clean::Item, deref_mut_: bool, tcx: TyCtxt<'_>) -> bool {
let self_type_opt = match *item.kind { let self_type_opt = match *item.kind {
clean::MethodItem(ref method, _) => method.decl.self_type(), clean::MethodItem(ref method, _) => method.decl.self_type(),
clean::TyMethodItem(ref method) => method.decl.self_type(), clean::TyMethodItem(ref method) => method.decl.self_type(),
@ -1177,7 +1178,7 @@ fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bo
(mutability == Mutability::Mut, false, false) (mutability == Mutability::Mut, false, false)
} }
SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => { SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
(false, Some(did) == cache.owned_box_did, false) (false, Some(did) == tcx.lang_items().owned_box(), false)
} }
SelfTy::SelfValue => (false, false, true), SelfTy::SelfValue => (false, false, true),
_ => (false, false, false), _ => (false, false, false),
@ -1300,7 +1301,7 @@ fn render_impl(
&& match render_mode { && match render_mode {
RenderMode::Normal => true, RenderMode::Normal => true,
RenderMode::ForDeref { mut_: deref_mut_ } => { RenderMode::ForDeref { mut_: deref_mut_ } => {
should_render_item(&item, deref_mut_, cx.cache()) should_render_item(&item, deref_mut_, cx.tcx())
} }
}; };
@ -1798,13 +1799,13 @@ fn get_methods(
for_deref: bool, for_deref: bool,
used_links: &mut FxHashSet<String>, used_links: &mut FxHashSet<String>,
deref_mut: bool, deref_mut: bool,
cache: &Cache, tcx: TyCtxt<'_>,
) -> Vec<String> { ) -> Vec<String> {
i.items i.items
.iter() .iter()
.filter_map(|item| match item.name { .filter_map(|item| match item.name {
Some(ref name) if !name.is_empty() && item.is_method() => { Some(ref name) if !name.is_empty() && item.is_method() => {
if !for_deref || should_render_item(item, deref_mut, cache) { if !for_deref || should_render_item(item, deref_mut, tcx) {
Some(format!( Some(format!(
"<a href=\"#{}\">{}</a>", "<a href=\"#{}\">{}</a>",
get_next_url(used_links, format!("method.{}", name)), get_next_url(used_links, format!("method.{}", name)),
@ -1866,7 +1867,9 @@ fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
let mut ret = v let mut ret = v
.iter() .iter()
.filter(|i| i.inner_impl().trait_.is_none()) .filter(|i| i.inner_impl().trait_.is_none())
.flat_map(move |i| get_methods(i.inner_impl(), false, used_links_bor, false, cache)) .flat_map(move |i| {
get_methods(i.inner_impl(), false, used_links_bor, false, cx.tcx())
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if !ret.is_empty() { if !ret.is_empty() {
// We want links' order to be reproducible so we don't use unstable sort. // We want links' order to be reproducible so we don't use unstable sort.
@ -1884,11 +1887,9 @@ fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
} }
if v.iter().any(|i| i.inner_impl().trait_.is_some()) { if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
if let Some(impl_) = v if let Some(impl_) = v.iter().filter(|i| i.inner_impl().trait_.is_some()).find(|i| {
.iter() i.inner_impl().trait_.def_id_full(cache) == cx.tcx().lang_items().deref_trait()
.filter(|i| i.inner_impl().trait_.is_some()) }) {
.find(|i| i.inner_impl().trait_.def_id_full(cache) == cache.deref_trait_did)
{
sidebar_deref_methods(cx, out, impl_, v); sidebar_deref_methods(cx, out, impl_, v);
} }
@ -1986,10 +1987,9 @@ fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &V
} }
} }
} }
let deref_mut = v let deref_mut = v.iter().filter(|i| i.inner_impl().trait_.is_some()).any(|i| {
.iter() i.inner_impl().trait_.def_id_full(c) == cx.tcx().lang_items().deref_mut_trait()
.filter(|i| i.inner_impl().trait_.is_some()) });
.any(|i| i.inner_impl().trait_.def_id_full(c) == c.deref_mut_trait_did);
let inner_impl = target let inner_impl = target
.def_id_full(c) .def_id_full(c)
.or_else(|| { .or_else(|| {
@ -2002,7 +2002,9 @@ fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &V
let mut ret = impls let mut ret = impls
.iter() .iter()
.filter(|i| i.inner_impl().trait_.is_none()) .filter(|i| i.inner_impl().trait_.is_none())
.flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c)) .flat_map(|i| {
get_methods(i.inner_impl(), true, &mut used_links, deref_mut, cx.tcx())
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if !ret.is_empty() { if !ret.is_empty() {
write!( write!(

View file

@ -10,7 +10,7 @@ where
// @has no_redundancy/struct.Outer.html // @has no_redundancy/struct.Outer.html
// @has - '//*[@id="synthetic-implementations-list"]//*[@class="impl has-srclink"]//h3[@class="code-header in-band"]' \ // @has - '//*[@id="synthetic-implementations-list"]//*[@class="impl has-srclink"]//h3[@class="code-header in-band"]' \
// "impl<T> Send for Outer<T> where T: Copy + Send" // "impl<T> Send for Outer<T> where T: Send + Copy"
pub struct Outer<T> { pub struct Outer<T> {
inner_field: Inner<T>, inner_field: Inner<T>,
} }