1
Fork 0
rust/src/librustdoc/html/format.rs

1071 lines
37 KiB
Rust
Raw Normal View History

//! HTML formatting module
//!
//! This module contains a large number of `fmt::Display` implementations for
//! various types in `rustdoc::clean`. These implementations all currently
//! assume that HTML output is desired, although it may be possible to redesign
//! them in the future to instead emit any format desired.
use std::borrow::Cow;
use std::fmt;
use rustc::hir::def_id::DefId;
use rustc_target::spec::abi::Abi;
2016-03-29 08:50:44 +03:00
use rustc::hir;
use clean::{self, PrimitiveType};
2016-04-17 08:54:48 +02:00
use core::DocAccessLevels;
use html::item_type::ItemType;
Remove hoedown from rustdoc Is it really time? Have our months, no, *years* of suffering come to an end? Are we finally able to cast off the pall of Hoedown? The weight which has dragged us down for so long? ----- So, timeline for those who need to catch up: * Way back in December 2016, [we decided we wanted to switch out the markdown renderer](https://github.com/rust-lang/rust/issues/38400). However, this was put on hold because the build system at the time made it difficult to pull in dependencies from crates.io. * A few months later, in March 2017, [the first PR was done, to switch out the renderers entirely](https://github.com/rust-lang/rust/pull/40338). The PR itself was fraught with CI and build system issues, but eventually landed. * However, not all was well in the Rustdoc world. During the PR and shortly after, we noticed [some differences in the way the two parsers handled some things](https://github.com/rust-lang/rust/issues/40912), and some of these differences were major enough to break the docs for some crates. * A couple weeks afterward, [Hoedown was put back in](https://github.com/rust-lang/rust/pull/41290), at this point just to catch tests that Pulldown was "spuriously" running. This would at least provide some warning about spurious tests, rather than just breaking spontaneously. * However, the problems had created enough noise by this point that just a few days after that, [Hoedown was switched back to the default](https://github.com/rust-lang/rust/pull/41431) while we came up with a solution for properly warning about the differences. * That solution came a few weeks later, [as a series of warnings when the HTML emitted by the two parsers was semantically different](https://github.com/rust-lang/rust/pull/41991). But that came at a cost, as now rustdoc needed proc-macro support (the new crate needed some custom derives farther down its dependency tree), and the build system was not equipped to handle it at the time. It was worked on for three months as the issue stumped more and more people. * In that time, [bootstrap was completely reworked](https://github.com/rust-lang/rust/pull/43059) to change how it ordered compilation, and [the method by which it built rustdoc would change](https://github.com/rust-lang/rust/pull/43482), as well. This allowed it to only be built after stage1, when proc-macros would be available, allowing the "rendering differences" PR to finally land. * The warnings were not perfect, and revealed a few [spurious](https://github.com/rust-lang/rust/pull/44368) [differences](https://github.com/rust-lang/rust/pull/45421) between how we handled the renderers. * Once these were handled, [we flipped the switch to turn on the "rendering difference" warnings all the time](https://github.com/rust-lang/rust/pull/45324), in October 2017. This began the "warning cycle" for this change, and landed in stable in 1.23, on 2018-01-04. * Once those warnings hit stable, and after a couple weeks of seeing whether we would get any more reports than what we got from sitting on nightly/beta, [we switched the renderers](https://github.com/rust-lang/rust/pull/47398), making Pulldown the default but still offering the option to use Hoedown. And that brings us to the present. We haven't received more new issues from this in the meantime, and the "switch by default" is now on beta. Our reasoning is that, at this point, anyone who would have been affected by this has run into it already.
2018-02-16 15:09:19 +01:00
use html::render::{self, cache, CURRENT_LOCATION_KEY};
/// Helper to render an optional visibility with a space after it (if the
/// visibility is preset)
#[derive(Copy, Clone)]
2016-04-11 08:15:14 +00:00
pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
/// Similarly to VisSpace, this structure is used to render a function style with a
/// space after it.
#[derive(Copy, Clone)]
2015-07-31 00:04:06 -07:00
pub struct UnsafetySpace(pub hir::Unsafety);
/// Similarly to VisSpace, this structure is used to render a function constness
/// with a space after it.
#[derive(Copy, Clone)]
2015-07-31 00:04:06 -07:00
pub struct ConstnessSpace(pub hir::Constness);
2018-05-17 14:47:52 -07:00
/// Similarly to VisSpace, this structure is used to render a function asyncness
/// with a space after it.
#[derive(Copy, Clone)]
pub struct AsyncSpace(pub hir::IsAsync);
/// 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 type parameter bounds.
pub struct GenericBounds<'a>(pub &'a [clean::GenericBound]);
/// Wrapper struct for emitting a comma-separated list of items
pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
pub struct AbiSpace(pub Abi);
/// Wrapper struct for properly emitting a function or method declaration.
pub struct Function<'a> {
/// The declaration to emit.
pub decl: &'a clean::FnDecl,
/// The length of the function header and name. In other words, the number of characters in the
/// function declaration up to but not including the parentheses.
///
/// Used to determine line-wrapping.
pub header_len: usize,
/// The number of spaces to indent each successive line with, if line-wrapping is necessary.
pub indent: usize,
/// Whether the function is async or not.
pub asyncness: hir::IsAsync,
}
2019-02-08 14:53:55 +01:00
/// Wrapper struct for emitting a where-clause from Generics.
pub struct WhereClause<'a>{
2019-02-08 14:53:55 +01:00
/// The Generics from which to emit a where-clause.
pub gens: &'a clean::Generics,
/// The number of spaces to indent each line with.
pub indent: usize,
2019-02-08 14:53:55 +01:00
/// Whether the where-clause needs to add a comma and newline after the last bound.
pub end_newline: bool,
}
2016-04-25 08:24:50 +02:00
pub struct HRef<'a> {
pub did: DefId,
pub text: &'a str,
}
impl<'a> VisSpace<'a> {
2016-04-11 08:15:14 +00:00
pub fn get(self) -> &'a Option<clean::Visibility> {
let VisSpace(v) = self; v
}
}
2014-12-09 10:36:46 -05:00
impl UnsafetySpace {
2015-07-31 00:04:06 -07:00
pub fn get(&self) -> hir::Unsafety {
2014-12-09 10:36:46 -05:00
let UnsafetySpace(v) = *self; v
}
}
impl ConstnessSpace {
2015-07-31 00:04:06 -07:00
pub fn get(&self) -> hir::Constness {
let ConstnessSpace(v) = *self; v
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl<'a, T: fmt::Display> fmt::Display 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::Display::fmt(item, f)?;
}
Ok(())
}
}
impl<'a> fmt::Display for GenericBounds<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &GenericBounds(bounds) = self;
for (i, bound) in bounds.iter().enumerate() {
if i > 0 {
f.write_str(" + ")?;
}
fmt::Display::fmt(bound, f)?;
}
Ok(())
}
}
2018-04-12 17:53:29 +01:00
impl fmt::Display for clean::GenericParamDef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
f.write_str(&self.name)?;
if !bounds.is_empty() {
if f.alternate() {
write!(f, ": {:#}", GenericBounds(bounds))?;
} else {
write!(f, ":&nbsp;{}", GenericBounds(bounds))?;
}
}
if let Some(ref ty) = default {
if f.alternate() {
write!(f, " = {:#}", ty)?;
} else {
write!(f, "&nbsp;=&nbsp;{}", ty)?;
}
}
Ok(())
}
clean::GenericParamDefKind::Const { ref ty, .. } => {
f.write_str("const ")?;
f.write_str(&self.name)?;
if f.alternate() {
write!(f, ": {:#}", ty)
} else {
write!(f, ":&nbsp;{}", ty)
}
}
}
}
}
impl fmt::Display for clean::Generics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2018-03-24 11:03:06 +09:00
let real_params = self.params
.iter()
.filter(|p| !p.is_synthetic_type_param())
.collect::<Vec<_>>();
if real_params.is_empty() {
return Ok(());
}
if f.alternate() {
2018-03-24 11:03:06 +09:00
write!(f, "<{:#}>", CommaSep(&real_params))
} else {
2018-03-24 11:03:06 +09:00
write!(f, "&lt;{}&gt;", CommaSep(&real_params))
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl<'a> fmt::Display for WhereClause<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &WhereClause { gens, indent, end_newline } = self;
if gens.where_predicates.is_empty() {
return Ok(());
}
let mut clause = String::new();
if f.alternate() {
clause.push_str(" where");
} else {
if end_newline {
clause.push_str(" <span class=\"where fmt-newline\">where");
} else {
clause.push_str(" <span class=\"where\">where");
}
}
for (i, pred) in gens.where_predicates.iter().enumerate() {
if f.alternate() {
clause.push(' ');
} else {
clause.push_str("<br>");
}
match pred {
2014-12-24 00:58:21 -08:00
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
let bounds = bounds;
if f.alternate() {
clause.push_str(&format!("{:#}: {:#}", ty, GenericBounds(bounds)));
} else {
clause.push_str(&format!("{}: {}", ty, GenericBounds(bounds)));
}
2014-12-24 00:58:21 -08:00
}
&clean::WherePredicate::RegionPredicate { ref lifetime,
ref bounds } => {
clause.push_str(&format!("{}: ", lifetime));
for (i, lifetime) in bounds.iter().enumerate() {
if i > 0 {
clause.push_str(" + ");
}
2018-07-27 11:11:18 +02:00
clause.push_str(&lifetime.to_string());
}
2014-12-24 00:58:21 -08:00
}
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
if f.alternate() {
clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
} else {
clause.push_str(&format!("{} == {}", lhs, rhs));
}
}
}
if i < gens.where_predicates.len() - 1 || end_newline {
clause.push(',');
}
}
if end_newline {
2017-08-28 22:40:09 +02:00
// add a space so stripping <br> tags and breaking spaces still renders properly
if f.alternate() {
clause.push(' ');
} else {
clause.push_str("&nbsp;");
}
}
if !f.alternate() {
clause.push_str("</span>");
2018-04-01 13:48:15 +09:00
let padding = "&nbsp;".repeat(indent + 4);
clause = clause.replace("<br>", &format!("<br>{}", padding));
2018-04-01 13:48:15 +09:00
clause.insert_str(0, &"&nbsp;".repeat(indent.saturating_sub(1)));
if !end_newline {
clause.insert_str(0, "<br>");
}
}
write!(f, "{}", clause)
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::Lifetime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.get_ref())?;
2014-01-30 11:30:21 -08:00
Ok(())
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::PolyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if !self.generic_params.is_empty() {
if f.alternate() {
write!(f, "for<{:#}> ", CommaSep(&self.generic_params))?;
} else {
write!(f, "for&lt;{}&gt; ", CommaSep(&self.generic_params))?;
}
}
if f.alternate() {
write!(f, "{:#}", self.trait_)
} else {
write!(f, "{}", self.trait_)
}
}
}
impl fmt::Display for clean::GenericBound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
2018-06-14 12:23:46 +01:00
clean::GenericBound::Outlives(ref lt) => {
write!(f, "{}", *lt)
}
2018-06-14 12:23:46 +01:00
clean::GenericBound::TraitBound(ref ty, modifier) => {
2014-12-24 22:34:57 +13:00
let modifier_str = match modifier {
2015-07-31 00:04:06 -07:00
hir::TraitBoundModifier::None => "",
hir::TraitBoundModifier::Maybe => "?",
2014-12-24 22:34:57 +13:00
};
if f.alternate() {
write!(f, "{}{:#}", modifier_str, *ty)
} else {
write!(f, "{}{}", modifier_str, *ty)
}
}
}
}
}
impl fmt::Display for clean::GenericArgs {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::GenericArgs::AngleBracketed {
ref lifetimes, ref types, ref bindings
} => {
if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
if f.alternate() {
f.write_str("<")?;
} else {
f.write_str("&lt;")?;
}
let mut comma = false;
2015-01-31 12:20:46 -05:00
for lifetime in lifetimes {
if comma {
f.write_str(", ")?;
}
comma = true;
write!(f, "{}", *lifetime)?;
2014-01-30 11:30:21 -08:00
}
2015-01-31 12:20:46 -05:00
for ty in types {
if comma {
f.write_str(", ")?;
}
comma = true;
if f.alternate() {
write!(f, "{:#}", *ty)?;
} else {
write!(f, "{}", *ty)?;
}
}
2015-01-31 12:20:46 -05:00
for binding in bindings {
if comma {
f.write_str(", ")?;
}
comma = true;
if f.alternate() {
write!(f, "{:#}", *binding)?;
} else {
write!(f, "{}", *binding)?;
}
}
if f.alternate() {
f.write_str(">")?;
} else {
f.write_str("&gt;")?;
}
}
}
clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
f.write_str("(")?;
let mut comma = false;
2015-01-31 12:20:46 -05:00
for ty in inputs {
2014-01-30 11:30:21 -08:00
if comma {
f.write_str(", ")?;
2014-01-30 11:30:21 -08:00
}
comma = true;
if f.alternate() {
write!(f, "{:#}", *ty)?;
} else {
write!(f, "{}", *ty)?;
}
}
f.write_str(")")?;
if let Some(ref ty) = *output {
if f.alternate() {
write!(f, " -> {:#}", ty)?;
} else {
write!(f, " -&gt; {}", ty)?;
}
}
}
}
Ok(())
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::PathSegment {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.name)?;
if f.alternate() {
2018-02-23 17:48:54 +00:00
write!(f, "{:#}", self.args)
} else {
2018-02-23 17:48:54 +00:00
write!(f, "{}", self.args)
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.global {
f.write_str("::")?
}
for (i, seg) in self.segments.iter().enumerate() {
if i > 0 {
f.write_str("::")?
}
if f.alternate() {
write!(f, "{:#}", seg)?;
} else {
write!(f, "{}", seg)?;
}
}
2014-01-30 11:30:21 -08:00
Ok(())
}
}
2015-08-16 06:32:28 -04:00
pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
let cache = cache();
if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
return None
}
let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
let (fqp, shortty, mut url) = match cache.paths.get(&did) {
Some(&(ref fqp, shortty)) => {
2018-04-01 13:48:15 +09:00
(fqp, shortty, "../".repeat(loc.len()))
}
None => {
let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
(fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(),
2018-04-01 13:48:15 +09:00
(.., render::Local) => "../".repeat(loc.len()),
(.., render::Unknown) => return None,
})
}
};
for component in &fqp[..fqp.len() - 1] {
url.push_str(component);
url.push_str("/");
}
match shortty {
ItemType::Module => {
url.push_str(fqp.last().unwrap());
url.push_str("/index.html");
}
_ => {
url.push_str(shortty.css_class());
url.push_str(".");
url.push_str(fqp.last().unwrap());
url.push_str(".html");
}
}
Some((url, shortty, fqp.to_vec()))
}
/// Used when rendering a `ResolvedPath` structure. This invokes the `path`
/// rendering function with the necessary arguments for linking to a local path.
2015-08-16 06:32:28 -04:00
fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
print_all: bool, use_absolute: bool) -> fmt::Result {
let last = path.segments.last().unwrap();
if print_all {
for seg in &path.segments[..path.segments.len() - 1] {
write!(w, "{}::", seg.name)?;
}
}
if w.alternate() {
2018-02-23 17:48:54 +00:00
write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.args)?;
} else {
let path = if use_absolute {
match href(did) {
Some((_, _, fqp)) => {
format!("{}::{}",
fqp[..fqp.len() - 1].join("::"),
HRef::new(did, fqp.last().unwrap()))
2017-03-10 16:21:07 +01:00
}
2018-07-27 11:11:18 +02:00
None => HRef::new(did, &last.name).to_string(),
}
} else {
2018-07-27 11:11:18 +02:00
HRef::new(did, &last.name).to_string()
};
2018-02-23 17:48:54 +00:00
write!(w, "{}{}", path, last.args)?;
}
Ok(())
}
fn primitive_link(f: &mut fmt::Formatter,
prim: clean::PrimitiveType,
name: &str) -> fmt::Result {
let m = cache();
let mut needs_termination = false;
if !f.alternate() {
match m.primitive_locations.get(&prim) {
Some(&def_id) if def_id.is_local() => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
let len = if len == 0 {0} else {len - 1};
write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
2018-04-01 13:48:15 +09:00
"../".repeat(len),
prim.to_url_str())?;
needs_termination = true;
}
Some(&def_id) => {
let loc = match m.extern_locations[&def_id.krate] {
(ref cname, _, render::Remote(ref s)) => {
Some((cname, s.to_string()))
}
(ref cname, _, render::Local) => {
let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
2018-04-01 13:48:15 +09:00
Some((cname, "../".repeat(len)))
}
(.., render::Unknown) => None,
};
if let Some((cname, root)) = loc {
write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
root,
cname,
prim.to_url_str())?;
needs_termination = true;
}
}
None => {}
}
}
write!(f, "{}", name)?;
if needs_termination {
write!(f, "</a>")?;
}
Ok(())
}
/// Helper to render type parameters
fn tybounds(w: &mut fmt::Formatter,
typarams: &Option<Vec<clean::GenericBound>>) -> fmt::Result {
rustdoc: Generate hyperlinks between crates The general idea of hyperlinking between crates is that it should require as little configuration as possible, if any at all. In this vein, there are two separate ways to generate hyperlinks between crates: 1. When you're generating documentation for a crate 'foo' into folder 'doc', then if foo's external crate dependencies already have documented in the folder 'doc', then hyperlinks will be generated. This will work because all documentation is in the same folder, allowing links to work seamlessly both on the web and on the local filesystem browser. The rationale for this use case is a package with multiple libraries/crates that all want to link to one another, and you don't want to have to deal with going to the web. In theory this could be extended to have a RUST_PATH-style searching situtation, but I'm not sure that it would work seamlessly on the web as it does on the local filesystem, so I'm not attempting to explore this case in this pull request. I believe to fully realize this potential rustdoc would have to be acting as a server instead of a static site generator. 2. One of foo's external dependencies has a #[doc(html_root_url = "...")] attribute. This means that all hyperlinks to the dependency will be rooted at this url. This use case encompasses all packages using libstd/libextra. These two crates now have this attribute encoded (currently at the /doc/master url) and will be read by anything which has a dependency on libstd/libextra. This should also work for arbitrary crates in the wild that have online documentation. I don't like how the version is hard-wired into the url, but I think that this may be a case-by-case thing which doesn't end up being too bad in the long run. Closes #9539
2013-10-02 15:39:32 -07:00
match *typarams {
Some(ref params) => {
2015-01-31 12:20:46 -05:00
for param in params {
write!(w, " + ")?;
fmt::Display::fmt(param, w)?;
rustdoc: Generate hyperlinks between crates The general idea of hyperlinking between crates is that it should require as little configuration as possible, if any at all. In this vein, there are two separate ways to generate hyperlinks between crates: 1. When you're generating documentation for a crate 'foo' into folder 'doc', then if foo's external crate dependencies already have documented in the folder 'doc', then hyperlinks will be generated. This will work because all documentation is in the same folder, allowing links to work seamlessly both on the web and on the local filesystem browser. The rationale for this use case is a package with multiple libraries/crates that all want to link to one another, and you don't want to have to deal with going to the web. In theory this could be extended to have a RUST_PATH-style searching situtation, but I'm not sure that it would work seamlessly on the web as it does on the local filesystem, so I'm not attempting to explore this case in this pull request. I believe to fully realize this potential rustdoc would have to be acting as a server instead of a static site generator. 2. One of foo's external dependencies has a #[doc(html_root_url = "...")] attribute. This means that all hyperlinks to the dependency will be rooted at this url. This use case encompasses all packages using libstd/libextra. These two crates now have this attribute encoded (currently at the /doc/master url) and will be read by anything which has a dependency on libstd/libextra. This should also work for arbitrary crates in the wild that have online documentation. I don't like how the version is hard-wired into the url, but I think that this may be a case-by-case thing which doesn't end up being too bad in the long run. Closes #9539
2013-10-02 15:39:32 -07:00
}
2014-01-30 11:30:21 -08:00
Ok(())
rustdoc: Generate hyperlinks between crates The general idea of hyperlinking between crates is that it should require as little configuration as possible, if any at all. In this vein, there are two separate ways to generate hyperlinks between crates: 1. When you're generating documentation for a crate 'foo' into folder 'doc', then if foo's external crate dependencies already have documented in the folder 'doc', then hyperlinks will be generated. This will work because all documentation is in the same folder, allowing links to work seamlessly both on the web and on the local filesystem browser. The rationale for this use case is a package with multiple libraries/crates that all want to link to one another, and you don't want to have to deal with going to the web. In theory this could be extended to have a RUST_PATH-style searching situtation, but I'm not sure that it would work seamlessly on the web as it does on the local filesystem, so I'm not attempting to explore this case in this pull request. I believe to fully realize this potential rustdoc would have to be acting as a server instead of a static site generator. 2. One of foo's external dependencies has a #[doc(html_root_url = "...")] attribute. This means that all hyperlinks to the dependency will be rooted at this url. This use case encompasses all packages using libstd/libextra. These two crates now have this attribute encoded (currently at the /doc/master url) and will be read by anything which has a dependency on libstd/libextra. This should also work for arbitrary crates in the wild that have online documentation. I don't like how the version is hard-wired into the url, but I think that this may be a case-by-case thing which doesn't end up being too bad in the long run. Closes #9539
2013-10-02 15:39:32 -07:00
}
2014-01-30 11:30:21 -08:00
None => Ok(())
rustdoc: Generate hyperlinks between crates The general idea of hyperlinking between crates is that it should require as little configuration as possible, if any at all. In this vein, there are two separate ways to generate hyperlinks between crates: 1. When you're generating documentation for a crate 'foo' into folder 'doc', then if foo's external crate dependencies already have documented in the folder 'doc', then hyperlinks will be generated. This will work because all documentation is in the same folder, allowing links to work seamlessly both on the web and on the local filesystem browser. The rationale for this use case is a package with multiple libraries/crates that all want to link to one another, and you don't want to have to deal with going to the web. In theory this could be extended to have a RUST_PATH-style searching situtation, but I'm not sure that it would work seamlessly on the web as it does on the local filesystem, so I'm not attempting to explore this case in this pull request. I believe to fully realize this potential rustdoc would have to be acting as a server instead of a static site generator. 2. One of foo's external dependencies has a #[doc(html_root_url = "...")] attribute. This means that all hyperlinks to the dependency will be rooted at this url. This use case encompasses all packages using libstd/libextra. These two crates now have this attribute encoded (currently at the /doc/master url) and will be read by anything which has a dependency on libstd/libextra. This should also work for arbitrary crates in the wild that have online documentation. I don't like how the version is hard-wired into the url, but I think that this may be a case-by-case thing which doesn't end up being too bad in the long run. Closes #9539
2013-10-02 15:39:32 -07:00
}
}
2016-04-25 08:24:50 +02:00
impl<'a> HRef<'a> {
pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
HRef { did: did, text: text }
}
}
impl<'a> fmt::Display for HRef<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match href(self.did) {
Some((url, shortty, fqp)) => if !f.alternate() {
write!(f, "<a class=\"{}\" href=\"{}\" title=\"{} {}\">{}</a>",
shortty, url, shortty, fqp.join("::"), self.text)
} else {
write!(f, "{}", self.text)
},
2016-04-25 08:24:50 +02:00
_ => write!(f, "{}", self.text),
}
}
}
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 } => {
if typarams.is_some() {
f.write_str("dyn ")?;
}
// Paths like T::Output and Self::Output should be rendered with all segments
resolved_path(f, did, path, is_generic, use_absolute)?;
tybounds(f, typarams)
}
clean::Infer => write!(f, "_"),
clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
clean::BareFunction(ref decl) => {
if f.alternate() {
2017-11-28 12:05:53 +01:00
write!(f, "{}{:#}fn{:#}{:#}",
UnsafetySpace(decl.unsafety),
AbiSpace(decl.abi),
CommaSep(&decl.generic_params),
decl.decl)
} else {
write!(f, "{}{}", UnsafetySpace(decl.unsafety), AbiSpace(decl.abi))?;
primitive_link(f, PrimitiveType::Fn, "fn")?;
write!(f, "{}{}", CommaSep(&decl.generic_params), decl.decl)
}
}
clean::Tuple(ref typs) => {
match &typs[..] {
&[] => primitive_link(f, PrimitiveType::Unit, "()"),
&[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, ",)")
}
many => {
primitive_link(f, PrimitiveType::Tuple, "(")?;
2018-03-23 22:06:28 +09:00
fmt::Display::fmt(&CommaSep(many), f)?;
primitive_link(f, PrimitiveType::Tuple, ")")
}
}
}
clean::Slice(ref t) => {
primitive_link(f, PrimitiveType::Slice, "[")?;
fmt::Display::fmt(t, f)?;
primitive_link(f, PrimitiveType::Slice, "]")
}
clean::Array(ref t, ref n) => {
primitive_link(f, PrimitiveType::Array, "[")?;
fmt::Display::fmt(t, f)?;
primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
}
2017-11-28 09:38:19 +08:00
clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
clean::RawPointer(m, ref t) => {
match **t {
clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
if f.alternate() {
primitive_link(f, clean::PrimitiveType::RawPointer,
&format!("*{}{:#}", RawMutableSpace(m), t))
} else {
primitive_link(f, clean::PrimitiveType::RawPointer,
&format!("*{}{}", RawMutableSpace(m), t))
2016-01-23 15:01:17 +05:30
}
}
_ => {
primitive_link(f, clean::PrimitiveType::RawPointer,
&format!("*{}", RawMutableSpace(m)))?;
fmt::Display::fmt(t, f)
}
}
}
clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
let lt = match *l {
Some(ref l) => format!("{} ", *l),
_ => String::new(),
};
let m = MutableSpace(mutability);
2017-07-30 14:59:08 -05:00
let amp = if f.alternate() {
"&".to_string()
} else {
"&amp;".to_string()
};
match **ty {
clean::Slice(ref bt) => { // BorrowedRef{ ... Slice(T) } is &[T]
match **bt {
clean::Generic(_) => {
if f.alternate() {
primitive_link(f, PrimitiveType::Slice,
2017-07-30 14:59:08 -05:00
&format!("{}{}{}[{:#}]", amp, lt, m, **bt))
} else {
primitive_link(f, PrimitiveType::Slice,
2017-07-30 14:59:08 -05:00
&format!("{}{}{}[{}]", amp, lt, m, **bt))
}
}
_ => {
2017-07-30 14:59:08 -05:00
primitive_link(f, PrimitiveType::Slice,
&format!("{}{}{}[", amp, lt, m))?;
if f.alternate() {
write!(f, "{:#}", **bt)?;
} else {
write!(f, "{}", **bt)?;
}
primitive_link(f, PrimitiveType::Slice, "]")
}
}
}
clean::ResolvedPath { typarams: Some(ref v), .. } if !v.is_empty() => {
2017-07-30 14:59:08 -05:00
write!(f, "{}{}{}(", amp, lt, m)?;
fmt_type(&ty, f, use_absolute)?;
write!(f, ")")
}
2017-07-30 14:59:08 -05:00
clean::Generic(..) => {
primitive_link(f, PrimitiveType::Reference,
&format!("{}{}{}", amp, lt, m))?;
fmt_type(&ty, f, use_absolute)
}
_ => {
2017-07-30 14:59:08 -05:00
write!(f, "{}{}{}", amp, lt, m)?;
fmt_type(&ty, f, use_absolute)
}
}
}
clean::ImplTrait(ref bounds) => {
if f.alternate() {
write!(f, "impl {:#}", GenericBounds(bounds))
} else {
write!(f, "impl {}", GenericBounds(bounds))
}
}
clean::QPath { ref name, ref self_type, ref trait_ } => {
let should_show_cast = match *trait_ {
box clean::ResolvedPath { ref path, .. } => {
!path.segments.is_empty() && !self_type.is_self_type()
}
_ => true,
};
if f.alternate() {
if should_show_cast {
write!(f, "<{:#} as {:#}>::", self_type, trait_)?
} else {
write!(f, "{:#}::", self_type)?
}
} else {
if should_show_cast {
write!(f, "&lt;{} as {}&gt;::", self_type, trait_)?
} else {
write!(f, "{}::", self_type)?
}
};
match *trait_ {
// It's pretty unsightly to look at `<A as B>::C` in output, and
// we've got hyperlinking on our side, so try to avoid longer
// notation as much as possible by making `C` a hyperlink to trait
// `B` to disambiguate.
//
// FIXME: this is still a lossy conversion and there should probably
// be a better way of representing this in general? Most of
// 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 typarams, .. } => {
match href(did) {
Some((ref url, _, ref path)) if !f.alternate() => {
write!(f,
"<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
title=\"type {path}::{name}\">{name}</a>",
url = url,
shortty = ItemType::AssociatedType,
name = name,
path = path.join("::"))?;
}
_ => write!(f, "{}", name)?,
}
// FIXME: `typarams` are not rendered, and this seems bad?
drop(typarams);
Ok(())
}
_ => {
write!(f, "{}", name)
}
}
}
clean::Unique(..) => {
panic!("should have been cleaned")
}
}
}
impl fmt::Display for clean::Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_type(self, f, false)
}
}
2016-12-22 23:20:22 -08:00
fn fmt_impl(i: &clean::Impl,
f: &mut fmt::Formatter,
link_trait: bool,
use_absolute: bool) -> fmt::Result {
if f.alternate() {
write!(f, "impl{:#} ", i.generics)?;
} else {
write!(f, "impl{} ", i.generics)?;
}
if let Some(ref ty) = i.trait_ {
if i.polarity == Some(clean::ImplPolarity::Negative) {
write!(f, "!")?;
}
if link_trait {
fmt::Display::fmt(ty, f)?;
} else {
match *ty {
clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => {
let last = path.segments.last().unwrap();
fmt::Display::fmt(&last.name, f)?;
2018-02-23 17:48:54 +00:00
fmt::Display::fmt(&last.args, f)?;
}
_ => unreachable!(),
}
}
write!(f, " for ")?;
}
if let Some(ref ty) = i.blanket_impl {
fmt_type(ty, f, use_absolute)?;
} else {
fmt_type(&i.for_, f, use_absolute)?;
}
fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?;
Ok(())
}
impl fmt::Display for clean::Impl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_impl(self, f, true, false)
}
}
// The difference from above is that trait is not hyperlinked.
pub fn fmt_impl_for_trait_page(i: &clean::Impl,
f: &mut fmt::Formatter,
2016-12-22 23:20:22 -08:00
use_absolute: bool) -> fmt::Result {
fmt_impl(i, f, false, use_absolute)
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::Arguments {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, input) in self.values.iter().enumerate() {
if !input.name.is_empty() {
write!(f, "{}: ", input.name)?;
}
if f.alternate() {
write!(f, "{:#}", input.type_)?;
} else {
write!(f, "{}", input.type_)?;
}
if i + 1 < self.values.len() { write!(f, ", ")?; }
}
Ok(())
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::FunctionRetTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
clean::Return(ref ty) if f.alternate() => write!(f, " -> {:#}", ty),
clean::Return(ref ty) => write!(f, " -&gt; {}", ty),
clean::DefaultReturn => Ok(()),
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::FnDecl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2015-08-20 18:27:53 +01:00
if self.variadic {
if f.alternate() {
write!(f, "({args:#}, ...){arrow:#}", args = self.inputs, arrow = self.output)
} else {
write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
}
2015-08-20 18:27:53 +01:00
} else {
if f.alternate() {
write!(f, "({args:#}){arrow:#}", args = self.inputs, arrow = self.output)
} else {
write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
}
2015-08-20 18:27:53 +01:00
}
2013-11-28 02:23:12 +09:00
}
}
impl<'a> fmt::Display for Function<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Function { decl, header_len, indent, asyncness } = self;
let amp = if f.alternate() { "&" } else { "&amp;" };
let mut args = String::new();
let mut args_plain = String::new();
2016-05-08 21:19:29 +03:00
for (i, input) in decl.inputs.values.iter().enumerate() {
2017-03-28 16:49:05 -05:00
if i == 0 {
args.push_str("<br>");
}
2016-05-08 21:19:29 +03:00
if let Some(selfty) = input.to_self() {
match selfty {
clean::SelfValue => {
args.push_str("self");
args_plain.push_str("self");
}
2016-05-08 21:19:29 +03:00
clean::SelfBorrowed(Some(ref lt), mtbl) => {
args.push_str(&format!("{}{} {}self", amp, *lt, MutableSpace(mtbl)));
args_plain.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
2016-05-08 21:19:29 +03:00
}
clean::SelfBorrowed(None, mtbl) => {
args.push_str(&format!("{}{}self", amp, MutableSpace(mtbl)));
args_plain.push_str(&format!("&{}self", MutableSpace(mtbl)));
2016-05-08 21:19:29 +03:00
}
clean::SelfExplicit(ref typ) => {
if f.alternate() {
args.push_str(&format!("self: {:#}", *typ));
} else {
args.push_str(&format!("self: {}", *typ));
}
args_plain.push_str(&format!("self: {:#}", *typ));
2016-05-08 21:19:29 +03:00
}
}
} else {
if i > 0 {
args.push_str(" <br>");
args_plain.push_str(" ");
}
2016-05-08 21:19:29 +03:00
if !input.name.is_empty() {
args.push_str(&format!("{}: ", input.name));
args_plain.push_str(&format!("{}: ", input.name));
2016-05-08 21:19:29 +03:00
}
if f.alternate() {
args.push_str(&format!("{:#}", input.type_));
} else {
2018-07-27 11:11:18 +02:00
args.push_str(&input.type_.to_string());
}
args_plain.push_str(&format!("{:#}", input.type_));
}
if i + 1 < decl.inputs.values.len() {
2017-03-28 16:49:05 -05:00
args.push(',');
args_plain.push(',');
}
}
let mut args_plain = format!("({})", args_plain);
if decl.variadic {
args.push_str(",<br> ...");
args_plain.push_str(", ...");
}
let output = if let hir::IsAsync::Async = asyncness {
Cow::Owned(decl.sugared_async_return_type())
} else {
Cow::Borrowed(&decl.output)
};
let arrow_plain = format!("{:#}", &output);
let arrow = if f.alternate() {
format!("{:#}", &output)
} else {
output.to_string()
};
let declaration_len = header_len + args_plain.len() + arrow_plain.len();
let output = if declaration_len > 80 {
2018-04-01 13:48:15 +09:00
let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
format!("({args}{close}){arrow}",
args = args.replace("<br>", &full_pad),
close = close_pad,
arrow = arrow)
} else {
2017-03-28 16:49:05 -05:00
format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
};
if f.alternate() {
write!(f, "{}", output.replace("<br>", "\n"))
} else {
write!(f, "{}", output)
}
}
}
impl<'a> fmt::Display for VisSpace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.get() {
Some(clean::Public) => f.write_str("pub "),
Some(clean::Inherited) | None => Ok(()),
Some(clean::Visibility::Crate) => write!(f, "pub(crate) "),
Some(clean::Visibility::Restricted(did, ref path)) => {
f.write_str("pub(")?;
if path.segments.len() != 1
|| (path.segments[0].name != "self" && path.segments[0].name != "super")
{
f.write_str("in ")?;
}
resolved_path(f, did, path, true, false)?;
f.write_str(") ")
}
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for UnsafetySpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
2015-07-31 00:04:06 -07:00
hir::Unsafety::Unsafe => write!(f, "unsafe "),
hir::Unsafety::Normal => Ok(())
}
}
}
impl fmt::Display for ConstnessSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get() {
2015-07-31 00:04:06 -07:00
hir::Constness::Const => write!(f, "const "),
hir::Constness::NotConst => Ok(())
}
}
}
2018-05-17 14:47:52 -07:00
impl fmt::Display for AsyncSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.0 {
hir::IsAsync::Async => write!(f, "async "),
hir::IsAsync::NotAsync => Ok(()),
}
}
}
impl fmt::Display for clean::Import {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
clean::Import::Simple(ref name, ref src) => {
if *name == src.path.last_name() {
write!(f, "use {};", *src)
} else {
write!(f, "use {} as {};", *src, *name)
}
}
clean::Import::Glob(ref src) => {
2017-06-24 18:16:39 +01:00
if src.path.segments.is_empty() {
write!(f, "use *;")
} else {
write!(f, "use {}::*;", *src)
}
}
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
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),
_ => {
for (i, seg) in self.path.segments.iter().enumerate() {
2014-01-30 11:30:21 -08:00
if i > 0 {
write!(f, "::")?
2014-01-30 11:30:21 -08:00
}
write!(f, "{}", seg.name)?;
}
2014-01-30 11:30:21 -08:00
Ok(())
}
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for clean::TypeBinding {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
write!(f, "{} = {:#}", self.name, self.ty)
} else {
write!(f, "{} = {}", self.name, self.ty)
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for MutableSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
MutableSpace(clean::Immutable) => Ok(()),
MutableSpace(clean::Mutable) => write!(f, "mut "),
}
}
}
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 15:45:07 -08:00
impl fmt::Display for RawMutableSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RawMutableSpace(clean::Immutable) => write!(f, "const "),
RawMutableSpace(clean::Mutable) => write!(f, "mut "),
}
}
}
impl fmt::Display for AbiSpace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let quot = if f.alternate() { "\"" } else { "&quot;" };
match self.0 {
Abi::Rust => Ok(()),
abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
}
}
}