Skip to content

Commit 74e97f3

Browse files
Add trait alias support in rustdoc
1 parent 618f5a0 commit 74e97f3

File tree

7 files changed

+149
-46
lines changed

7 files changed

+149
-46
lines changed

src/librustdoc/clean/mod.rs

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,7 @@ pub enum ItemEnum {
517517
StaticItem(Static),
518518
ConstantItem(Constant),
519519
TraitItem(Trait),
520+
TraitAliasItem(TraitAlias),
520521
ImplItem(Impl),
521522
/// A method signature only. Used for required methods in traits (ie,
522523
/// non-default-methods).
@@ -554,6 +555,7 @@ impl ItemEnum {
554555
ItemEnum::TyMethodItem(ref i) => &i.generics,
555556
ItemEnum::MethodItem(ref i) => &i.generics,
556557
ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
558+
ItemEnum::TraitAliasItem(ref ta) => &ta.generics,
557559
_ => return None,
558560
})
559561
}
@@ -603,6 +605,7 @@ impl Clean<Item> for doctree::Module {
603605
items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
604606
items.extend(self.macros.iter().map(|x| x.clean(cx)));
605607
items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
608+
items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
606609

607610
// determine if we should display the inner contents or
608611
// the outer `mod` item for the source code.
@@ -1885,13 +1888,41 @@ impl Clean<Item> for doctree::Trait {
18851888
items: self.items.clean(cx),
18861889
generics: self.generics.clean(cx),
18871890
bounds: self.bounds.clean(cx),
1888-
is_spotlight: is_spotlight,
1891+
is_spotlight,
18891892
is_auto: self.is_auto.clean(cx),
18901893
}),
18911894
}
18921895
}
18931896
}
18941897

1898+
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1899+
pub struct TraitAlias {
1900+
pub generics: Generics,
1901+
pub bounds: Vec<GenericBound>,
1902+
pub is_spotlight: bool,
1903+
}
1904+
1905+
impl Clean<Item> for doctree::TraitAlias {
1906+
fn clean(&self, cx: &DocContext) -> Item {
1907+
let attrs = self.attrs.clean(cx);
1908+
let is_spotlight = attrs.has_doc_flag("spotlight");
1909+
Item {
1910+
name: Some(self.name.clean(cx)),
1911+
attrs,
1912+
source: self.whence.clean(cx),
1913+
def_id: cx.tcx.hir().local_def_id(self.id),
1914+
visibility: self.vis.clean(cx),
1915+
stability: self.stab.clean(cx),
1916+
deprecation: self.depr.clean(cx),
1917+
inner: TraitAliasItem(TraitAlias {
1918+
generics: self.generics.clean(cx),
1919+
bounds: self.bounds.clean(cx),
1920+
is_spotlight,
1921+
}),
1922+
}
1923+
}
1924+
}
1925+
18951926
impl Clean<bool> for hir::IsAuto {
18961927
fn clean(&self, _: &DocContext) -> bool {
18971928
match *self {
@@ -2223,6 +2254,7 @@ pub enum TypeKind {
22232254
Macro,
22242255
Attr,
22252256
Derive,
2257+
TraitAlias,
22262258
}
22272259

22282260
pub trait GetDefId {
@@ -3819,10 +3851,9 @@ pub fn register_def(cx: &DocContext, def: Def) -> DefId {
38193851
MacroKind::Derive => (i, TypeKind::Derive),
38203852
MacroKind::ProcMacroStub => unreachable!(),
38213853
},
3854+
Def::TraitAlias(i) => (i, TypeKind::TraitAlias),
38223855
Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
3823-
Def::SelfTy(_, Some(impl_def_id)) => {
3824-
return impl_def_id
3825-
}
3856+
Def::SelfTy(_, Some(impl_def_id)) => return impl_def_id,
38263857
_ => return def.def_id()
38273858
};
38283859
if did.is_local() { return did }

src/librustdoc/doctree.rs

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ pub struct Module {
3838
pub foreigns: Vec<hir::ForeignMod>,
3939
pub macros: Vec<Macro>,
4040
pub proc_macros: Vec<ProcMacro>,
41+
pub trait_aliases: Vec<TraitAlias>,
4142
pub is_crate: bool,
4243
}
4344

@@ -53,21 +54,22 @@ impl Module {
5354
where_inner: syntax_pos::DUMMY_SP,
5455
attrs : hir::HirVec::new(),
5556
extern_crates: Vec::new(),
56-
imports : Vec::new(),
57-
structs : Vec::new(),
58-
unions : Vec::new(),
59-
enums : Vec::new(),
60-
fns : Vec::new(),
61-
mods : Vec::new(),
62-
typedefs : Vec::new(),
63-
existentials: Vec::new(),
64-
statics : Vec::new(),
65-
constants : Vec::new(),
66-
traits : Vec::new(),
67-
impls : Vec::new(),
68-
foreigns : Vec::new(),
69-
macros : Vec::new(),
70-
proc_macros: Vec::new(),
57+
imports : Vec::new(),
58+
structs : Vec::new(),
59+
unions : Vec::new(),
60+
enums : Vec::new(),
61+
fns : Vec::new(),
62+
mods : Vec::new(),
63+
typedefs : Vec::new(),
64+
existentials: Vec::new(),
65+
statics : Vec::new(),
66+
constants : Vec::new(),
67+
traits : Vec::new(),
68+
impls : Vec::new(),
69+
foreigns : Vec::new(),
70+
macros : Vec::new(),
71+
proc_macros: Vec::new(),
72+
trait_aliases: Vec::new(),
7173
is_crate : false,
7274
}
7375
}
@@ -208,6 +210,18 @@ pub struct Trait {
208210
pub depr: Option<attr::Deprecation>,
209211
}
210212

213+
pub struct TraitAlias {
214+
pub name: Name,
215+
pub generics: hir::Generics,
216+
pub bounds: hir::HirVec<hir::GenericBound>,
217+
pub attrs: hir::HirVec<ast::Attribute>,
218+
pub id: ast::NodeId,
219+
pub whence: Span,
220+
pub vis: hir::Visibility,
221+
pub stab: Option<attr::Stability>,
222+
pub depr: Option<attr::Deprecation>,
223+
}
224+
211225
#[derive(Debug)]
212226
pub struct Impl {
213227
pub unsafety: hir::Unsafety,

src/librustdoc/html/item_type.rs

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ pub enum ItemType {
4242
Existential = 22,
4343
ProcAttribute = 23,
4444
ProcDerive = 24,
45+
TraitAlias = 25,
4546
}
4647

4748

@@ -86,6 +87,7 @@ impl<'a> From<&'a clean::Item> for ItemType {
8687
clean::AssociatedTypeItem(..) => ItemType::AssociatedType,
8788
clean::ForeignTypeItem => ItemType::ForeignType,
8889
clean::KeywordItem(..) => ItemType::Keyword,
90+
clean::TraitAliasItem(..) => ItemType::TraitAlias,
8991
clean::ProcMacroItem(ref mac) => match mac.kind {
9092
MacroKind::Bang => ItemType::Macro,
9193
MacroKind::Attr => ItemType::ProcAttribute,
@@ -100,20 +102,21 @@ impl<'a> From<&'a clean::Item> for ItemType {
100102
impl From<clean::TypeKind> for ItemType {
101103
fn from(kind: clean::TypeKind) -> ItemType {
102104
match kind {
103-
clean::TypeKind::Struct => ItemType::Struct,
104-
clean::TypeKind::Union => ItemType::Union,
105-
clean::TypeKind::Enum => ItemType::Enum,
106-
clean::TypeKind::Function => ItemType::Function,
107-
clean::TypeKind::Trait => ItemType::Trait,
108-
clean::TypeKind::Module => ItemType::Module,
109-
clean::TypeKind::Static => ItemType::Static,
110-
clean::TypeKind::Const => ItemType::Constant,
111-
clean::TypeKind::Variant => ItemType::Variant,
112-
clean::TypeKind::Typedef => ItemType::Typedef,
113-
clean::TypeKind::Foreign => ItemType::ForeignType,
114-
clean::TypeKind::Macro => ItemType::Macro,
115-
clean::TypeKind::Attr => ItemType::ProcAttribute,
116-
clean::TypeKind::Derive => ItemType::ProcDerive,
105+
clean::TypeKind::Struct => ItemType::Struct,
106+
clean::TypeKind::Union => ItemType::Union,
107+
clean::TypeKind::Enum => ItemType::Enum,
108+
clean::TypeKind::Function => ItemType::Function,
109+
clean::TypeKind::Trait => ItemType::Trait,
110+
clean::TypeKind::Module => ItemType::Module,
111+
clean::TypeKind::Static => ItemType::Static,
112+
clean::TypeKind::Const => ItemType::Constant,
113+
clean::TypeKind::Variant => ItemType::Variant,
114+
clean::TypeKind::Typedef => ItemType::Typedef,
115+
clean::TypeKind::Foreign => ItemType::ForeignType,
116+
clean::TypeKind::Macro => ItemType::Macro,
117+
clean::TypeKind::Attr => ItemType::ProcAttribute,
118+
clean::TypeKind::Derive => ItemType::ProcDerive,
119+
clean::TypeKind::TraitAlias => ItemType::TraitAlias,
117120
}
118121
}
119122
}
@@ -146,6 +149,7 @@ impl ItemType {
146149
ItemType::Existential => "existential",
147150
ItemType::ProcAttribute => "attr",
148151
ItemType::ProcDerive => "derive",
152+
ItemType::TraitAlias => "traitalias",
149153
}
150154
}
151155

@@ -160,6 +164,7 @@ impl ItemType {
160164
ItemType::Primitive |
161165
ItemType::AssociatedType |
162166
ItemType::Existential |
167+
ItemType::TraitAlias |
163168
ItemType::ForeignType => NameSpace::Type,
164169

165170
ItemType::ExternCrate |

src/librustdoc/html/render.rs

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1836,6 +1836,7 @@ struct AllTypes {
18361836
keywords: FxHashSet<ItemEntry>,
18371837
attributes: FxHashSet<ItemEntry>,
18381838
derives: FxHashSet<ItemEntry>,
1839+
trait_aliases: FxHashSet<ItemEntry>,
18391840
}
18401841

18411842
impl AllTypes {
@@ -1856,6 +1857,7 @@ impl AllTypes {
18561857
keywords: new_set(100),
18571858
attributes: new_set(100),
18581859
derives: new_set(100),
1860+
trait_aliases: new_set(100),
18591861
}
18601862
}
18611863

@@ -1879,6 +1881,7 @@ impl AllTypes {
18791881
ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
18801882
ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
18811883
ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
1884+
ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
18821885
_ => true,
18831886
};
18841887
}
@@ -1922,6 +1925,7 @@ impl fmt::Display for AllTypes {
19221925
print_entries(f, &self.derives, "Derive Macros", "derives")?;
19231926
print_entries(f, &self.functions, "Functions", "functions")?;
19241927
print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
1928+
print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-alias")?;
19251929
print_entries(f, &self.existentials, "Existentials", "existentials")?;
19261930
print_entries(f, &self.statics, "Statics", "statics")?;
19271931
print_entries(f, &self.constants, "Constants", "constants")
@@ -2419,6 +2423,7 @@ impl<'a> fmt::Display for Item<'a> {
24192423
clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
24202424
clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
24212425
clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
2426+
clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
24222427
_ => {
24232428
// We don't generate pages for any other type.
24242429
unreachable!();
@@ -2457,6 +2462,7 @@ impl<'a> fmt::Display for Item<'a> {
24572462
clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
24582463
clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
24592464
clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
2465+
clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
24602466
_ => {
24612467
// We don't generate pages for any other type.
24622468
unreachable!();
@@ -3014,23 +3020,17 @@ fn render_impls(cx: &Context, w: &mut fmt::Formatter,
30143020
Ok(())
30153021
}
30163022

3017-
fn bounds(t_bounds: &[clean::GenericBound]) -> String {
3023+
fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
30183024
let mut bounds = String::new();
3019-
let mut bounds_plain = String::new();
30203025
if !t_bounds.is_empty() {
3021-
if !bounds.is_empty() {
3022-
bounds.push(' ');
3023-
bounds_plain.push(' ');
3026+
if !trait_alias {
3027+
bounds.push_str(": ");
30243028
}
3025-
bounds.push_str(": ");
3026-
bounds_plain.push_str(": ");
30273029
for (i, p) in t_bounds.iter().enumerate() {
30283030
if i > 0 {
30293031
bounds.push_str(" + ");
3030-
bounds_plain.push_str(" + ");
30313032
}
30323033
bounds.push_str(&(*p).to_string());
3033-
bounds_plain.push_str(&format!("{:#}", *p));
30343034
}
30353035
}
30363036
bounds
@@ -3050,7 +3050,7 @@ fn item_trait(
30503050
it: &clean::Item,
30513051
t: &clean::Trait,
30523052
) -> fmt::Result {
3053-
let bounds = bounds(&t.bounds);
3053+
let bounds = bounds(&t.bounds, false);
30543054
let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
30553055
let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
30563056
let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
@@ -4280,7 +4280,26 @@ fn item_existential(
42804280
it.name.as_ref().unwrap(),
42814281
t.generics,
42824282
where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4283-
bounds = bounds(&t.bounds))?;
4283+
bounds = bounds(&t.bounds, false))?;
4284+
4285+
document(w, cx, it)?;
4286+
4287+
// Render any items associated directly to this alias, as otherwise they
4288+
// won't be visible anywhere in the docs. It would be nice to also show
4289+
// associated items from the aliased type (see discussion in #32077), but
4290+
// we need #14072 to make sense of the generics.
4291+
render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
4292+
}
4293+
4294+
fn item_trait_alias(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
4295+
t: &clean::TraitAlias) -> fmt::Result {
4296+
write!(w, "<pre class='rust trait-alias'>")?;
4297+
render_attributes(w, it)?;
4298+
write!(w, "trait {}{}{} = {};</pre>",
4299+
it.name.as_ref().unwrap(),
4300+
t.generics,
4301+
WhereClause { gens: &t.generics, indent: 0, end_newline: true },
4302+
bounds(&t.bounds, true))?;
42844303

42854304
document(w, cx, it)?;
42864305

@@ -4844,6 +4863,7 @@ fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
48444863
ItemType::Existential => ("existentials", "Existentials"),
48454864
ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
48464865
ItemType::ProcDerive => ("derives", "Derive Macros"),
4866+
ItemType::TraitAlias => ("trait-alias", "Trait aliases"),
48474867
}
48484868
}
48494869

src/librustdoc/passes/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ impl<'a> fold::DocFolder for Stripper<'a> {
224224
| clean::ConstantItem(..)
225225
| clean::UnionItem(..)
226226
| clean::AssociatedConstItem(..)
227+
| clean::TraitAliasItem(..)
227228
| clean::ForeignTypeItem => {
228229
if i.def_id.is_local() {
229230
if !self.access_levels.is_exported(i.def_id) {

src/librustdoc/visit_ast.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,19 @@ impl<'a, 'tcx, 'rcx> RustdocVisitor<'a, 'tcx, 'rcx> {
547547
};
548548
om.traits.push(t);
549549
},
550-
hir::ItemKind::TraitAlias(..) => {
551-
unimplemented!("trait objects are not yet implemented")
550+
hir::ItemKind::TraitAlias(ref gen, ref b) => {
551+
let t = TraitAlias {
552+
name: ident.name,
553+
generics: gen.clone(),
554+
bounds: b.iter().cloned().collect(),
555+
id: item.id,
556+
attrs: item.attrs.clone(),
557+
whence: item.span,
558+
vis: item.vis.clone(),
559+
stab: self.stability(item.id),
560+
depr: self.deprecation(item.id),
561+
};
562+
om.trait_aliases.push(t);
552563
},
553564

554565
hir::ItemKind::Impl(unsafety,

src/test/rustdoc/trait_alias.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#![feature(trait_alias)]
2+
3+
#![crate_name = "foo"]
4+
5+
use std::fmt::Debug;
6+
7+
// @has foo/all.html '//a[@href="traitalias.CopyAlias.html"]' 'CopyAlias'
8+
// @has foo/all.html '//a[@href="traitalias.Alias2.html"]' 'Alias2'
9+
// @has foo/all.html '//a[@href="traitalias.Foo.html"]' 'Foo'
10+
11+
// @has foo/index.html '//h2[@id="trait-alias"]' 'Trait aliases'
12+
// @has foo/index.html '//a[@class="traitalias"]' 'CopyAlias'
13+
// @has foo/index.html '//a[@class="traitalias"]' 'Alias2'
14+
// @has foo/index.html '//a[@class="traitalias"]' 'Foo'
15+
16+
// @has foo/traitalias.CopyAlias.html '//section[@id="main"]/pre' 'trait CopyAlias = Copy;'
17+
pub trait CopyAlias = Copy;
18+
// @has foo/traitalias.Alias2.html '//section[@id="main"]/pre' 'trait Alias2 = Copy + Debug;'
19+
pub trait Alias2 = Copy + Debug;
20+
// @has foo/traitalias.Foo.html '//section[@id="main"]/pre' 'trait Foo<T> = Into<T> + Debug;'
21+
pub trait Foo<T> = Into<T> + Debug;

0 commit comments

Comments
 (0)