Skip to content

Commit

Permalink
rustdoc: Introduce new DynTrait type for better representation of t…
Browse files Browse the repository at this point in the history
…rait objects
  • Loading branch information
Stupremee committed Jun 19, 2021
1 parent 1f65f56 commit 4ea2748
Show file tree
Hide file tree
Showing 9 changed files with 117 additions and 116 deletions.
10 changes: 1 addition & 9 deletions src/librustdoc/clean/auto_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,12 +353,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
let (poly_trait, output) =
(data.0.as_ref().expect("as_ref failed").clone(), data.1.as_ref().cloned());
let new_ty = match poly_trait.trait_ {
Type::ResolvedPath {
ref path,
ref param_names,
ref did,
ref is_generic,
} => {
Type::ResolvedPath { ref path, ref did, ref is_generic } => {
let mut new_path = path.clone();
let last_segment =
new_path.segments.pop().expect("segments were empty");
Expand Down Expand Up @@ -395,7 +390,6 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {

Type::ResolvedPath {
path: new_path,
param_names: param_names.clone(),
did: *did,
is_generic: *is_generic,
}
Expand Down Expand Up @@ -570,7 +564,6 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
match **trait_ {
Type::ResolvedPath {
path: ref trait_path,
ref param_names,
ref did,
ref is_generic,
} => {
Expand Down Expand Up @@ -617,7 +610,6 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
PolyTrait {
trait_: Type::ResolvedPath {
path: new_trait_path,
param_names: param_names.clone(),
did: *did,
is_generic: *is_generic,
},
Expand Down
84 changes: 26 additions & 58 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ impl Clean<Type> for (ty::TraitRef<'_>, &[TypeBinding]) {

debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs);

ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false }
ResolvedPath { path, did: trait_ref.def_id, is_generic: false }
}
}

Expand Down Expand Up @@ -1378,30 +1378,9 @@ impl Clean<Type> for hir::Ty<'_> {
}
TyKind::Path(_) => clean_qpath(&self, cx),
TyKind::TraitObject(ref bounds, ref lifetime, _) => {
let cleaned = bounds[0].clean(cx);
match cleaned.trait_ {
ResolvedPath { path, param_names: None, did, is_generic, .. } => {
let mut bounds: Vec<self::GenericBound> = bounds[1..]
.iter()
.map(|bound| {
self::GenericBound::TraitBound(
bound.clean(cx),
hir::TraitBoundModifier::None,
)
})
.collect();
if !lifetime.is_elided() {
bounds.push(self::GenericBound::Outlives(lifetime.clean(cx)));
}
ResolvedPath {
path,
param_names: Some((bounds, cleaned.generic_params)),
did,
is_generic,
}
}
_ => Infer, // shouldn't happen
}
let bounds = bounds.iter().map(|bound| bound.clean(cx)).collect();
let lifetime = if !lifetime.is_elided() { Some(lifetime.clean(cx)) } else { None };
DynTrait(bounds, lifetime)
}
TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
TyKind::Infer | TyKind::Err => Infer,
Expand Down Expand Up @@ -1484,7 +1463,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
};
inline::record_extern_fqn(cx, did, kind);
let path = external_path(cx, cx.tcx.item_name(did), None, false, vec![], substs);
ResolvedPath { path, param_names: None, did, is_generic: false }
ResolvedPath { path, did, is_generic: false }
}
ty::Foreign(did) => {
inline::record_extern_fqn(cx, did, ItemType::ForeignType);
Expand All @@ -1496,7 +1475,7 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {
vec![],
InternalSubsts::empty(),
);
ResolvedPath { path, param_names: None, did, is_generic: false }
ResolvedPath { path, did, is_generic: false }
}
ty::Dynamic(ref obj, ref reg) => {
// HACK: pick the first `did` as the `did` of the trait object. Someone
Expand All @@ -1514,28 +1493,19 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {

inline::record_extern_fqn(cx, did, ItemType::Trait);

let mut param_names = vec![];
if let Some(b) = reg.clean(cx) {
param_names.push(GenericBound::Outlives(b));
}
let lifetime = reg.clean(cx);
let mut bounds = vec![];

for did in dids {
let empty = cx.tcx.intern_substs(&[]);
let path =
external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
inline::record_extern_fqn(cx, did, ItemType::Trait);
let bound = GenericBound::TraitBound(
PolyTrait {
trait_: ResolvedPath {
path,
param_names: None,
did,
is_generic: false,
},
generic_params: Vec::new(),
},
hir::TraitBoundModifier::None,
);
param_names.push(bound);
let bound = PolyTrait {
trait_: ResolvedPath { path, did, is_generic: false },
generic_params: Vec::new(),
};
bounds.push(bound);
}

let mut bindings = vec![];
Expand All @@ -1548,12 +1518,15 @@ impl<'tcx> Clean<Type> for Ty<'tcx> {

let path =
external_path(cx, cx.tcx.item_name(did), Some(did), false, bindings, substs);
ResolvedPath {
path,
param_names: Some((param_names, vec![])),
did,
is_generic: false,
}
bounds.insert(
0,
PolyTrait {
trait_: ResolvedPath { path, did, is_generic: false },
generic_params: Vec::new(),
},
);

DynTrait(bounds, lifetime)
}
ty::Tuple(ref t) => {
Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx))
Expand Down Expand Up @@ -2257,14 +2230,9 @@ impl From<GenericBound> for SimpleBound {
match bound.clone() {
GenericBound::Outlives(l) => SimpleBound::Outlives(l),
GenericBound::TraitBound(t, mod_) => match t.trait_ {
Type::ResolvedPath { path, param_names, .. } => SimpleBound::TraitBound(
path.segments,
param_names.map_or_else(Vec::new, |(v, _)| {
v.iter().map(|p| SimpleBound::from(p.clone())).collect()
}),
t.generic_params,
mod_,
),
Type::ResolvedPath { path, .. } => {
SimpleBound::TraitBound(path.segments, Vec::new(), t.generic_params, mod_)
}
_ => panic!("Unexpected bound {:?}", bound),
},
}
Expand Down
8 changes: 4 additions & 4 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,7 +1141,7 @@ impl GenericBound {
inline::record_extern_fqn(cx, did, ItemType::Trait);
GenericBound::TraitBound(
PolyTrait {
trait_: ResolvedPath { path, param_names: None, did, is_generic: false },
trait_: ResolvedPath { path, did, is_generic: false },
generic_params: Vec::new(),
},
hir::TraitBoundModifier::Maybe,
Expand Down Expand Up @@ -1407,13 +1407,12 @@ crate enum Type {
/// Structs/enums/traits (most that would be an `hir::TyKind::Path`).
ResolvedPath {
path: Path,
/// If `param_names` is `Some`, this path is a trait object and the Vecs repsresent
/// `(generic bounds, generic parameters)`
param_names: Option<(Vec<GenericBound>, Vec<GenericParamDef>)>,
did: DefId,
/// `true` if is a `T::Name` path for associated types.
is_generic: bool,
},
/// `dyn for<'a> Trait<'a> + Send + 'static`
DynTrait(Vec<PolyTrait>, Option<Lifetime>),
/// For parameterized types, so the consumer of the JSON don't go
/// looking for types which don't exist anywhere.
Generic(Symbol),
Expand Down Expand Up @@ -1600,6 +1599,7 @@ impl Type {
fn inner_def_id(&self, cache: Option<&Cache>) -> Option<DefId> {
let t: PrimitiveType = match *self {
ResolvedPath { did, .. } => return Some(did.into()),
DynTrait(ref bounds, _) => return bounds[0].trait_.inner_def_id(cache),
Primitive(p) => return cache.and_then(|c| c.primitive_locations.get(&p).cloned()),
BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference,
BorrowedRef { ref type_, .. } => return type_.inner_def_id(cache),
Expand Down
18 changes: 14 additions & 4 deletions src/librustdoc/clean/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::clean::auto_trait::AutoTraitFinder;
use crate::clean::blanket_impl::BlanketImplFinder;
use crate::clean::{
inline, Clean, Crate, Generic, GenericArg, GenericArgs, ImportSource, Item, ItemKind, Lifetime,
Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Type, TypeBinding,
Path, PathSegment, PolyTrait, Primitive, PrimitiveType, ResolvedPath, Type, TypeBinding,
};
use crate::core::DocContext;
use crate::formats::item_type::ItemType;
Expand Down Expand Up @@ -163,8 +163,18 @@ pub(super) fn external_path(

crate fn strip_type(ty: Type) -> Type {
match ty {
Type::ResolvedPath { path, param_names, did, is_generic } => {
Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
Type::ResolvedPath { path, did, is_generic } => {
Type::ResolvedPath { path: strip_path(&path), did, is_generic }
}
Type::DynTrait(mut bounds, lt) => {
let first = bounds.remove(0);
let stripped_trait = strip_type(first.trait_);

bounds.insert(
0,
PolyTrait { trait_: stripped_trait, generic_params: first.generic_params },
);
Type::DynTrait(bounds, lt)
}
Type::Tuple(inner_tys) => {
Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
Expand Down Expand Up @@ -431,7 +441,7 @@ crate fn resolve_type(cx: &mut DocContext<'_>, path: Path, id: hir::HirId) -> Ty
_ => false,
};
let did = register_res(cx, path.res);
ResolvedPath { path, param_names: None, did, is_generic }
ResolvedPath { path, did, is_generic }
}

crate fn get_auto_trait_and_blanket_impls(
Expand Down
15 changes: 15 additions & 0 deletions src/librustdoc/formats/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,15 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
self.cache.parent_stack.push(did);
true
}
clean::DynTrait(ref bounds, _)
| clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
if let Some(did) = bounds[0].trait_.def_id() {
self.cache.parent_stack.push(did);
true
} else {
false
}
}
ref t => {
let prim_did = t
.primitive_type()
Expand Down Expand Up @@ -432,6 +441,12 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> {
| clean::BorrowedRef { type_: box clean::ResolvedPath { did, .. }, .. } => {
dids.insert(did);
}
clean::DynTrait(ref bounds, _)
| clean::BorrowedRef { type_: box clean::DynTrait(ref bounds, _), .. } => {
if let Some(did) = bounds[0].trait_.def_id() {
dids.insert(did);
}
}
ref t => {
let did = t
.primitive_type()
Expand Down
60 changes: 23 additions & 37 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,18 +646,24 @@ fn primitive_link(

/// Helper to render type parameters
fn tybounds<'a, 'tcx: 'a>(
param_names: Option<&'a Vec<clean::GenericBound>>,
bounds: &'a Vec<clean::PolyTrait>,
lt: &'a Option<clean::Lifetime>,
cx: &'a Context<'tcx>,
) -> impl fmt::Display + 'a + Captures<'tcx> {
display_fn(move |f| match param_names {
Some(params) => {
for param in params {
display_fn(move |f| {
for (i, bound) in bounds.iter().enumerate() {
if i > 0 {
write!(f, " + ")?;
fmt::Display::fmt(&param.print(cx), f)?;
}
Ok(())

fmt::Display::fmt(&bound.print(cx), f)?;
}
None => Ok(()),

if let Some(lt) = lt {
write!(f, " + ")?;
fmt::Display::fmt(&lt.print(), f)?;
}
Ok(())
})
}

Expand Down Expand Up @@ -694,32 +700,13 @@ fn fmt_type<'cx>(

match *t {
clean::Generic(name) => write!(f, "{}", name),
clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
let generic_params = param_names.as_ref().map(|(_, x)| x);
let param_names = param_names.as_ref().map(|(x, _)| x);

if let Some(generic_params) = generic_params {
f.write_str("dyn ")?;

if !generic_params.is_empty() {
if f.alternate() {
write!(
f,
"for<{:#}> ",
comma_sep(generic_params.iter().map(|g| g.print(cx)))
)?;
} else {
write!(
f,
"for&lt;{}&gt; ",
comma_sep(generic_params.iter().map(|g| g.print(cx)))
)?;
}
}
}
clean::ResolvedPath { did, ref path, is_generic } => {
// Paths like `T::Output` and `Self::Output` should be rendered with all segments.
resolved_path(f, did, path, is_generic, use_absolute, cx)?;
fmt::Display::fmt(&tybounds(param_names, cx), f)
resolved_path(f, did, path, is_generic, use_absolute, cx)
}
clean::DynTrait(ref bounds, ref lt) => {
f.write_str("dyn ")?;
fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
}
clean::Infer => write!(f, "_"),
clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
Expand Down Expand Up @@ -854,7 +841,9 @@ fn fmt_type<'cx>(
}
}
}
clean::ResolvedPath { param_names: Some((ref v, _)), .. } if !v.is_empty() => {
clean::DynTrait(ref bounds, ref trait_lt)
if bounds.len() > 1 || trait_lt.is_some() =>
{
write!(f, "{}{}{}(", amp, lt, m)?;
fmt_type(&ty, f, use_absolute, cx)?;
write!(f, ")")
Expand Down Expand Up @@ -915,7 +904,7 @@ fn fmt_type<'cx>(
// the ugliness comes from inlining across crates where
// everything comes in as a fully resolved QPath (hard to
// look at).
box clean::ResolvedPath { did, ref param_names, .. } => {
box clean::ResolvedPath { did, .. } => {
match href(did.into(), cx) {
Some((ref url, _, ref path)) if !f.alternate() => {
write!(
Expand All @@ -930,9 +919,6 @@ fn fmt_type<'cx>(
}
_ => write!(f, "{}", name)?,
}

// FIXME: `param_names` are not rendered, and this seems bad?
drop(param_names);
Ok(())
}
_ => write!(f, "{}", name),
Expand Down
1 change: 1 addition & 0 deletions src/librustdoc/html/render/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option
});
Some(path_segment.name)
}
clean::DynTrait(ref bounds, _) => get_index_type_name(&bounds[0].trait_, accept_generic),
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),
Expand Down
Loading

0 comments on commit 4ea2748

Please sign in to comment.