From 86ea93e83cc0d0dbe59067d0154c6e32e73f094a Mon Sep 17 00:00:00 2001 From: Oliver Middleton Date: Wed, 31 May 2017 18:02:35 +0100 Subject: [PATCH] rustdoc: Cleanup associated const value rendering Rather than (ab)using Debug for outputting the type in plain text use the alternate format parameter which already does exactly that. This fixes type parameters for example which would output raw HTML. Also cleans up adding parens around references to trait objects. --- src/librustdoc/clean/mod.rs | 2 +- src/librustdoc/html/format.rs | 206 ++++++++----------------------- src/librustdoc/html/render.rs | 4 +- src/test/rustdoc/assoc-consts.rs | 18 +++ 4 files changed, 74 insertions(+), 156 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 48d387f812d25..593477b066583 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1487,7 +1487,7 @@ pub struct PolyTrait { /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly /// it does not preserve mutability or boxes. -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)] pub enum Type { /// structs/enums/traits (most that'd be an hir::TyPath) ResolvedPath { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 19a863bdc62e1..6111ea073dd19 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -106,16 +106,6 @@ impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> { } } -impl<'a, T: fmt::Debug> fmt::Debug for CommaSep<'a, T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - for (i, item) in self.0.iter().enumerate() { - if i != 0 { write!(f, ", ")?; } - fmt::Debug::fmt(item, f)?; - } - Ok(()) - } -} - impl<'a> fmt::Display for TyParamBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &TyParamBounds(bounds) = self; @@ -469,8 +459,7 @@ pub fn href(did: DefId) -> Option<(String, ItemType, Vec)> { /// Used when rendering a `ResolvedPath` structure. This invokes the `path` /// rendering function with the necessary arguments for linking to a local path. fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, - print_all: bool, use_absolute: bool, is_not_debug: bool, - need_paren: bool) -> fmt::Result { + print_all: bool, use_absolute: bool) -> fmt::Result { let empty = clean::PathSegment { name: String::new(), params: clean::PathParameters::Parenthesized { @@ -499,13 +488,9 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, } else { root.push_str(&seg.name); root.push_str("/"); - if is_not_debug { - write!(w, "{}::", - root, - seg.name)?; - } else { - write!(w, "{}::", seg.name)?; - } + write!(w, "{}::", + root, + seg.name)?; } } } @@ -517,39 +502,21 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, } } if w.alternate() { - if is_not_debug { - write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?; - } else { - write!(w, "{:?}{}", HRef::new(did, &last.name), last.params)?; - } + write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?; } else { - if is_not_debug { - let path = if use_absolute { - match href(did) { - Some((_, _, fqp)) => format!("{}::{}", - fqp[..fqp.len()-1].join("::"), - HRef::new(did, fqp.last() - .unwrap_or(&String::new()))), - None => format!("{}", HRef::new(did, &last.name)), + let path = if use_absolute { + match href(did) { + Some((_, _, fqp)) => { + format!("{}::{}", + fqp[..fqp.len() - 1].join("::"), + HRef::new(did, fqp.last().unwrap_or(&String::new()))) } - } else { - format!("{}", HRef::new(did, &last.name)) - }; - write!(w, "{}{}{}", if need_paren { "(" } else { "" }, path, last.params)?; + None => format!("{}", HRef::new(did, &last.name)), + } } else { - let path = if use_absolute { - match href(did) { - Some((_, _, fqp)) => format!("{:?}::{:?}", - fqp[..fqp.len()-1].join("::"), - HRef::new(did, fqp.last() - .unwrap_or(&String::new()))), - None => format!("{:?}", HRef::new(did, &last.name)), - } - } else { - format!("{:?}", HRef::new(did, &last.name)) - }; - write!(w, "{}{}{}", if need_paren { "(" } else { "" }, path, last.params)?; - } + format!("{}", HRef::new(did, &last.name)) + }; + write!(w, "{}{}", path, last.params)?; } Ok(()) } @@ -600,17 +567,13 @@ fn primitive_link(f: &mut fmt::Formatter, /// Helper to render type parameters fn tybounds(w: &mut fmt::Formatter, - typarams: &Option>, - need_paren: bool) -> fmt::Result { + typarams: &Option>) -> fmt::Result { match *typarams { Some(ref params) => { for param in params { write!(w, " + ")?; fmt::Display::fmt(param, w)?; } - if need_paren { - write!(w, ")")?; - } Ok(()) } None => Ok(()) @@ -637,30 +600,18 @@ impl<'a> fmt::Display for HRef<'a> { } } -impl<'a> fmt::Debug for HRef<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.text) - } -} - -fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, - is_not_debug: bool, is_ref: bool) -> fmt::Result { +fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt::Result { match *t { clean::Generic(ref name) => { f.write_str(name) } clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => { // Paths like T::Output and Self::Output should be rendered with all segments - let need_paren = match *typarams { - Some(ref v) => !v.is_empty(), - _ => false, - } && is_ref; - resolved_path(f, did, path, is_generic, use_absolute, is_not_debug, need_paren)?; - tybounds(f, typarams, need_paren) + resolved_path(f, did, path, is_generic, use_absolute)?; + tybounds(f, typarams) } clean::Infer => write!(f, "_"), - clean::Primitive(prim) if is_not_debug => primitive_link(f, prim, prim.as_str()), - clean::Primitive(prim) => write!(f, "{}", prim.as_str()), + clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()), clean::BareFunction(ref decl) => { if f.alternate() { write!(f, "{}{}fn{:#}{:#}", @@ -678,30 +629,26 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, } clean::Tuple(ref typs) => { match &typs[..] { - &[] if is_not_debug => primitive_link(f, PrimitiveType::Tuple, "()"), - &[] => write!(f, "()"), - &[ref one] if is_not_debug => { + &[] => primitive_link(f, PrimitiveType::Tuple, "()"), + &[ref one] => { primitive_link(f, PrimitiveType::Tuple, "(")?; //carry f.alternate() into this display w/o branching manually fmt::Display::fmt(one, f)?; primitive_link(f, PrimitiveType::Tuple, ",)") } - &[ref one] => write!(f, "({:?},)", one), - many if is_not_debug => { + many => { primitive_link(f, PrimitiveType::Tuple, "(")?; fmt::Display::fmt(&CommaSep(&many), f)?; primitive_link(f, PrimitiveType::Tuple, ")") } - many => write!(f, "({:?})", &CommaSep(&many)), } } - clean::Vector(ref t) if is_not_debug => { + clean::Vector(ref t) => { primitive_link(f, PrimitiveType::Slice, "[")?; fmt::Display::fmt(t, f)?; primitive_link(f, PrimitiveType::Slice, "]") } - clean::Vector(ref t) => write!(f, "[{:?}]", t), - clean::FixedVector(ref t, ref s) if is_not_debug => { + clean::FixedVector(ref t, ref s) => { primitive_link(f, PrimitiveType::Array, "[")?; fmt::Display::fmt(t, f)?; if f.alternate() { @@ -712,17 +659,10 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, &format!("; {}]", Escape(s))) } } - clean::FixedVector(ref t, ref s) => { - if f.alternate() { - write!(f, "[{:?}; {}]", t, s) - } else { - write!(f, "[{:?}; {}]", t, Escape(s)) - } - } clean::Never => f.write_str("!"), clean::RawPointer(m, ref t) => { match **t { - clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} if is_not_debug => { + clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => { if f.alternate() { primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{}{:#}", RawMutableSpace(m), t)) @@ -731,21 +671,11 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, &format!("*{}{}", RawMutableSpace(m), t)) } } - clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => { - if f.alternate() { - write!(f, "*{}{:#?}", RawMutableSpace(m), t) - } else { - write!(f, "*{}{:?}", RawMutableSpace(m), t) - } - } - _ if is_not_debug => { + _ => { primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{}", RawMutableSpace(m)))?; fmt::Display::fmt(t, f) } - _ => { - write!(f, "*{}{:?}", RawMutableSpace(m), t) - } } } clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => { @@ -757,7 +687,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, match **ty { clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T] match **bt { - clean::Generic(_) if is_not_debug => { + clean::Generic(_) => { if f.alternate() { primitive_link(f, PrimitiveType::Slice, &format!("&{}{}[{:#}]", lt, m, **bt)) @@ -766,14 +696,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, &format!("&{}{}[{}]", lt, m, **bt)) } } - clean::Generic(_) => { - if f.alternate() { - write!(f, "&{}{}[{:#?}]", lt, m, **bt) - } else { - write!(f, "&{}{}[{:?}]", lt, m, **bt) - } - } - _ if is_not_debug => { + _ => { if f.alternate() { primitive_link(f, PrimitiveType::Slice, &format!("&{}{}[", lt, m))?; @@ -785,26 +708,25 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, } primitive_link(f, PrimitiveType::Slice, "]") } - _ => { - if f.alternate() { - write!(f, "&{}{}[{:#?}]", lt, m, **bt) - } else { - write!(f, "&{}{}[{:?}]", lt, m, **bt) - } - } } } + clean::ResolvedPath { typarams: Some(ref v), .. } if !v.is_empty() => { + if f.alternate() { + write!(f, "&{}{}", lt, m)?; + } else { + write!(f, "&{}{}", lt, m)?; + } + write!(f, "(")?; + fmt_type(&ty, f, use_absolute)?; + write!(f, ")") + } _ => { if f.alternate() { write!(f, "&{}{}", lt, m)?; - fmt_type(&ty, f, use_absolute, is_not_debug, true) + fmt_type(&ty, f, use_absolute) } else { - if is_not_debug { - write!(f, "&{}{}", lt, m)?; - } else { - write!(f, "&{}{}", lt, m)?; - } - fmt_type(&ty, f, use_absolute, is_not_debug, true) + write!(f, "&{}{}", lt, m)?; + fmt_type(&ty, f, use_absolute) } } } @@ -833,32 +755,16 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, _ => true, }; if f.alternate() { - if is_not_debug { - if should_show_cast { - write!(f, "<{:#} as {:#}>::", self_type, trait_)? - } else { - write!(f, "{:#}::", self_type)? - } + if should_show_cast { + write!(f, "<{:#} as {:#}>::", self_type, trait_)? } else { - if should_show_cast { - write!(f, "<{:#?} as {:#?}>::", self_type, trait_)? - } else { - write!(f, "{:#?}::", self_type)? - } + write!(f, "{:#}::", self_type)? } } else { - if is_not_debug { - if should_show_cast { - write!(f, "<{} as {}>::", self_type, trait_)? - } else { - write!(f, "{}::", self_type)? - } + if should_show_cast { + write!(f, "<{} as {}>::", self_type, trait_)? } else { - if should_show_cast { - write!(f, "<{:?} as {:?}>::", self_type, trait_)? - } else { - write!(f, "{:?}::", self_type)? - } + write!(f, "{}::", self_type)? } }; match *trait_ { @@ -874,7 +780,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, // look at). box clean::ResolvedPath { did, ref typarams, .. } => { let path = clean::Path::singleton(name.clone()); - resolved_path(f, did, &path, true, use_absolute, is_not_debug, false)?; + resolved_path(f, did, &path, true, use_absolute)?; // FIXME: `typarams` are not rendered, and this seems bad? drop(typarams); @@ -893,13 +799,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool, impl fmt::Display for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt_type(self, f, false, true, false) - } -} - -impl fmt::Debug for clean::Type { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt_type(self, f, false, false, false) + fmt_type(self, f, false) } } @@ -933,7 +833,7 @@ fn fmt_impl(i: &clean::Impl, write!(f, " for ")?; } - fmt_type(&i.for_, f, use_absolute, true, false)?; + fmt_type(&i.for_, f, use_absolute)?; fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?; Ok(()) @@ -1139,7 +1039,7 @@ impl fmt::Display for clean::Import { impl fmt::Display for clean::ImportSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.did { - Some(did) => resolved_path(f, did, &self.path, true, false, true, false), + Some(did) => resolved_path(f, did, &self.path, true, false), _ => { for (i, seg) in self.path.segments.iter().enumerate() { if i > 0 { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index fa9315054a11f..a588460d467d2 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1662,9 +1662,9 @@ fn md_render_assoc_item(item: &clean::Item) -> String { match item.inner { clean::AssociatedConstItem(ref ty, ref default) => { if let Some(default) = default.as_ref() { - format!("```\n{}: {:?} = {}\n```\n\n", item.name.as_ref().unwrap(), ty, default) + format!("```\n{}: {:#} = {}\n```\n\n", item.name.as_ref().unwrap(), ty, default) } else { - format!("```\n{}: {:?}\n```\n\n", item.name.as_ref().unwrap(), ty) + format!("```\n{}: {:#}\n```\n\n", item.name.as_ref().unwrap(), ty) } } _ => String::new(), diff --git a/src/test/rustdoc/assoc-consts.rs b/src/test/rustdoc/assoc-consts.rs index d4119f5d351c1..04709407e58a8 100644 --- a/src/test/rustdoc/assoc-consts.rs +++ b/src/test/rustdoc/assoc-consts.rs @@ -26,3 +26,21 @@ impl Bar { // @has - '//*[@class="docblock"]' 'BAR: usize = 3' pub const BAR: usize = 3; } + +pub struct Baz<'a, U: 'a, T>(T, &'a [U]); + +impl Bar { + // @has assoc_consts/struct.Bar.html '//*[@id="associatedconstant.BAZ"]' \ + // "const BAZ: Baz<'static, u8, u32>" + // @has - '//*[@class="docblock"]' "BAZ: Baz<'static, u8, u32> = Baz(321, &[1, 2, 3])" + pub const BAZ: Baz<'static, u8, u32> = Baz(321, &[1, 2, 3]); +} + +pub fn f(_: &(ToString + 'static)) {} + +impl Bar { + // @has assoc_consts/struct.Bar.html '//*[@id="associatedconstant.F"]' \ + // "const F: fn(_: &(ToString + 'static))" + // @has - '//*[@class="docblock"]' "F: fn(_: &(ToString + 'static)) = f" + pub const F: fn(_: &(ToString + 'static)) = f; +}