Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rustdoc: add line breaks to where clauses a la rustfmt #37190

Merged
merged 6 commits into from
Nov 12, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 61 additions & 23 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ pub struct UnsafetySpace(pub hir::Unsafety);
#[derive(Copy, Clone)]
pub struct ConstnessSpace(pub hir::Constness);
/// Wrapper struct for properly emitting a method declaration.
pub struct Method<'a>(pub &'a clean::FnDecl, pub &'a str);
pub struct Method<'a>(pub &'a clean::FnDecl, pub usize);
/// Similar to VisSpace, but used for mutability
#[derive(Copy, Clone)]
pub struct MutableSpace(pub clean::Mutability);
/// Similar to VisSpace, but used for mutability
#[derive(Copy, Clone)]
pub struct RawMutableSpace(pub clean::Mutability);
/// Wrapper struct for emitting a where clause from Generics.
pub struct WhereClause<'a>(pub &'a clean::Generics);
pub struct WhereClause<'a>(pub &'a clean::Generics, pub usize);
/// Wrapper struct for emitting type parameter bounds.
pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
/// Wrapper struct for emitting a comma-separated list of items
Expand Down Expand Up @@ -157,52 +157,71 @@ impl fmt::Display for clean::Generics {

impl<'a> fmt::Display for WhereClause<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &WhereClause(gens) = self;
let &WhereClause(gens, pad) = self;
if gens.where_predicates.is_empty() {
return Ok(());
}
let mut clause = String::new();
if f.alternate() {
f.write_str(" ")?;
clause.push_str(" where ");
} else {
f.write_str(" <span class='where'>where ")?;
clause.push_str(" <span class='where'>where ");
}
for (i, pred) in gens.where_predicates.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
if f.alternate() {
clause.push_str(", ");
} else {
clause.push_str(",<br>");
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subjective, but these sort of patterns can be written:

clause.push_str(if f.alternate() {
    ", "
} else {
    ",<br>"
})

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personal preference, I guess. It it part of a broader style guideline somewhere? At that point it's a ternary expression, too, and can be collapsed onto one line.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It it part of a broader style guideline somewhere?

I don't think so; what you have is fine.

}
match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
let bounds = bounds;
if f.alternate() {
write!(f, "{:#}: {:#}", ty, TyParamBounds(bounds))?;
clause.push_str(&format!("{:#}: {:#}", ty, TyParamBounds(bounds)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to use write! instead of .push_str(&format!( to avoid an extra string allocation. For example, by importing std::fmt::Write this can be write!(clause, "{:#}: {:#}", ty, TyParamBounds(bounds)).unwrap();.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that adjustment as I was going through - I even asked in IRC whether it was possible to use write!() on a String when I was doing it. I decided against writing it in right then because there were other places (not just in my additions here or the previous PR) that used this pattern, so my sense of purism wanted to separate that change to its own logical unit, after this one got dealt with.

} else {
write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
clause.push_str(&format!("{}: {}", ty, TyParamBounds(bounds)));
}
}
&clean::WherePredicate::RegionPredicate { ref lifetime,
ref bounds } => {
write!(f, "{}: ", lifetime)?;
clause.push_str(&format!("{}: ", lifetime));
for (i, lifetime) in bounds.iter().enumerate() {
if i > 0 {
f.write_str(" + ")?;
clause.push_str(" + ");
}

write!(f, "{}", lifetime)?;
clause.push_str(&format!("{}", lifetime));
}
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
if f.alternate() {
write!(f, "{:#} == {:#}", lhs, rhs)?;
clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
} else {
write!(f, "{} == {}", lhs, rhs)?;
clause.push_str(&format!("{} == {}", lhs, rhs));
}
}
}
}
if !f.alternate() {
f.write_str("</span>")?;
clause.push_str("</span>");
let plain = format!("{:#}", self);
if plain.len() > 80 {
//break it onto its own line regardless, but make sure method impls and trait
//blocks keep their fixed padding (2 and 9, respectively)
let padding = if pad > 10 {
clause = clause.replace("class='where'", "class='where fmt-newline'");
repeat("&nbsp;").take(8).collect::<String>()
} else {
repeat("&nbsp;").take(pad + 6).collect::<String>()
};
clause = clause.replace("<br>", &format!("<br>{}", padding));
} else {
clause = clause.replace("<br>", " ");
}
}
Ok(())
write!(f, "{}", clause)
}
}

Expand Down Expand Up @@ -718,30 +737,43 @@ impl fmt::Display for clean::Type {
}

fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
let mut plain = String::new();

if f.alternate() {
write!(f, "impl{:#} ", i.generics)?;
} else {
write!(f, "impl{} ", i.generics)?;
}
plain.push_str(&format!("impl{:#} ", i.generics));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this just be:

let mut plain = format!("impl{:#} ", i.generics);

...and then getting rid of the String::new() above?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see why not. I guess my intent was to have the declaration separate since I was going to be pushing more things onto it later.


if let Some(ref ty) = i.trait_ {
write!(f, "{}",
if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
if i.polarity == Some(clean::ImplPolarity::Negative) {
write!(f, "!")?;
plain.push_str("!");
}

if link_trait {
fmt::Display::fmt(ty, f)?;
plain.push_str(&format!("{:#}", ty));
} else {
match *ty {
clean::ResolvedPath{ typarams: None, ref path, is_generic: false, .. } => {
let last = path.segments.last().unwrap();
fmt::Display::fmt(&last.name, f)?;
fmt::Display::fmt(&last.params, f)?;
plain.push_str(&format!("{:#}{:#}", last.name, last.params));
}
_ => unreachable!(),
}
}
write!(f, " for ")?;
plain.push_str(" for ");
}

fmt::Display::fmt(&i.for_, f)?;
fmt::Display::fmt(&WhereClause(&i.generics), f)?;
plain.push_str(&format!("{:#}", i.for_));

fmt::Display::fmt(&WhereClause(&i.generics, plain.len() + 1), f)?;
Ok(())
}

Expand Down Expand Up @@ -870,24 +902,30 @@ impl<'a> fmt::Display for Method<'a> {

let mut output: String;
let plain: String;
let pad = repeat(" ").take(indent).collect::<String>();
if arrow.is_empty() {
output = format!("({})", args);
plain = format!("{}({})", indent.replace("&nbsp;", " "), args_plain);
plain = format!("{}({})", pad, args_plain);
} else {
output = format!("({args})<br>{arrow}", args = args, arrow = arrow);
plain = format!("{indent}({args}){arrow}",
indent = indent.replace("&nbsp;", " "),
plain = format!("{pad}({args}){arrow}",
pad = pad,
args = args_plain,
arrow = arrow_plain);
}

if plain.len() > 80 {
let pad = format!("<br>{}", indent);
let pad = repeat("&nbsp;").take(indent).collect::<String>();
let pad = format!("<br>{}", pad);
output = output.replace("<br>", &pad);
} else {
output = output.replace("<br>", "");
}
write!(f, "{}", output)
if f.alternate() {
write!(f, "{}", output.replace("<br>", "\n"))
} else {
write!(f, "{}", output)
}
}
}

Expand Down
Loading