summaryrefslogtreecommitdiffstats
path: root/src/librustdoc/html
diff options
context:
space:
mode:
Diffstat (limited to 'src/librustdoc/html')
-rw-r--r--src/librustdoc/html/format.rs138
-rw-r--r--src/librustdoc/html/highlight.rs38
-rw-r--r--src/librustdoc/html/highlight/tests.rs2
-rw-r--r--src/librustdoc/html/length_limit.rs7
-rw-r--r--src/librustdoc/html/markdown.rs145
-rw-r--r--src/librustdoc/html/markdown/tests.rs2
-rw-r--r--src/librustdoc/html/render/context.rs39
-rw-r--r--src/librustdoc/html/render/mod.rs266
-rw-r--r--src/librustdoc/html/render/print_item.rs114
-rw-r--r--src/librustdoc/html/render/sidebar.rs14
-rw-r--r--src/librustdoc/html/render/span_map.rs97
-rw-r--r--src/librustdoc/html/render/type_layout.rs2
-rw-r--r--src/librustdoc/html/render/write_shared.rs29
-rw-r--r--src/librustdoc/html/sources.rs7
-rw-r--r--src/librustdoc/html/static/css/noscript.css2
-rw-r--r--src/librustdoc/html/static/css/rustdoc.css74
-rw-r--r--src/librustdoc/html/static/css/themes/ayu.css14
-rw-r--r--src/librustdoc/html/static/css/themes/dark.css6
-rw-r--r--src/librustdoc/html/static/css/themes/light.css6
-rw-r--r--src/librustdoc/html/static/js/search.js29
-rw-r--r--src/librustdoc/html/static/js/src-script.js (renamed from src/librustdoc/html/static/js/source-script.js)32
-rw-r--r--src/librustdoc/html/static/js/storage.js2
-rw-r--r--src/librustdoc/html/static_files.rs4
-rw-r--r--src/librustdoc/html/templates/STYLE.md2
-rw-r--r--src/librustdoc/html/templates/page.html16
-rw-r--r--src/librustdoc/html/templates/print_item.html2
-rw-r--r--src/librustdoc/html/templates/type_layout.html5
27 files changed, 622 insertions, 472 deletions
diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs
index 54c0cd2ef..2f611c31a 100644
--- a/src/librustdoc/html/format.rs
+++ b/src/librustdoc/html/format.rs
@@ -18,7 +18,7 @@ use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_metadata::creader::{CStore, LoadedMacro};
use rustc_middle::ty;
use rustc_middle::ty::TyCtxt;
@@ -109,6 +109,10 @@ impl Buffer {
self.buffer
}
+ pub(crate) fn push(&mut self, c: char) {
+ self.buffer.push(c);
+ }
+
pub(crate) fn push_str(&mut self, s: &str) {
self.buffer.push_str(s);
}
@@ -228,9 +232,9 @@ impl clean::GenericParamDef {
if let Some(default) = default {
if f.alternate() {
- write!(f, " = {:#}", default)?;
+ write!(f, " = {default:#}")?;
} else {
- write!(f, " = {}", default)?;
+ write!(f, " = {default}")?;
}
}
@@ -451,9 +455,9 @@ impl clean::GenericBound {
hir::TraitBoundModifier::MaybeConst => "",
};
if f.alternate() {
- write!(f, "{}{:#}", modifier_str, ty.print(cx))
+ write!(f, "{modifier_str}{ty:#}", ty = ty.print(cx))
} else {
- write!(f, "{}{}", modifier_str, ty.print(cx))
+ write!(f, "{modifier_str}{ty}", ty = ty.print(cx))
}
}
})
@@ -599,12 +603,12 @@ fn generate_macro_def_id_path(
let cstore = CStore::from_tcx(tcx);
// We need this to prevent a `panic` when this function is used from intra doc links...
if !cstore.has_crate_data(def_id.krate) {
- debug!("No data for crate {}", crate_name);
+ debug!("No data for crate {crate_name}");
return Err(HrefError::NotInExternalCache);
}
// Check to see if it is a macro 2.0 or built-in macro.
// More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
- let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
+ let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx) {
LoadedMacro::MacroDef(def, _) => {
// If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
@@ -631,19 +635,18 @@ fn generate_macro_def_id_path(
let url = match cache.extern_locations[&def_id.krate] {
ExternalLocation::Remote(ref s) => {
// `ExternalLocation::Remote` always end with a `/`.
- format!("{}{}", s, path.iter().map(|p| p.as_str()).join("/"))
+ format!("{s}{path}", path = path.iter().map(|p| p.as_str()).join("/"))
}
ExternalLocation::Local => {
// `root_path` always end with a `/`.
format!(
- "{}{}/{}",
- root_path.unwrap_or(""),
- crate_name,
- path.iter().map(|p| p.as_str()).join("/")
+ "{root_path}{crate_name}/{path}",
+ root_path = root_path.unwrap_or(""),
+ path = path.iter().map(|p| p.as_str()).join("/")
)
}
ExternalLocation::Unknown => {
- debug!("crate {} not in cache when linkifying macros", crate_name);
+ debug!("crate {crate_name} not in cache when linkifying macros");
return Err(HrefError::NotInExternalCache);
}
};
@@ -662,6 +665,14 @@ pub(crate) fn href_with_root_path(
// documented on their parent's page
tcx.parent(did)
}
+ DefKind::ExternCrate => {
+ // Link to the crate itself, not the `extern crate` item.
+ if let Some(local_did) = did.as_local() {
+ tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
+ } else {
+ did
+ }
+ }
_ => did,
};
let cache = cx.cache();
@@ -724,7 +735,7 @@ pub(crate) fn href_with_root_path(
_ => {
let prefix = shortty.as_str();
let last = fqp.last().unwrap();
- url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
+ url_parts.push_fmt(format_args!("{prefix}.{last}.html"));
}
}
Ok((url_parts.finish(), shortty, fqp.to_vec()))
@@ -771,9 +782,10 @@ pub(crate) fn href_relative_parts<'fqp>(
pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Context<'_>) -> String {
let cache = cx.cache();
- let Some((fqp, shortty)) = cache.paths.get(&did)
- .or_else(|| cache.external_paths.get(&did))
- else { return String::new() };
+ let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did))
+ else {
+ return String::new();
+ };
let mut buf = Buffer::new();
let fqp = if *shortty == ItemType::Primitive {
// primitives are documented in a crate, but not actually part of it
@@ -819,9 +831,9 @@ fn resolved_path<'cx>(
let path = if use_absolute {
if let Ok((_, _, fqp)) = href(did, cx) {
format!(
- "{}::{}",
- join_with_double_colon(&fqp[..fqp.len() - 1]),
- anchor(did, *fqp.last().unwrap(), cx)
+ "{path}::{anchor}",
+ path = join_with_double_colon(&fqp[..fqp.len() - 1]),
+ anchor = anchor(did, *fqp.last().unwrap(), cx)
)
} else {
last.name.to_string()
@@ -829,7 +841,7 @@ fn resolved_path<'cx>(
} else {
anchor(did, last.name, cx).to_string()
};
- write!(w, "{}{}", path, last.args.print(cx))?;
+ write!(w, "{path}{args}", args = last.args.print(cx))?;
}
Ok(())
}
@@ -897,7 +909,7 @@ fn primitive_link_fragment(
None => {}
}
}
- write!(f, "{}", name)?;
+ f.write_str(name)?;
if needs_termination {
write!(f, "</a>")?;
}
@@ -937,15 +949,11 @@ pub(crate) fn anchor<'a, 'cx: 'a>(
if let Ok((url, short_ty, fqp)) = parts {
write!(
f,
- r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
- short_ty,
- url,
- short_ty,
- join_with_double_colon(&fqp),
- text.as_str()
+ r#"<a class="{short_ty}" href="{url}" title="{short_ty} {path}">{text}</a>"#,
+ path = join_with_double_colon(&fqp),
)
} else {
- write!(f, "{}", text)
+ f.write_str(text.as_str())
}
})
}
@@ -956,10 +964,10 @@ fn fmt_type<'cx>(
use_absolute: bool,
cx: &'cx Context<'_>,
) -> fmt::Result {
- trace!("fmt_type(t = {:?})", t);
+ trace!("fmt_type(t = {t:?})");
match *t {
- clean::Generic(name) => write!(f, "{}", name),
+ clean::Generic(name) => f.write_str(name.as_str()),
clean::Type::Path { ref path } => {
// Paths like `T::Output` and `Self::Output` should be rendered with all segments.
let did = path.def_id();
@@ -1076,13 +1084,13 @@ fn fmt_type<'cx>(
if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
let text = if f.alternate() {
- format!("*{} {:#}", m, t.print(cx))
+ format!("*{m} {ty:#}", ty = t.print(cx))
} else {
- format!("*{} {}", m, t.print(cx))
+ format!("*{m} {ty}", ty = t.print(cx))
};
primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
} else {
- primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
+ primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{m} "), cx)?;
fmt::Display::fmt(&t.print(cx), f)
}
}
@@ -1093,22 +1101,35 @@ fn fmt_type<'cx>(
};
let m = mutability.print_with_space();
let amp = if f.alternate() { "&" } else { "&amp;" };
- match **ty {
+
+ if let clean::Generic(name) = **ty {
+ return primitive_link(
+ f,
+ PrimitiveType::Reference,
+ &format!("{amp}{lt}{m}{name}"),
+ cx,
+ );
+ }
+
+ write!(f, "{amp}{lt}{m}")?;
+
+ let needs_parens = match **ty {
clean::DynTrait(ref bounds, ref trait_lt)
if bounds.len() > 1 || trait_lt.is_some() =>
{
- write!(f, "{}{}{}(", amp, lt, m)?;
- fmt_type(ty, f, use_absolute, cx)?;
- write!(f, ")")
- }
- clean::Generic(name) => {
- primitive_link(f, PrimitiveType::Reference, &format!("{amp}{lt}{m}{name}"), cx)
- }
- _ => {
- write!(f, "{}{}{}", amp, lt, m)?;
- fmt_type(ty, f, use_absolute, cx)
+ true
}
+ clean::ImplTrait(ref bounds) if bounds.len() > 1 => true,
+ _ => false,
+ };
+ if needs_parens {
+ f.write_str("(")?;
+ }
+ fmt_type(ty, f, use_absolute, cx)?;
+ if needs_parens {
+ f.write_str(")")?;
}
+ Ok(())
}
clean::ImplTrait(ref bounds) => {
if f.alternate() {
@@ -1423,11 +1444,20 @@ impl clean::FnDecl {
clean::SelfValue => {
write!(f, "self")?;
}
- clean::SelfBorrowed(Some(ref lt), mtbl) => {
- write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?;
+ clean::SelfBorrowed(Some(ref lt), mutability) => {
+ write!(
+ f,
+ "{amp}{lifetime} {mutability}self",
+ lifetime = lt.print(),
+ mutability = mutability.print_with_space(),
+ )?;
}
- clean::SelfBorrowed(None, mtbl) => {
- write!(f, "{}{}self", amp, mtbl.print_with_space())?;
+ clean::SelfBorrowed(None, mutability) => {
+ write!(
+ f,
+ "{amp}{mutability}self",
+ mutability = mutability.print_with_space(),
+ )?;
}
clean::SelfExplicit(ref typ) => {
write!(f, "self: ")?;
@@ -1501,7 +1531,7 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
"pub(super) ".into()
} else {
let path = cx.tcx().def_path(vis_did);
- debug!("path={:?}", path);
+ debug!("path={path:?}");
// modified from `resolved_path()` to work with `DefPathData`
let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
let anchor = anchor(vis_did, last_name, cx);
@@ -1510,12 +1540,12 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
for seg in &path.data[..path.data.len() - 1] {
let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
}
- let _ = write!(s, "{}) ", anchor);
+ let _ = write!(s, "{anchor}) ");
s.into()
}
}
};
- display_fn(move |f| write!(f, "{}", to_print))
+ display_fn(move |f| f.write_str(&to_print))
}
/// This function is the same as print_with_space, except that it renders no links.
@@ -1610,7 +1640,7 @@ impl clean::Import {
if name == self.source.path.last() {
write!(f, "use {};", self.source.print(cx))
} else {
- write!(f, "use {} as {};", self.source.print(cx), name)
+ write!(f, "use {source} as {name};", source = self.source.print(cx))
}
}
clean::ImportKind::Glob => {
@@ -1639,7 +1669,7 @@ impl clean::ImportSource {
if let hir::def::Res::PrimTy(p) = self.path.res {
primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
} else {
- write!(f, "{}", name)?;
+ f.write_str(name.as_str())?;
}
Ok(())
}
diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs
index c94968b48..039e8cdb9 100644
--- a/src/librustdoc/html/highlight.rs
+++ b/src/librustdoc/html/highlight.rs
@@ -928,18 +928,16 @@ fn string_without_closing_tag<T: Display>(
href_context: &Option<HrefContext<'_, '_>>,
open_tag: bool,
) -> Option<&'static str> {
- let Some(klass) = klass
- else {
- write!(out, "{}", text).unwrap();
+ let Some(klass) = klass else {
+ write!(out, "{text}").unwrap();
return None;
};
- let Some(def_span) = klass.get_span()
- else {
+ let Some(def_span) = klass.get_span() else {
if !open_tag {
- write!(out, "{}", text).unwrap();
+ write!(out, "{text}").unwrap();
return None;
}
- write!(out, "<span class=\"{}\">{}", klass.as_html(), text).unwrap();
+ write!(out, "<span class=\"{klass}\">{text}", klass = klass.as_html()).unwrap();
return Some("</span>");
};
@@ -949,14 +947,17 @@ fn string_without_closing_tag<T: Display>(
match t {
"self" | "Self" => write!(
&mut path,
- "<span class=\"{}\">{}</span>",
- Class::Self_(DUMMY_SP).as_html(),
- t
+ "<span class=\"{klass}\">{t}</span>",
+ klass = Class::Self_(DUMMY_SP).as_html(),
),
"crate" | "super" => {
- write!(&mut path, "<span class=\"{}\">{}</span>", Class::KeyWord.as_html(), t)
+ write!(
+ &mut path,
+ "<span class=\"{klass}\">{t}</span>",
+ klass = Class::KeyWord.as_html(),
+ )
}
- t => write!(&mut path, "{}", t),
+ t => write!(&mut path, "{t}"),
}
.expect("Failed to build source HTML path");
path
@@ -988,19 +989,24 @@ fn string_without_closing_tag<T: Display>(
)
.ok()
.map(|(url, _, _)| url),
+ LinkFromSrc::Doc(def_id) => {
+ format::href_with_root_path(*def_id, context, Some(&href_context.root_path))
+ .ok()
+ .map(|(doc_link, _, _)| doc_link)
+ }
}
})
{
if !open_tag {
// We're already inside an element which has the same klass, no need to give it
// again.
- write!(out, "<a href=\"{}\">{}", href, text_s).unwrap();
+ write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else {
let klass_s = klass.as_html();
if klass_s.is_empty() {
- write!(out, "<a href=\"{}\">{}", href, text_s).unwrap();
+ write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else {
- write!(out, "<a class=\"{}\" href=\"{}\">{}", klass_s, href, text_s).unwrap();
+ write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
}
}
return Some("</a>");
@@ -1015,7 +1021,7 @@ fn string_without_closing_tag<T: Display>(
out.write_str(&text_s).unwrap();
Some("")
} else {
- write!(out, "<span class=\"{}\">{}", klass_s, text_s).unwrap();
+ write!(out, "<span class=\"{klass_s}\">{text_s}").unwrap();
Some("</span>")
}
}
diff --git a/src/librustdoc/html/highlight/tests.rs b/src/librustdoc/html/highlight/tests.rs
index 2c93b9a09..4c0874a68 100644
--- a/src/librustdoc/html/highlight/tests.rs
+++ b/src/librustdoc/html/highlight/tests.rs
@@ -23,7 +23,7 @@ fn test_html_highlighting() {
let html = {
let mut out = Buffer::new();
write_code(&mut out, src, None, None);
- format!("{}<pre><code>{}</code></pre>\n", STYLE, out.into_inner())
+ format!("{STYLE}<pre><code>{}</code></pre>\n", out.into_inner())
};
expect_file!["fixtures/sample.html"].assert_eq(&html);
});
diff --git a/src/librustdoc/html/length_limit.rs b/src/librustdoc/html/length_limit.rs
index 4c8db2c67..8562e103d 100644
--- a/src/librustdoc/html/length_limit.rs
+++ b/src/librustdoc/html/length_limit.rs
@@ -78,8 +78,7 @@ impl HtmlWithLimit {
pub(super) fn open_tag(&mut self, tag_name: &'static str) {
assert!(
tag_name.chars().all(|c| ('a'..='z').contains(&c)),
- "tag_name contained non-alphabetic chars: {:?}",
- tag_name
+ "tag_name contained non-alphabetic chars: {tag_name:?}",
);
self.queued_tags.push(tag_name);
}
@@ -88,7 +87,7 @@ impl HtmlWithLimit {
pub(super) fn close_tag(&mut self) {
match self.unclosed_tags.pop() {
// Close the most recently opened tag.
- Some(tag_name) => write!(self.buf, "</{}>", tag_name).unwrap(),
+ Some(tag_name) => write!(self.buf, "</{tag_name}>").unwrap(),
// There are valid cases where `close_tag()` is called without
// there being any tags to close. For example, this occurs when
// a tag is opened after the length limit is exceeded;
@@ -101,7 +100,7 @@ impl HtmlWithLimit {
/// Write all queued tags and add them to the `unclosed_tags` list.
fn flush_queue(&mut self) {
for tag_name in self.queued_tags.drain(..) {
- write!(self.buf, "<{}>", tag_name).unwrap();
+ write!(self.buf, "<{tag_name}>").unwrap();
self.unclosed_tags.push(tag_name);
}
diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs
index fd00277e2..98cc38a10 100644
--- a/src/librustdoc/html/markdown.rs
+++ b/src/librustdoc/html/markdown.rs
@@ -50,7 +50,7 @@ use crate::html::render::small_url_encode;
use crate::html::toc::TocBuilder;
use pulldown_cmark::{
- html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
+ html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, OffsetIter, Options, Parser, Tag,
};
#[cfg(test)]
@@ -246,10 +246,9 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
return Some(Event::Html(
format!(
"<div class=\"example-wrap\">\
- <pre class=\"language-{}\"><code>{}</code></pre>\
+ <pre class=\"language-{lang}\"><code>{text}</code></pre>\
</div>",
- lang,
- Escape(&original_text),
+ text = Escape(&original_text),
)
.into(),
));
@@ -288,8 +287,9 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
let test_escaped = small_url_encode(test);
Some(format!(
- r#"<a class="test-arrow" target="_blank" href="{}?code={}{}&amp;edition={}">Run</a>"#,
- url, test_escaped, channel, edition,
+ "<a class=\"test-arrow\" \
+ target=\"_blank\" \
+ href=\"{url}?code={test_escaped}{channel}&amp;edition={edition}\">Run</a>",
))
});
@@ -308,7 +308,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
// insert newline to clearly separate it from the
// previous block so we can shorten the html output
let mut s = Buffer::new();
- s.push_str("\n");
+ s.push('\n');
highlight::render_example_with_highlighting(
&text,
@@ -349,7 +349,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
dest,
title,
))) => {
- debug!("saw start of shortcut link to {} with title {}", dest, title);
+ debug!("saw start of shortcut link to {dest} with title {title}");
// If this is a shortcut link, it was resolved by the broken_link_callback.
// So the URL will already be updated properly.
let link = self.links.iter().find(|&link| *link.href == **dest);
@@ -370,7 +370,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
dest,
_,
))) => {
- debug!("saw end of shortcut link to {}", dest);
+ debug!("saw end of shortcut link to {dest}");
if self.links.iter().any(|link| *link.href == **dest) {
assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
self.shortcut_link = None;
@@ -379,7 +379,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
// Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
// [`fn@f`]
Some(Event::Code(text)) => {
- trace!("saw code {}", text);
+ trace!("saw code {text}");
if let Some(link) = self.shortcut_link {
// NOTE: this only replaces if the code block is the *entire* text.
// If only part of the link has code highlighting, the disambiguator will not be removed.
@@ -394,7 +394,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
l.href == link.href
&& Some(&**text) == l.original_text.get(1..l.original_text.len() - 1)
}) {
- debug!("replacing {} with {}", text, link.new_text);
+ debug!("replacing {text} with {new_text}", new_text = link.new_text);
*text = CowStr::Borrowed(&link.new_text);
}
}
@@ -402,7 +402,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
// Replace plain text in links, but only in the middle of a shortcut link.
// [fn@f]
Some(Event::Text(text)) => {
- trace!("saw text {}", text);
+ trace!("saw text {text}");
if let Some(link) = self.shortcut_link {
// NOTE: same limitations as `Event::Code`
if let Some(link) = self
@@ -410,7 +410,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
.iter()
.find(|l| l.href == link.href && **text == *l.original_text)
{
- debug!("replacing {} with {}", text, link.new_text);
+ debug!("replacing {text} with {new_text}", new_text = link.new_text);
*text = CowStr::Borrowed(&link.new_text);
}
}
@@ -522,18 +522,16 @@ impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
let mut html_header = String::new();
html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
let sec = builder.push(level as u32, html_header, id.clone());
- self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0));
+ self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0));
}
let level =
std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL);
- self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0));
+ self.buf.push_back((Event::Html(format!("</a></h{level}>").into()), 0..0));
let start_tags = format!(
"<h{level} id=\"{id}\">\
<a href=\"#{id}\">",
- id = id,
- level = level
);
return Some((Event::Html(start_tags.into()), 0..0));
}
@@ -683,14 +681,14 @@ impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
v.sort_by(|a, b| a.1.cmp(&b.1));
let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
for (mut content, id) in v {
- write!(ret, "<li id=\"fn{}\">", id).unwrap();
+ write!(ret, "<li id=\"fn{id}\">").unwrap();
let mut is_paragraph = false;
if let Some(&Event::End(Tag::Paragraph)) = content.last() {
content.pop();
is_paragraph = true;
}
html::push_html(&mut ret, content.into_iter());
- write!(ret, "&nbsp;<a href=\"#fnref{}\">↩</a>", id).unwrap();
+ write!(ret, "&nbsp;<a href=\"#fnref{id}\">↩</a>").unwrap();
if is_paragraph {
ret.push_str("</p>");
}
@@ -961,7 +959,7 @@ impl LangString {
} {
if let Some(extra) = extra {
extra.error_invalid_codeblock_attr(
- format!("unknown attribute `{}`. Did you mean `{}`?", x, flag),
+ format!("unknown attribute `{x}`. Did you mean `{flag}`?"),
help,
);
}
@@ -1040,7 +1038,7 @@ impl MarkdownWithToc<'_> {
html::push_html(&mut s, p);
}
- format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s)
+ format!("<nav id=\"TOC\">{toc}</nav>{s}", toc = toc.into_toc().print())
}
}
@@ -1242,6 +1240,7 @@ pub(crate) fn plain_text_summary(md: &str, link_names: &[RenderedLink]) -> Strin
pub(crate) struct MarkdownLink {
pub kind: LinkType,
pub link: String,
+ pub display_text: Option<String>,
pub range: MarkdownLinkRange,
}
@@ -1265,8 +1264,8 @@ impl MarkdownLinkRange {
}
}
-pub(crate) fn markdown_links<R>(
- md: &str,
+pub(crate) fn markdown_links<'md, R>(
+ md: &'md str,
preprocess_link: impl Fn(MarkdownLink) -> Option<R>,
) -> Vec<R> {
if md.is_empty() {
@@ -1377,32 +1376,90 @@ pub(crate) fn markdown_links<R>(
MarkdownLinkRange::Destination(range.clone())
};
- Parser::new_with_broken_link_callback(
+ let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into()));
+ let mut event_iter = Parser::new_with_broken_link_callback(
md,
main_body_opts(),
- Some(&mut |link: BrokenLink<'_>| Some((link.reference, "".into()))),
+ Some(&mut broken_link_callback),
)
- .into_offset_iter()
- .filter_map(|(event, span)| match event {
- Event::Start(Tag::Link(link_type, dest, _)) if may_be_doc_link(link_type) => {
- let range = match link_type {
- // Link is pulled from the link itself.
- LinkType::ReferenceUnknown | LinkType::ShortcutUnknown => {
- span_for_offset_backward(span, b'[', b']')
- }
- LinkType::CollapsedUnknown => span_for_offset_forward(span, b'[', b']'),
- LinkType::Inline => span_for_offset_backward(span, b'(', b')'),
- // Link is pulled from elsewhere in the document.
- LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut => {
- span_for_link(&dest, span)
+ .into_offset_iter();
+ let mut links = Vec::new();
+
+ while let Some((event, span)) = event_iter.next() {
+ match event {
+ Event::Start(Tag::Link(link_type, dest, _)) if may_be_doc_link(link_type) => {
+ let range = match link_type {
+ // Link is pulled from the link itself.
+ LinkType::ReferenceUnknown | LinkType::ShortcutUnknown => {
+ span_for_offset_backward(span, b'[', b']')
+ }
+ LinkType::CollapsedUnknown => span_for_offset_forward(span, b'[', b']'),
+ LinkType::Inline => span_for_offset_backward(span, b'(', b')'),
+ // Link is pulled from elsewhere in the document.
+ LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut => {
+ span_for_link(&dest, span)
+ }
+ LinkType::Autolink | LinkType::Email => unreachable!(),
+ };
+
+ let display_text = if matches!(
+ link_type,
+ LinkType::Inline
+ | LinkType::ReferenceUnknown
+ | LinkType::Reference
+ | LinkType::Shortcut
+ | LinkType::ShortcutUnknown
+ ) {
+ collect_link_data(&mut event_iter)
+ } else {
+ None
+ };
+
+ if let Some(link) = preprocess_link(MarkdownLink {
+ kind: link_type,
+ link: dest.into_string(),
+ display_text,
+ range,
+ }) {
+ links.push(link);
}
- LinkType::Autolink | LinkType::Email => unreachable!(),
- };
- preprocess_link(MarkdownLink { kind: link_type, range, link: dest.into_string() })
+ }
+ _ => {}
}
- _ => None,
- })
- .collect()
+ }
+
+ links
+}
+
+/// Collects additional data of link.
+fn collect_link_data<'input, 'callback>(
+ event_iter: &mut OffsetIter<'input, 'callback>,
+) -> Option<String> {
+ let mut display_text: Option<String> = None;
+ let mut append_text = |text: CowStr<'_>| {
+ if let Some(display_text) = &mut display_text {
+ display_text.push_str(&text);
+ } else {
+ display_text = Some(text.to_string());
+ }
+ };
+
+ while let Some((event, _span)) = event_iter.next() {
+ match event {
+ Event::Text(text) => {
+ append_text(text);
+ }
+ Event::Code(code) => {
+ append_text(code);
+ }
+ Event::End(_) => {
+ break;
+ }
+ _ => {}
+ }
+ }
+
+ display_text
}
#[derive(Debug)]
diff --git a/src/librustdoc/html/markdown/tests.rs b/src/librustdoc/html/markdown/tests.rs
index e05635a02..db8504d15 100644
--- a/src/librustdoc/html/markdown/tests.rs
+++ b/src/librustdoc/html/markdown/tests.rs
@@ -38,7 +38,7 @@ fn test_unique_id() {
];
let mut map = IdMap::new();
- let actual: Vec<String> = input.iter().map(|s| map.derive(s.to_string())).collect();
+ let actual: Vec<String> = input.iter().map(|s| map.derive(s)).collect();
assert_eq!(&actual[..], expected);
}
diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs
index 4c4762636..d7ff248a9 100644
--- a/src/librustdoc/html/render/context.rs
+++ b/src/librustdoc/html/render/context.rs
@@ -162,7 +162,7 @@ impl<'tcx> Context<'tcx> {
self.shared.tcx.sess
}
- pub(super) fn derive_id(&mut self, id: String) -> String {
+ pub(super) fn derive_id<S: AsRef<str> + ToString>(&mut self, id: S) -> String {
self.id_map.derive(id)
}
@@ -206,15 +206,14 @@ impl<'tcx> Context<'tcx> {
format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
} else {
format!(
- "API documentation for the Rust `{}` {} in crate `{}`.",
- it.name.as_ref().unwrap(),
- tyname,
- self.shared.layout.krate
+ "API documentation for the Rust `{name}` {tyname} in crate `{krate}`.",
+ name = it.name.as_ref().unwrap(),
+ krate = self.shared.layout.krate,
)
};
let name;
let tyname_s = if it.is_crate() {
- name = format!("{} crate", tyname);
+ name = format!("{tyname} crate");
name.as_str()
} else {
tyname.as_str()
@@ -264,7 +263,12 @@ impl<'tcx> Context<'tcx> {
current_path.push_str(&item_path(ty, names.last().unwrap().as_str()));
redirections.borrow_mut().insert(current_path, path);
}
- None => return layout::redirect(&format!("{}{}", self.root_path(), path)),
+ None => {
+ return layout::redirect(&format!(
+ "{root}{path}",
+ root = self.root_path()
+ ));
+ }
}
}
}
@@ -382,11 +386,7 @@ impl<'tcx> Context<'tcx> {
let hiline = span.hi(self.sess()).line;
format!(
"#{}",
- if loline == hiline {
- loline.to_string()
- } else {
- format!("{}-{}", loline, hiline)
- }
+ if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
)
} else {
"".to_string()
@@ -798,15 +798,18 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
if let Some(def_id) = item.def_id() && self.cache().inlined_items.contains(&def_id) {
self.is_inside_inlined_module = true;
}
- } else if item.is_doc_hidden() {
+ } else if !self.cache().document_hidden && item.is_doc_hidden() {
// We're not inside an inlined module anymore since this one cannot be re-exported.
self.is_inside_inlined_module = false;
}
// Render sidebar-items.js used throughout this module.
if !self.render_redirect_pages {
- let (clean::StrippedItem(box clean::ModuleItem(ref module)) | clean::ModuleItem(ref module)) = *item.kind
- else { unreachable!() };
+ let (clean::StrippedItem(box clean::ModuleItem(ref module))
+ | clean::ModuleItem(ref module)) = *item.kind
+ else {
+ unreachable!()
+ };
let items = self.build_sidebar_items(module);
let js_dst = self.dst.join(&format!("sidebar-items{}.js", self.shared.resource_suffix));
let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap());
@@ -852,12 +855,12 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
// If the item is a macro, redirect from the old macro URL (with !)
// to the new one (without).
if item_type == ItemType::Macro {
- let redir_name = format!("{}.{}!.html", item_type, name);
+ let redir_name = format!("{item_type}.{name}!.html");
if let Some(ref redirections) = self.shared.redirections {
let crate_name = &self.shared.layout.krate;
redirections.borrow_mut().insert(
- format!("{}/{}", crate_name, redir_name),
- format!("{}/{}", crate_name, file_name),
+ format!("{crate_name}/{redir_name}"),
+ format!("{crate_name}/{file_name}"),
);
} else {
let v = layout::redirect(file_name);
diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs
index f923f9054..ac9c180a6 100644
--- a/src/librustdoc/html/render/mod.rs
+++ b/src/librustdoc/html/render/mod.rs
@@ -85,7 +85,7 @@ use crate::DOC_RUST_LANG_ORG_CHANNEL;
pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
crate::html::format::display_fn(move |f| {
- if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
+ if !v.ends_with('/') && !v.is_empty() { write!(f, "{v}/") } else { f.write_str(v) }
})
}
@@ -268,7 +268,7 @@ impl AllTypes {
fn append(&mut self, item_name: String, item_type: &ItemType) {
let mut url: Vec<_> = item_name.split("::").skip(1).collect();
if let Some(name) = url.pop() {
- let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
+ let new_url = format!("{}/{item_type}.{name}.html", url.join("/"));
url.push(name);
let name = url.join("::");
match *item_type {
@@ -385,16 +385,17 @@ impl AllTypes {
fn scrape_examples_help(shared: &SharedContext<'_>) -> String {
let mut content = SCRAPE_EXAMPLES_HELP_MD.to_owned();
content.push_str(&format!(
- "## More information\n\n\
- If you want more information about this feature, please read the [corresponding chapter in the Rustdoc book]({}/rustdoc/scraped-examples.html).",
- DOC_RUST_LANG_ORG_CHANNEL));
+ "## More information\n\n\
+ If you want more information about this feature, please read the [corresponding chapter in \
+ the Rustdoc book]({DOC_RUST_LANG_ORG_CHANNEL}/rustdoc/scraped-examples.html)."
+ ));
let mut ids = IdMap::default();
format!(
"<div class=\"main-heading\">\
- <h1>About scraped examples</h1>\
- </div>\
- <div>{}</div>",
+ <h1>About scraped examples</h1>\
+ </div>\
+ <div>{}</div>",
Markdown {
content: &content,
links: &[],
@@ -415,7 +416,7 @@ fn document<'a, 'cx: 'a>(
heading_offset: HeadingOffset,
) -> impl fmt::Display + 'a + Captures<'cx> {
if let Some(ref name) = item.name {
- info!("Documenting {}", name);
+ info!("Documenting {name}");
}
display_fn(move |f| {
@@ -473,7 +474,7 @@ fn document_short<'a, 'cx: 'a>(
MarkdownSummaryLine(&s, &item.links(cx)).into_string_with_has_more_content();
if has_more_content {
- let link = format!(r#" <a{}>Read more</a>"#, assoc_href_attr(item, link, cx));
+ let link = format!(" <a{}>Read more</a>", assoc_href_attr(item, link, cx));
if let Some(idx) = summary_html.rfind("</p>") {
summary_html.insert_str(idx, &link);
@@ -482,7 +483,7 @@ fn document_short<'a, 'cx: 'a>(
}
}
- write!(f, "<div class='docblock'>{}</div>", summary_html)?;
+ write!(f, "<div class='docblock'>{summary_html}</div>")?;
}
Ok(())
})
@@ -512,14 +513,14 @@ fn document_full_inner<'a, 'cx: 'a>(
) -> impl fmt::Display + 'a + Captures<'cx> {
display_fn(move |f| {
if let Some(s) = item.opt_doc_value() {
- debug!("Doc block: =====\n{}\n=====", s);
+ debug!("Doc block: =====\n{s}\n=====");
if is_collapsible {
write!(
f,
"<details class=\"toggle top-doc\" open>\
- <summary class=\"hideme\">\
+ <summary class=\"hideme\">\
<span>Expand description</span>\
- </summary>{}</details>",
+ </summary>{}</details>",
render_markdown(cx, &s, item.links(cx), heading_offset)
)?;
} else {
@@ -564,12 +565,10 @@ fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<Strin
};
debug!(
- "Portability {:?} {:?} (parent: {:?}) - {:?} = {:?}",
- item.name,
- item.cfg,
- parent,
- parent.and_then(|p| p.cfg.as_ref()),
- cfg
+ "Portability {name:?} {item_cfg:?} (parent: {parent:?}) - {parent_cfg:?} = {cfg:?}",
+ name = item.name,
+ item_cfg = item.cfg,
+ parent_cfg = parent.and_then(|p| p.cfg.as_ref()),
);
Some(cfg?.render_long_html())
@@ -701,8 +700,8 @@ fn assoc_href_attr(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>)
let item_type = it.type_();
let href = match link {
- AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
- AssocItemLink::Anchor(None) => Some(format!("#{}.{}", item_type, name)),
+ AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{id}")),
+ AssocItemLink::Anchor(None) => Some(format!("#{item_type}.{name}")),
AssocItemLink::GotoSource(did, provided_methods) => {
// We're creating a link from the implementation of an associated item to its
// declaration in the trait declaration.
@@ -722,7 +721,7 @@ fn assoc_href_attr(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>)
};
match href(did.expect_def_id(), cx) {
- Ok((url, ..)) => Some(format!("{}#{}.{}", url, item_type, name)),
+ Ok((url, ..)) => Some(format!("{url}#{item_type}.{name}")),
// The link is broken since it points to an external crate that wasn't documented.
// Do not create any link in such case. This is better than falling back to a
// dummy anchor like `#{item_type}.{name}` representing the `id` of *this* impl item
@@ -735,37 +734,39 @@ fn assoc_href_attr(it: &clean::Item, link: AssocItemLink<'_>, cx: &Context<'_>)
// In this scenario, the actual `id` of this impl item would be
// `#{item_type}.{name}-{n}` for some number `n` (a disambiguator).
Err(HrefError::DocumentationNotBuilt) => None,
- Err(_) => Some(format!("#{}.{}", item_type, name)),
+ Err(_) => Some(format!("#{item_type}.{name}")),
}
}
};
// If there is no `href` for the reason explained above, simply do not render it which is valid:
// https://html.spec.whatwg.org/multipage/links.html#links-created-by-a-and-area-elements
- href.map(|href| format!(" href=\"{}\"", href)).unwrap_or_default()
+ href.map(|href| format!(" href=\"{href}\"")).unwrap_or_default()
}
fn assoc_const(
w: &mut Buffer,
it: &clean::Item,
+ generics: &clean::Generics,
ty: &clean::Type,
default: Option<&clean::ConstantKind>,
link: AssocItemLink<'_>,
- extra: &str,
+ indent: usize,
cx: &Context<'_>,
) {
let tcx = cx.tcx();
write!(
w,
- "{extra}{vis}const <a{href} class=\"constant\">{name}</a>: {ty}",
- extra = extra,
+ "{indent}{vis}const <a{href} class=\"constant\">{name}</a>{generics}: {ty}",
+ indent = " ".repeat(indent),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
href = assoc_href_attr(it, link, cx),
name = it.name.as_ref().unwrap(),
+ generics = generics.print(cx),
ty = ty.print(cx),
);
if let Some(default) = default {
- write!(w, " = ");
+ w.write_str(" = ");
// FIXME: `.value()` uses `clean::utils::format_integer_with_underscore_sep` under the
// hood which adds noisy underscores and a type suffix to number literals.
@@ -774,6 +775,7 @@ fn assoc_const(
// Find a way to print constants here without all that jazz.
write!(w, "{}", Escape(&default.value(tcx).unwrap_or_else(|| default.expr(tcx))));
}
+ write!(w, "{}", print_where_clause(generics, cx, indent, Ending::NoNewline));
}
fn assoc_type(
@@ -820,6 +822,7 @@ fn assoc_method(
let header = meth.fn_header(tcx).expect("Trying to get header from a non-function item");
let name = meth.name.as_ref().unwrap();
let vis = visibility_print_with_space(meth.visibility(tcx), meth.item_id, cx).to_string();
+ let defaultness = print_default_space(meth.is_default());
// FIXME: Once https://github.com/rust-lang/rust/issues/67792 is implemented, we can remove
// this condition.
let constness = match render_mode {
@@ -830,7 +833,6 @@ fn assoc_method(
};
let asyncness = header.asyncness.print_with_space();
let unsafety = header.unsafety.print_with_space();
- let defaultness = print_default_space(meth.is_default());
let abi = print_abi_with_space(header.abi).to_string();
let href = assoc_href_attr(meth, link, cx);
@@ -838,10 +840,10 @@ fn assoc_method(
let generics_len = format!("{:#}", g.print(cx)).len();
let mut header_len = "fn ".len()
+ vis.len()
+ + defaultness.len()
+ constness.len()
+ asyncness.len()
+ unsafety.len()
- + defaultness.len()
+ abi.len()
+ name.as_str().len()
+ generics_len;
@@ -860,14 +862,14 @@ fn assoc_method(
w.reserve(header_len + "<a href=\"\" class=\"fn\">{".len() + "</a>".len());
write!(
w,
- "{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn \
+ "{indent}{vis}{defaultness}{constness}{asyncness}{unsafety}{abi}fn \
<a{href} class=\"fn\">{name}</a>{generics}{decl}{notable_traits}{where_clause}",
indent = indent_str,
vis = vis,
+ defaultness = defaultness,
constness = constness,
asyncness = asyncness,
unsafety = unsafety,
- defaultness = defaultness,
abi = abi,
href = href,
name = name,
@@ -907,39 +909,41 @@ fn render_stability_since_raw_with_extra(
if let Some(ver) = stable_version {
stability.push_str(ver.as_str());
- title.push_str(&format!("Stable since Rust version {}", ver));
+ title.push_str(&format!("Stable since Rust version {ver}"));
}
let const_title_and_stability = match const_stability {
Some(ConstStability { level: StabilityLevel::Stable { since, .. }, .. })
if Some(since) != containing_const_ver =>
{
- Some((format!("const since {}", since), format!("const: {}", since)))
+ Some((format!("const since {since}"), format!("const: {since}")))
}
Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }) => {
let unstable = if let Some(n) = issue {
format!(
- r#"<a href="https://github.com/rust-lang/rust/issues/{}" title="Tracking issue for {}">unstable</a>"#,
- n, feature
+ "<a \
+ href=\"https://github.com/rust-lang/rust/issues/{n}\" \
+ title=\"Tracking issue for {feature}\"\
+ >unstable</a>"
)
} else {
String::from("unstable")
};
- Some((String::from("const unstable"), format!("const: {}", unstable)))
+ Some((String::from("const unstable"), format!("const: {unstable}")))
}
_ => None,
};
if let Some((const_title, const_stability)) = const_title_and_stability {
if !title.is_empty() {
- title.push_str(&format!(", {}", const_title));
+ title.push_str(&format!(", {const_title}"));
} else {
title.push_str(&const_title);
}
if !stability.is_empty() {
- stability.push_str(&format!(" ({})", const_stability));
+ stability.push_str(&format!(" ({const_stability})"));
} else {
stability.push_str(&const_stability);
}
@@ -986,19 +990,22 @@ fn render_assoc_item(
clean::MethodItem(m, _) => {
assoc_method(w, item, &m.generics, &m.decl, link, parent, cx, render_mode)
}
- kind @ (clean::TyAssocConstItem(ty) | clean::AssocConstItem(ty, _)) => assoc_const(
- w,
- item,
- ty,
- match kind {
- clean::TyAssocConstItem(_) => None,
- clean::AssocConstItem(_, default) => Some(default),
- _ => unreachable!(),
- },
- link,
- if parent == ItemType::Trait { " " } else { "" },
- cx,
- ),
+ kind @ (clean::TyAssocConstItem(generics, ty) | clean::AssocConstItem(generics, ty, _)) => {
+ assoc_const(
+ w,
+ item,
+ generics,
+ ty,
+ match kind {
+ clean::TyAssocConstItem(..) => None,
+ clean::AssocConstItem(.., default) => Some(default),
+ _ => unreachable!(),
+ },
+ link,
+ if parent == ItemType::Trait { 4 } else { 0 },
+ cx,
+ )
+ }
clean::TyAssocTypeItem(ref generics, ref bounds) => assoc_type(
w,
item,
@@ -1032,7 +1039,7 @@ fn render_attributes_in_pre<'a, 'b: 'a>(
) -> impl fmt::Display + Captures<'a> + Captures<'b> {
crate::html::format::display_fn(move |f| {
for a in it.attributes(tcx, false) {
- writeln!(f, "{}{}", prefix, a)?;
+ writeln!(f, "{prefix}{a}")?;
}
Ok(())
})
@@ -1085,7 +1092,7 @@ pub(crate) fn render_all_impls(
let impls = impls.into_inner();
if !impls.is_empty() {
write_impl_section_heading(&mut w, "Trait Implementations", "trait-implementations");
- write!(w, "<div id=\"trait-implementations-list\">{}</div>", impls).unwrap();
+ write!(w, "<div id=\"trait-implementations-list\">{impls}</div>").unwrap();
}
if !synthetic.is_empty() {
@@ -1144,9 +1151,7 @@ fn render_assoc_items_inner(
AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
let id =
cx.derive_id(small_url_encode(format!("deref-methods-{:#}", type_.print(cx))));
- if let Some(def_id) = type_.def_id(cx.cache()) {
- cx.deref_id_map.insert(def_id, id.clone());
- }
+ let derived_id = cx.derive_id(&id);
write_impl_section_heading(
&mut tmp_buf,
&format!(
@@ -1156,11 +1161,10 @@ fn render_assoc_items_inner(
),
&id,
);
- (
- RenderMode::ForDeref { mut_: deref_mut_ },
- cx.derive_id(id),
- r#" class="impl-items""#,
- )
+ if let Some(def_id) = type_.def_id(cx.cache()) {
+ cx.deref_id_map.insert(def_id, id);
+ }
+ (RenderMode::ForDeref { mut_: deref_mut_ }, derived_id, r#" class="impl-items""#)
}
};
let mut impls_buf = Buffer::html();
@@ -1183,10 +1187,13 @@ fn render_assoc_items_inner(
);
}
if !impls_buf.is_empty() {
- write!(w, "{}", tmp_buf.into_inner()).unwrap();
- write!(w, "<div id=\"{id}\"{class_html}>").unwrap();
- write!(w, "{}", impls_buf.into_inner()).unwrap();
- w.write_str("</div>").unwrap();
+ write!(
+ w,
+ "{}<div id=\"{id}\"{class_html}>{}</div>",
+ tmp_buf.into_inner(),
+ impls_buf.into_inner()
+ )
+ .unwrap();
}
}
@@ -1236,7 +1243,10 @@ fn render_deref_methods(
_ => None,
})
.expect("Expected associated type binding");
- debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
+ debug!(
+ "Render deref methods for {for_:#?}, target {target:#?}",
+ for_ = impl_.inner_impl().for_
+ );
let what =
AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
if let Some(did) = target.def_id(cache) {
@@ -1386,7 +1396,7 @@ fn notable_traits_decl(ty: &clean::Type, cx: &Context<'_>) -> (String, String) {
}
}
if out.is_empty() {
- write!(&mut out, "</code></pre>",);
+ out.write_str("</code></pre>");
}
(format!("{:#}", ty.print(cx)), out.into_inner())
@@ -1532,25 +1542,25 @@ fn render_impl(
let toggled = !doc_buffer.is_empty();
if toggled {
let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
- write!(w, "<details class=\"toggle{}\" open><summary>", method_toggle_class);
+ write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
}
match &*item.kind {
clean::MethodItem(..) | clean::TyMethodItem(_) => {
// Only render when the method is not static or we allow static methods
if render_method_item {
- let id = cx.derive_id(format!("{}.{}", item_type, name));
+ let id = cx.derive_id(format!("{item_type}.{name}"));
let source_id = trait_
.and_then(|trait_| {
trait_.items.iter().find(|item| {
item.name.map(|n| n.as_str().eq(name.as_str())).unwrap_or(false)
})
})
- .map(|item| format!("{}.{}", item.type_(), name));
- write!(w, "<section id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class,);
+ .map(|item| format!("{}.{name}", item.type_()));
+ write!(w, "<section id=\"{id}\" class=\"{item_type}{in_trait_class}\">");
render_rightside(w, cx, item, containing_item, render_mode);
if trait_.is_some() {
// Anchors are only used on trait impls.
- write!(w, "<a href=\"#{}\" class=\"anchor\">§</a>", id);
+ write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>");
}
w.write_str("<h4 class=\"code-header\">");
render_assoc_item(
@@ -1561,43 +1571,43 @@ fn render_impl(
cx,
render_mode,
);
- w.write_str("</h4>");
- w.write_str("</section>");
+ w.write_str("</h4></section>");
}
}
- kind @ (clean::TyAssocConstItem(ty) | clean::AssocConstItem(ty, _)) => {
- let source_id = format!("{}.{}", item_type, name);
- let id = cx.derive_id(source_id.clone());
- write!(w, "<section id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class);
+ kind @ (clean::TyAssocConstItem(generics, ty)
+ | clean::AssocConstItem(generics, ty, _)) => {
+ let source_id = format!("{item_type}.{name}");
+ let id = cx.derive_id(&source_id);
+ write!(w, "<section id=\"{id}\" class=\"{item_type}{in_trait_class}\">");
render_rightside(w, cx, item, containing_item, render_mode);
if trait_.is_some() {
// Anchors are only used on trait impls.
- write!(w, "<a href=\"#{}\" class=\"anchor\">§</a>", id);
+ write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>");
}
w.write_str("<h4 class=\"code-header\">");
assoc_const(
w,
item,
+ generics,
ty,
match kind {
- clean::TyAssocConstItem(_) => None,
- clean::AssocConstItem(_, default) => Some(default),
+ clean::TyAssocConstItem(..) => None,
+ clean::AssocConstItem(.., default) => Some(default),
_ => unreachable!(),
},
link.anchor(if trait_.is_some() { &source_id } else { &id }),
- "",
+ 0,
cx,
);
- w.write_str("</h4>");
- w.write_str("</section>");
+ w.write_str("</h4></section>");
}
clean::TyAssocTypeItem(generics, bounds) => {
- let source_id = format!("{}.{}", item_type, name);
- let id = cx.derive_id(source_id.clone());
- write!(w, "<section id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class);
+ let source_id = format!("{item_type}.{name}");
+ let id = cx.derive_id(&source_id);
+ write!(w, "<section id=\"{id}\" class=\"{item_type}{in_trait_class}\">");
if trait_.is_some() {
// Anchors are only used on trait impls.
- write!(w, "<a href=\"#{}\" class=\"anchor\">§</a>", id);
+ write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>");
}
w.write_str("<h4 class=\"code-header\">");
assoc_type(
@@ -1610,16 +1620,15 @@ fn render_impl(
0,
cx,
);
- w.write_str("</h4>");
- w.write_str("</section>");
+ w.write_str("</h4></section>");
}
clean::AssocTypeItem(tydef, _bounds) => {
- let source_id = format!("{}.{}", item_type, name);
- let id = cx.derive_id(source_id.clone());
- write!(w, "<section id=\"{}\" class=\"{}{}\">", id, item_type, in_trait_class);
+ let source_id = format!("{item_type}.{name}");
+ let id = cx.derive_id(&source_id);
+ write!(w, "<section id=\"{id}\" class=\"{item_type}{in_trait_class}\">");
if trait_.is_some() {
// Anchors are only used on trait impls.
- write!(w, "<a href=\"#{}\" class=\"anchor\">§</a>", id);
+ write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>");
}
w.write_str("<h4 class=\"code-header\">");
assoc_type(
@@ -1632,8 +1641,7 @@ fn render_impl(
0,
cx,
);
- w.write_str("</h4>");
- w.write_str("</section>");
+ w.write_str("</h4></section>");
}
clean::StrippedItem(..) => return,
_ => panic!("can't make docs for trait item with name {:?}", item.name),
@@ -1678,11 +1686,11 @@ fn render_impl(
rendering_params: ImplRenderingParameters,
) {
for trait_item in &t.items {
- // Skip over any default trait items that are impossible to call
+ // Skip over any default trait items that are impossible to reference
// (e.g. if it has a `Self: Sized` bound on an unsized type).
if let Some(impl_def_id) = parent.item_id.as_def_id()
&& let Some(trait_item_def_id) = trait_item.item_id.as_def_id()
- && cx.tcx().is_impossible_method((impl_def_id, trait_item_def_id))
+ && cx.tcx().is_impossible_associated_item((impl_def_id, trait_item_def_id))
{
continue;
}
@@ -1736,10 +1744,10 @@ fn render_impl(
close_tags.insert_str(0, "</details>");
write!(
w,
- "<details class=\"toggle implementors-toggle\"{}>",
+ "<details class=\"toggle implementors-toggle\"{}>\
+ <summary>",
if rendering_params.toggle_open_by_default { " open" } else { "" }
);
- write!(w, "<summary>")
}
render_impl_summary(
w,
@@ -1752,15 +1760,15 @@ fn render_impl(
aliases,
);
if toggled {
- write!(w, "</summary>")
+ w.write_str("</summary>");
}
if let Some(ref dox) = i.impl_item.opt_doc_value() {
if trait_.is_none() && i.inner_impl().items.is_empty() {
w.write_str(
"<div class=\"item-info\">\
- <div class=\"stab empty-impl\">This impl block contains no items.</div>\
- </div>",
+ <div class=\"stab empty-impl\">This impl block contains no items.</div>\
+ </div>",
);
}
write!(
@@ -1819,11 +1827,11 @@ fn render_rightside(
const_stable_since,
if has_src_ref { "" } else { " rightside" },
);
- if let Some(l) = src_href {
+ if let Some(link) = src_href {
if has_stability {
- write!(rightside, " · <a class=\"srclink\" href=\"{}\">source</a>", l)
+ write!(rightside, " · <a class=\"src\" href=\"{link}\">source</a>")
} else {
- write!(rightside, "<a class=\"srclink rightside\" href=\"{}\">source</a>", l)
+ write!(rightside, "<a class=\"src rightside\" href=\"{link}\">source</a>")
}
}
if has_stability && has_src_ref {
@@ -1852,10 +1860,13 @@ pub(crate) fn render_impl_summary(
} else {
format!(" data-aliases=\"{}\"", aliases.join(","))
};
- write!(w, "<section id=\"{}\" class=\"impl\"{}>", id, aliases);
+ write!(w, "<section id=\"{id}\" class=\"impl\"{aliases}>");
render_rightside(w, cx, &i.impl_item, containing_item, RenderMode::Normal);
- write!(w, "<a href=\"#{}\" class=\"anchor\">§</a>", id);
- write!(w, "<h3 class=\"code-header\">");
+ write!(
+ w,
+ "<a href=\"#{id}\" class=\"anchor\">§</a>\
+ <h3 class=\"code-header\">"
+ );
if let Some(use_absolute) = use_absolute {
write!(w, "{}", inner_impl.print(use_absolute, cx));
@@ -1880,15 +1891,16 @@ pub(crate) fn render_impl_summary(
} else {
write!(w, "{}", inner_impl.print(false, cx));
}
- write!(w, "</h3>");
+ w.write_str("</h3>");
let is_trait = inner_impl.trait_.is_some();
if is_trait {
if let Some(portability) = portability(&i.impl_item, Some(parent)) {
write!(
w,
- "<span class=\"item-info\"><div class=\"stab portability\">{}</div></span>",
- portability
+ "<span class=\"item-info\">\
+ <div class=\"stab portability\">{portability}</div>\
+ </span>",
);
}
}
@@ -1941,7 +1953,7 @@ pub(crate) fn small_url_encode(s: String) -> String {
// consistent with itself when encoding them.
st += "+";
} else {
- write!(st, "%{:02X}", b).unwrap();
+ write!(st, "%{b:02X}").unwrap();
}
// Invariant: if the current byte is not at the start of a multi-byte character,
// we need to get down here so that when the next turn of the loop comes around,
@@ -1988,7 +2000,9 @@ pub(crate) fn get_filtered_impls_for_reference<'a>(
) -> (Vec<&'a Impl>, Vec<&'a Impl>, Vec<&'a Impl>) {
let def_id = it.item_id.expect_def_id();
// If the reference primitive is somehow not defined, exit early.
- let Some(v) = shared.cache.impls.get(&def_id) else { return (Vec::new(), Vec::new(), Vec::new()) };
+ let Some(v) = shared.cache.impls.get(&def_id) else {
+ return (Vec::new(), Vec::new(), Vec::new());
+ };
// Since there is no "direct implementation" on the reference primitive type, we filter out
// every implementation which isn't a trait implementation.
let traits = v.iter().filter(|i| i.inner_impl().trait_.is_some());
@@ -2254,7 +2268,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
format!("lines {}-{}", line_lo + 1, line_hi + 1),
)
};
- let url = format!("{}{}#{}", cx.root_path(), call_data.url, anchor);
+ let url = format!("{}{}#{anchor}", cx.root_path(), call_data.url);
(url, title)
};
@@ -2264,7 +2278,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
Ok(contents) => contents,
Err(err) => {
let span = item.span(tcx).map_or(rustc_span::DUMMY_SP, |span| span.inner());
- tcx.sess.span_err(span, format!("failed to read file {}: {}", path.display(), err));
+ tcx.sess.span_err(span, format!("failed to read file {}: {err}", path.display()));
return false;
}
};
@@ -2323,7 +2337,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
.unwrap();
if line_ranges.len() > 1 {
- write!(w, r#"<button class="prev">&pr;</button> <button class="next">&sc;</button>"#)
+ w.write_str(r#"<button class="prev">&pr;</button> <button class="next">&sc;</button>"#)
.unwrap();
}
@@ -2359,7 +2373,7 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
highlight::DecorationInfo(decoration_info),
sources::SourceContext::Embedded { offset: line_min, needs_expansion },
);
- write!(w, "</div></div>").unwrap();
+ w.write_str("</div></div>").unwrap();
true
};
@@ -2426,8 +2440,10 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
// For the remaining examples, generate a <ul> containing links to the source files.
if it.peek().is_some() {
- write!(w, r#"<div class="example-links">Additional examples can be found in:<br><ul>"#)
- .unwrap();
+ w.write_str(
+ r#"<div class="example-links">Additional examples can be found in:<br><ul>"#,
+ )
+ .unwrap();
it.for_each(|(_, call_data)| {
let (url, _) = link_to_loc(call_data, &call_data.locations[0]);
write!(
@@ -2438,11 +2454,11 @@ fn render_call_locations<W: fmt::Write>(mut w: W, cx: &mut Context<'_>, item: &c
)
.unwrap();
});
- write!(w, "</ul></div>").unwrap();
+ w.write_str("</ul></div>").unwrap();
}
- write!(w, "</div></details>").unwrap();
+ w.write_str("</div></details>").unwrap();
}
- write!(w, "</div>").unwrap();
+ w.write_str("</div>").unwrap();
}
diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs
index 383e3c170..6cab34986 100644
--- a/src/librustdoc/html/render/print_item.rs
+++ b/src/librustdoc/html/render/print_item.rs
@@ -310,9 +310,8 @@ fn toggle_open(mut w: impl fmt::Write, text: impl fmt::Display) {
w,
"<details class=\"toggle type-contents-toggle\">\
<summary class=\"hideme\">\
- <span>Show {}</span>\
+ <span>Show {text}</span>\
</summary>",
- text
)
.unwrap();
}
@@ -412,7 +411,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
)
});
- debug!("{:?}", indices);
+ debug!("{indices:?}");
let mut last_section = None;
for &idx in &indices {
@@ -431,9 +430,8 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
w,
"<h2 id=\"{id}\" class=\"small-section-header\">\
<a href=\"#{id}\">{name}</a>\
- </h2>{}",
- ITEM_TABLE_OPEN,
- id = cx.derive_id(my_section.id().to_owned()),
+ </h2>{ITEM_TABLE_OPEN}",
+ id = cx.derive_id(my_section.id()),
name = my_section.name(),
);
}
@@ -485,7 +483,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
w.write_str(ITEM_TABLE_ROW_OPEN);
let id = match import.kind {
clean::ImportKind::Simple(s) => {
- format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
+ format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
}
clean::ImportKind::Glob => String::new(),
};
@@ -583,10 +581,8 @@ fn extra_info_tags<'a, 'tcx: 'a>(
display_fn(move |f| {
write!(
f,
- r#"<span class="stab {}" title="{}">{}</span>"#,
- class,
- Escape(title),
- contents
+ r#"<span class="stab {class}" title="{title}">{contents}</span>"#,
+ title = Escape(title),
)
})
}
@@ -614,7 +610,12 @@ fn extra_info_tags<'a, 'tcx: 'a>(
(cfg, _) => cfg.as_deref().cloned(),
};
- debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg);
+ debug!(
+ "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
+ name = item.name,
+ cfg = item.cfg,
+ parent_cfg = parent.cfg
+ );
if let Some(ref cfg) = cfg {
write!(
f,
@@ -689,14 +690,13 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
wrap_item(w, |mut w| {
write!(
w,
- "{attrs}{}{}{}trait {}{}{}",
- visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
- t.unsafety(tcx).print_with_space(),
- if t.is_auto(tcx) { "auto " } else { "" },
- it.name.unwrap(),
- t.generics.print(cx),
- bounds,
+ "{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}",
attrs = render_attributes_in_pre(it, "", tcx),
+ vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
+ unsafety = t.unsafety(tcx).print_with_space(),
+ is_auto = if t.is_auto(tcx) { "auto " } else { "" },
+ name = it.name.unwrap(),
+ generics = t.generics.print(cx),
);
if !t.generics.where_predicates.is_empty() {
@@ -742,11 +742,10 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
toggle_open(
&mut w,
format_args!(
- "{} associated constant{} and {} method{}",
- count_consts,
- pluralize(count_consts),
- count_methods,
- pluralize(count_methods),
+ "{count_consts} associated constant{plural_const} and \
+ {count_methods} method{plural_method}",
+ plural_const = pluralize(count_consts),
+ plural_method = pluralize(count_methods),
),
);
}
@@ -768,7 +767,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
}
if !toggle && should_hide_fields(count_methods) {
toggle = true;
- toggle_open(&mut w, format_args!("{} methods", count_methods));
+ toggle_open(&mut w, format_args!("{count_methods} methods"));
}
if count_consts != 0 && count_methods != 0 {
w.write_str("\n");
@@ -837,9 +836,9 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
let name = m.name.unwrap();
- info!("Documenting {} on {:?}", name, t.name);
+ info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
let item_type = m.type_();
- let id = cx.derive_id(format!("{}.{}", item_type, name));
+ let id = cx.derive_id(format!("{item_type}.{name}"));
let mut content = Buffer::empty_from(w);
write!(&mut content, "{}", document(cx, m, Some(t), HeadingOffset::H5));
let toggled = !content.is_empty();
@@ -847,7 +846,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
}
- write!(w, "<section id=\"{}\" class=\"method\">", id);
+ write!(w, "<section id=\"{id}\" class=\"method\">");
render_rightside(w, cx, m, t, RenderMode::Normal);
write!(w, "<h4 class=\"code-header\">");
render_assoc_item(
@@ -1170,12 +1169,12 @@ fn item_trait_alias(
wrap_item(w, |w| {
write!(
w,
- "{attrs}trait {}{}{} = {};",
- it.name.unwrap(),
- t.generics.print(cx),
- print_where_clause(&t.generics, cx, 0, Ending::Newline),
- bounds(&t.bounds, true, cx),
+ "{attrs}trait {name}{generics}{where_b} = {bounds};",
attrs = render_attributes_in_pre(it, "", cx.tcx()),
+ name = it.name.unwrap(),
+ generics = t.generics.print(cx),
+ where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline),
+ bounds = bounds(&t.bounds, true, cx),
)
.unwrap();
});
@@ -1198,12 +1197,12 @@ fn item_opaque_ty(
wrap_item(w, |w| {
write!(
w,
- "{attrs}type {}{}{where_clause} = impl {bounds};",
- it.name.unwrap(),
- t.generics.print(cx),
+ "{attrs}type {name}{generics}{where_clause} = impl {bounds};",
+ attrs = render_attributes_in_pre(it, "", cx.tcx()),
+ name = it.name.unwrap(),
+ generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds = bounds(&t.bounds, false, cx),
- attrs = render_attributes_in_pre(it, "", cx.tcx()),
)
.unwrap();
});
@@ -1223,13 +1222,13 @@ fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clea
wrap_item(w, |w| {
write!(
w,
- "{attrs}{}type {}{}{where_clause} = {type_};",
- visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
- it.name.unwrap(),
- t.generics.print(cx),
+ "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
+ attrs = render_attributes_in_pre(it, "", cx.tcx()),
+ vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
+ name = it.name.unwrap(),
+ generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
type_ = t.type_.print(cx),
- attrs = render_attributes_in_pre(it, "", cx.tcx()),
);
});
}
@@ -1354,7 +1353,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
w.write_str("{\n");
let toggle = should_hide_fields(count_variants);
if toggle {
- toggle_open(&mut w, format_args!("{} variants", count_variants));
+ toggle_open(&mut w, format_args!("{count_variants} variants"));
}
for v in e.variants() {
w.write_str(" ");
@@ -1362,7 +1361,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
match *v.kind {
// FIXME(#101337): Show discriminant
clean::VariantItem(ref var) => match var.kind {
- clean::VariantKind::CLike => write!(w, "{}", name),
+ clean::VariantKind::CLike => w.write_str(name.as_str()),
clean::VariantKind::Tuple(ref s) => {
write!(w, "{name}({})", print_tuple_struct_fields(cx, s),);
}
@@ -1418,7 +1417,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
- write!(w, "({})", print_tuple_struct_fields(cx, s),);
+ write!(w, "({})", print_tuple_struct_fields(cx, s));
}
w.write_str("</h3></section>");
@@ -1543,10 +1542,12 @@ fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &cle
write!(
w,
- "{vis}const {name}: {typ}",
+ "{vis}const {name}{generics}: {typ}{where_clause}",
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
name = it.name.unwrap(),
+ generics = c.generics.print(cx),
typ = c.type_.print(cx),
+ where_clause = print_where_clause(&c.generics, cx, 0, Ending::NoNewline),
);
// FIXME: The code below now prints
@@ -1615,7 +1616,7 @@ fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean
for (index, (field, ty)) in fields.enumerate() {
let field_name =
field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
- let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
+ let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField));
write!(
w,
"<span id=\"{id}\" class=\"{item_type} small-section-header\">\
@@ -1720,7 +1721,7 @@ pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
pub(super) fn item_path(ty: ItemType, name: &str) -> String {
match ty {
ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
- _ => format!("{}.{}.html", ty, name),
+ _ => format!("{ty}.{name}.html"),
}
}
@@ -1843,7 +1844,7 @@ fn render_union<'a, 'cx: 'a>(
fields.iter().filter(|field| matches!(*field.kind, clean::StructFieldItem(..))).count();
let toggle = should_hide_fields(count_fields);
if toggle {
- toggle_open(&mut f, format_args!("{} fields", count_fields));
+ toggle_open(&mut f, format_args!("{count_fields} fields"));
}
for field in fields {
@@ -1906,26 +1907,25 @@ fn render_struct(
let has_visible_fields = count_fields > 0;
let toggle = should_hide_fields(count_fields);
if toggle {
- toggle_open(&mut w, format_args!("{} fields", count_fields));
+ toggle_open(&mut w, format_args!("{count_fields} fields"));
}
for field in fields {
if let clean::StructFieldItem(ref ty) = *field.kind {
write!(
w,
- "\n{} {}{}: {},",
- tab,
- visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
- field.name.unwrap(),
- ty.print(cx),
+ "\n{tab} {vis}{name}: {ty},",
+ vis = visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
+ name = field.name.unwrap(),
+ ty = ty.print(cx),
);
}
}
if has_visible_fields {
if it.has_stripped_entries().unwrap() {
- write!(w, "\n{} /* private fields */", tab);
+ write!(w, "\n{tab} /* private fields */");
}
- write!(w, "\n{}", tab);
+ write!(w, "\n{tab}");
} else if it.has_stripped_entries().unwrap() {
write!(w, " /* private fields */ ");
}
diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs
index 455b4e9ae..f3da61056 100644
--- a/src/librustdoc/html/render/sidebar.rs
+++ b/src/librustdoc/html/render/sidebar.rs
@@ -330,7 +330,7 @@ fn sidebar_deref_methods<'a>(
) {
let c = cx.cache();
- debug!("found Deref: {:?}", impl_);
+ debug!("found Deref: {impl_:?}");
if let Some((target, real_target)) =
impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
clean::AssocTypeItem(box ref t, _) => Some(match *t {
@@ -340,7 +340,7 @@ fn sidebar_deref_methods<'a>(
_ => None,
})
{
- debug!("found target, real_target: {:?} {:?}", target, real_target);
+ debug!("found target, real_target: {target:?} {real_target:?}");
if let Some(did) = target.def_id(c) &&
let Some(type_did) = impl_.inner_impl().for_.def_id(c) &&
// `impl Deref<Target = S> for S`
@@ -357,7 +357,7 @@ fn sidebar_deref_methods<'a>(
})
.and_then(|did| c.impls.get(&did));
if let Some(impls) = inner_impl {
- debug!("found inner_impl: {:?}", impls);
+ debug!("found inner_impl: {impls:?}");
let mut ret = impls
.iter()
.filter(|i| i.inner_impl().trait_.is_none())
@@ -510,10 +510,10 @@ fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
return url;
}
let mut add = 1;
- while !used_links.insert(format!("{}-{}", url, add)) {
+ while !used_links.insert(format!("{url}-{add}")) {
add += 1;
}
- format!("{}-{}", url, add)
+ format!("{url}-{add}")
}
fn get_methods<'a>(
@@ -529,7 +529,7 @@ fn get_methods<'a>(
Some(ref name) if !name.is_empty() && item.is_method() => {
if !for_deref || super::should_render_item(item, deref_mut, tcx) {
Some(Link::new(
- get_next_url(used_links, format!("{}.{}", ItemType::Method, name)),
+ get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::Method)),
name.as_str(),
))
} else {
@@ -549,7 +549,7 @@ fn get_associated_constants<'a>(
.iter()
.filter_map(|item| match item.name {
Some(ref name) if !name.is_empty() && item.is_associated_const() => Some(Link::new(
- get_next_url(used_links, format!("{}.{}", ItemType::AssocConst, name)),
+ get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::AssocConst)),
name.as_str(),
)),
_ => None,
diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs
index eb9262f47..5f130f187 100644
--- a/src/librustdoc/html/render/span_map.rs
+++ b/src/librustdoc/html/render/span_map.rs
@@ -1,11 +1,11 @@
-use crate::clean::{self, PrimitiveType};
+use crate::clean::{self, rustc_span, PrimitiveType};
use crate::html::sources;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::{DefKind, Res};
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::intravisit::{self, Visitor};
-use rustc_hir::{ExprKind, HirId, Mod, Node};
+use rustc_hir::{ExprKind, HirId, Item, ItemKind, Mod, Node};
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::TyCtxt;
use rustc_span::hygiene::MacroKind;
@@ -25,6 +25,7 @@ pub(crate) enum LinkFromSrc {
Local(clean::Span),
External(DefId),
Primitive(PrimitiveType),
+ Doc(DefId),
}
/// This function will do at most two things:
@@ -65,24 +66,43 @@ struct SpanMapVisitor<'tcx> {
impl<'tcx> SpanMapVisitor<'tcx> {
/// This function is where we handle `hir::Path` elements and add them into the "span map".
fn handle_path(&mut self, path: &rustc_hir::Path<'_>) {
- let info = match path.res {
+ match path.res {
// FIXME: For now, we handle `DefKind` if it's not a `DefKind::TyParam`.
// Would be nice to support them too alongside the other `DefKind`
// (such as primitive types!).
- Res::Def(kind, def_id) if kind != DefKind::TyParam => Some(def_id),
- Res::Local(_) => None,
+ Res::Def(kind, def_id) if kind != DefKind::TyParam => {
+ let link = if def_id.as_local().is_some() {
+ LinkFromSrc::Local(rustc_span(def_id, self.tcx))
+ } else {
+ LinkFromSrc::External(def_id)
+ };
+ self.matches.insert(path.span, link);
+ }
+ Res::Local(_) => {
+ if let Some(span) = self.tcx.hir().res_span(path.res) {
+ self.matches.insert(path.span, LinkFromSrc::Local(clean::Span::new(span)));
+ }
+ }
Res::PrimTy(p) => {
// FIXME: Doesn't handle "path-like" primitives like arrays or tuples.
self.matches.insert(path.span, LinkFromSrc::Primitive(PrimitiveType::from(p)));
- return;
}
- Res::Err => return,
- _ => return,
- };
- if let Some(span) = self.tcx.hir().res_span(path.res) {
- self.matches.insert(path.span, LinkFromSrc::Local(clean::Span::new(span)));
- } else if let Some(def_id) = info {
- self.matches.insert(path.span, LinkFromSrc::External(def_id));
+ Res::Err => {}
+ _ => {}
+ }
+ }
+
+ /// Used to generate links on items' definition to go to their documentation page.
+ pub(crate) fn extract_info_from_hir_id(&mut self, hir_id: HirId) {
+ if let Some(Node::Item(item)) = self.tcx.hir().find(hir_id) {
+ if let Some(span) = self.tcx.def_ident_span(item.owner_id) {
+ let cspan = clean::Span::new(span);
+ // If the span isn't from the current crate, we ignore it.
+ if cspan.inner().is_dummy() || cspan.cnum(self.tcx.sess) != LOCAL_CRATE {
+ return;
+ }
+ self.matches.insert(span, LinkFromSrc::Doc(item.owner_id.to_def_id()));
+ }
}
}
@@ -117,10 +137,13 @@ impl<'tcx> SpanMapVisitor<'tcx> {
_ => return true,
};
let link_from_src = match data.macro_def_id {
- Some(macro_def_id) if macro_def_id.is_local() => {
- LinkFromSrc::Local(clean::Span::new(data.def_site))
+ Some(macro_def_id) => {
+ if macro_def_id.is_local() {
+ LinkFromSrc::Local(clean::Span::new(data.def_site))
+ } else {
+ LinkFromSrc::External(macro_def_id)
+ }
}
- Some(macro_def_id) => LinkFromSrc::External(macro_def_id),
None => return true,
};
let new_span = data.call_site;
@@ -160,6 +183,9 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> {
LinkFromSrc::Local(clean::Span::new(m.spans.inner_span)),
);
}
+ } else {
+ // If it's a "mod foo {}", we want to look to its documentation page.
+ self.extract_info_from_hir_id(id);
}
intravisit::walk_mod(self, m, id);
}
@@ -176,13 +202,12 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> {
.tcx
.typeck_body(hir.maybe_body_owned_by(body_id).expect("a body which isn't a body"));
if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
- self.matches.insert(
- segment.ident.span,
- match hir.span_if_local(def_id) {
- Some(span) => LinkFromSrc::Local(clean::Span::new(span)),
- None => LinkFromSrc::External(def_id),
- },
- );
+ let link = if def_id.as_local().is_some() {
+ LinkFromSrc::Local(rustc_span(def_id, self.tcx))
+ } else {
+ LinkFromSrc::External(def_id)
+ };
+ self.matches.insert(segment.ident.span, link);
}
} else if self.handle_macro(expr.span) {
// We don't want to go deeper into the macro.
@@ -190,4 +215,28 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> {
}
intravisit::walk_expr(self, expr);
}
+
+ fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
+ match item.kind {
+ ItemKind::Static(_, _, _)
+ | ItemKind::Const(_, _, _)
+ | ItemKind::Fn(_, _, _)
+ | ItemKind::Macro(_, _)
+ | ItemKind::TyAlias(_, _)
+ | ItemKind::Enum(_, _)
+ | ItemKind::Struct(_, _)
+ | ItemKind::Union(_, _)
+ | ItemKind::Trait(_, _, _, _, _)
+ | ItemKind::TraitAlias(_, _) => self.extract_info_from_hir_id(item.hir_id()),
+ ItemKind::Impl(_)
+ | ItemKind::Use(_, _)
+ | ItemKind::ExternCrate(_)
+ | ItemKind::ForeignMod { .. }
+ | ItemKind::GlobalAsm(_)
+ | ItemKind::OpaqueTy(_)
+ // We already have "visit_mod" above so no need to check it here.
+ | ItemKind::Mod(_) => {}
+ }
+ intravisit::walk_item(self, item);
+ }
}
diff --git a/src/librustdoc/html/render/type_layout.rs b/src/librustdoc/html/render/type_layout.rs
index 0bc32ea5a..377daaeb9 100644
--- a/src/librustdoc/html/render/type_layout.rs
+++ b/src/librustdoc/html/render/type_layout.rs
@@ -39,7 +39,7 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>(
let tcx = cx.tcx();
let param_env = tcx.param_env(ty_def_id);
- let ty = tcx.type_of(ty_def_id).subst_identity();
+ let ty = tcx.type_of(ty_def_id).instantiate_identity();
let type_layout = tcx.layout_of(param_env.and(ty));
let variants =
diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs
index 54749e9a3..e824651e7 100644
--- a/src/librustdoc/html/render/write_shared.rs
+++ b/src/librustdoc/html/render/write_shared.rs
@@ -73,7 +73,7 @@ pub(super) fn write_shared(
}
let bytes = try_err!(fs::read(&entry.path), &entry.path);
- let filename = format!("{}{}.{}", theme, cx.shared.resource_suffix, extension);
+ let filename = format!("{theme}{suffix}.{extension}", suffix = cx.shared.resource_suffix);
cx.shared.fs.write(cx.dst.join(filename), bytes)?;
}
@@ -112,7 +112,7 @@ pub(super) fn write_shared(
let mut krates = Vec::new();
if path.exists() {
- let prefix = format!("\"{}\"", krate);
+ let prefix = format!("\"{krate}\"");
for line in BufReader::new(File::open(path)?).lines() {
let line = line?;
if !line.starts_with('"') {
@@ -157,7 +157,7 @@ pub(super) fn write_shared(
let mut krates = Vec::new();
if path.exists() {
- let prefix = format!("\"{}\"", krate);
+ let prefix = format!("\"{krate}\"");
for line in BufReader::new(File::open(path)?).lines() {
let line = line?;
if !line.starts_with('"') {
@@ -213,10 +213,10 @@ pub(super) fn write_shared(
let dirs = if subs.is_empty() && files.is_empty() {
String::new()
} else {
- format!(",[{}]", subs)
+ format!(",[{subs}]")
};
let files = files.join(",");
- let files = if files.is_empty() { String::new() } else { format!(",[{}]", files) };
+ let files = if files.is_empty() { String::new() } else { format!(",[{files}]") };
format!(
"[\"{name}\"{dirs}{files}]",
name = self.elem.to_str().expect("invalid osstring conversion"),
@@ -270,7 +270,7 @@ pub(super) fn write_shared(
hierarchy.add_path(source);
}
let hierarchy = Rc::try_unwrap(hierarchy).unwrap();
- let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
+ let dst = cx.dst.join(&format!("src-files{}.js", cx.shared.resource_suffix));
let make_sources = || {
let (mut all_sources, _krates) =
try_err!(collect_json(&dst, krate.name(cx.tcx()).as_str()), &dst);
@@ -286,12 +286,12 @@ pub(super) fn write_shared(
.replace("\\\"", "\\\\\"")
));
all_sources.sort();
- let mut v = String::from("var sourcesIndex = JSON.parse('{\\\n");
+ let mut v = String::from("var srcIndex = JSON.parse('{\\\n");
v.push_str(&all_sources.join(",\\\n"));
- v.push_str("\\\n}');\ncreateSourceSidebar();\n");
+ v.push_str("\\\n}');\ncreateSrcSidebar();\n");
Ok(v.into_bytes())
};
- write_invocation_specific("source-files.js", &make_sources)?;
+ write_invocation_specific("src-files.js", &make_sources)?;
}
// Update the search index and crate list.
@@ -319,8 +319,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
})?;
write_invocation_specific("crates.js", &|| {
- let krates = krates.iter().map(|k| format!("\"{}\"", k)).join(",");
- Ok(format!("window.ALL_CRATES = [{}];", krates).into_bytes())
+ let krates = krates.iter().map(|k| format!("\"{k}\"")).join(",");
+ Ok(format!("window.ALL_CRATES = [{krates}];").into_bytes())
})?;
if options.enable_index_page {
@@ -349,9 +349,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
.iter()
.map(|s| {
format!(
- "<li><a href=\"{}index.html\">{}</a></li>",
- ensure_trailing_slash(s),
- s
+ "<li><a href=\"{trailing_slash}index.html\">{s}</a></li>",
+ trailing_slash = ensure_trailing_slash(s),
)
})
.collect::<String>()
@@ -444,7 +443,7 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
mydst.push(part.to_string());
}
cx.shared.ensure_dir(&mydst)?;
- mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1]));
+ mydst.push(&format!("{remote_item_type}.{}.js", remote_path[remote_path.len() - 1]));
let (mut all_implementors, _) =
try_err!(collect(&mydst, krate.name(cx.tcx()).as_str()), &mydst);
diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs
index a26fa3749..c4a1ebbec 100644
--- a/src/librustdoc/html/sources.rs
+++ b/src/librustdoc/html/sources.rs
@@ -146,9 +146,8 @@ impl DocVisitor for SourceCollector<'_, '_> {
self.cx.shared.tcx.sess.span_err(
span,
format!(
- "failed to render source code for `{}`: {}",
- filename.prefer_local(),
- e,
+ "failed to render source code for `{filename}`: {e}",
+ filename = filename.prefer_local(),
),
);
false
@@ -227,7 +226,7 @@ impl SourceCollector<'_, '_> {
let desc = format!("Source of the Rust file `{}`.", filename.prefer_remapped());
let page = layout::Page {
title: &title,
- css_class: "source",
+ css_class: "src",
root_path: &root_path,
static_root_path: shared.static_root_path.as_deref(),
description: &desc,
diff --git a/src/librustdoc/html/static/css/noscript.css b/src/librustdoc/html/static/css/noscript.css
index 54e8b6561..93aa11a58 100644
--- a/src/librustdoc/html/static/css/noscript.css
+++ b/src/librustdoc/html/static/css/noscript.css
@@ -19,7 +19,7 @@ nav.sub {
display: none;
}
-.source .sidebar {
+.src .sidebar {
display: none;
}
diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css
index b7f455259..b1de8c152 100644
--- a/src/librustdoc/html/static/css/rustdoc.css
+++ b/src/librustdoc/html/static/css/rustdoc.css
@@ -194,7 +194,7 @@ h1, h2, h3, h4, h5, h6,
.item-name > a,
.out-of-band,
span.since,
-a.srclink,
+a.src,
#help-button > a,
summary.hideme,
.scraped-example-list,
@@ -206,7 +206,7 @@ ul.all-items {
#toggle-all-docs,
a.anchor,
.small-section-header a,
-#source-sidebar a,
+#src-sidebar a,
.rust a,
.sidebar h2 a,
.sidebar h3 a,
@@ -315,7 +315,7 @@ main {
min-width: 0; /* avoid growing beyond the size limit */
}
-.source main {
+.src main {
padding: 15px;
}
@@ -350,10 +350,10 @@ pre.item-decl {
contain: initial;
}
-.source .content pre {
+.src .content pre {
padding: 20px;
}
-.rustdoc.source .example-wrap pre.src-line-numbers {
+.rustdoc.src .example-wrap pre.src-line-numbers {
padding: 20px 0 20px 4px;
}
@@ -392,7 +392,7 @@ img {
left: 0;
}
-.rustdoc.source .sidebar {
+.rustdoc.src .sidebar {
flex-basis: 50px;
border-right: 1px solid;
overflow-x: hidden;
@@ -402,7 +402,7 @@ img {
}
.sidebar, .mobile-topbar, .sidebar-menu-toggle,
-#src-sidebar-toggle, #source-sidebar {
+#src-sidebar-toggle, #src-sidebar {
background-color: var(--sidebar-background-color);
}
@@ -410,16 +410,16 @@ img {
background-color: var(--sidebar-background-color-hover);
}
-.source .sidebar > *:not(#src-sidebar-toggle) {
+.src .sidebar > *:not(#src-sidebar-toggle) {
visibility: hidden;
}
-.source-sidebar-expanded .source .sidebar {
+.src-sidebar-expanded .src .sidebar {
overflow-y: auto;
flex-basis: 300px;
}
-.source-sidebar-expanded .source .sidebar > *:not(#src-sidebar-toggle) {
+.src-sidebar-expanded .src .sidebar > *:not(#src-sidebar-toggle) {
visibility: visible;
}
@@ -544,7 +544,7 @@ ul.block, .block li {
flex-grow: 1;
}
-.rustdoc:not(.source) .example-wrap pre {
+.rustdoc:not(.src) .example-wrap pre {
overflow: auto hidden;
}
@@ -619,7 +619,7 @@ ul.block, .block li {
}
.docblock code, .docblock-short code,
-pre, .rustdoc.source .example-wrap {
+pre, .rustdoc.src .example-wrap {
background-color: var(--code-block-background-color);
}
@@ -676,7 +676,7 @@ nav.sub {
height: 34px;
flex-grow: 1;
}
-.source nav.sub {
+.src nav.sub {
margin: 0 0 15px 0;
}
@@ -776,7 +776,6 @@ table,
}
#crate-search {
min-width: 115px;
- /* keep these two in sync with "@-moz-document url-prefix()" below */
padding: 0 23px 0 4px;
/* prevents the <select> from overflowing the containing div in case it's shrunk */
max-width: 100%;
@@ -798,14 +797,6 @@ table,
#crate-search:hover, #crate-search:focus {
border-color: var(--crate-search-hover-border);
}
-/* cancel stylistic differences in padding in firefox
-for "appearance: none"-style (or equivalent) <select>s */
-@-moz-document url-prefix() {
- #crate-search {
- padding-left: 0px; /* == 4px - 4px */
- padding-right: 19px; /* == 23px - 4px */
- }
-}
/* pseudo-element for holding the dropdown-arrow image; needs to be a separate thing
so that we can apply CSS-filters to change the arrow color in themes */
#crate-search-div::after {
@@ -888,7 +879,7 @@ so that we can apply CSS-filters to change the arrow color in themes */
justify-content: start;
flex: 3;
}
-.search-results .result-name span.alias {
+.search-results .result-name .alias {
color: var(--search-results-alias-color);
}
.search-results .result-name .grey {
@@ -904,6 +895,9 @@ so that we can apply CSS-filters to change the arrow color in themes */
max-width: calc(100% - var(--search-typename-width));
display: inline-block;
}
+.search-results .result-name .path > * {
+ display: inline;
+}
.popover {
position: absolute;
@@ -1074,7 +1068,7 @@ pre.rust .doccomment {
color: var(--code-highlight-doc-comment-color);
}
-.rustdoc.source .example-wrap pre.rust a {
+.rustdoc.src .example-wrap pre.rust a {
background: var(--codeblock-link-background);
}
@@ -1301,22 +1295,22 @@ a.tooltip:hover::after {
align-items: stretch;
z-index: 10;
}
-#source-sidebar {
+#src-sidebar {
width: 100%;
overflow: auto;
}
-#source-sidebar > .title {
+#src-sidebar > .title {
font-size: 1.5rem;
text-align: center;
border-bottom: 1px solid var(--border-color);
margin-bottom: 6px;
}
-#source-sidebar div.files > a:hover, details.dir-entry summary:hover,
-#source-sidebar div.files > a:focus, details.dir-entry summary:focus {
- background-color: var(--source-sidebar-background-hover);
+#src-sidebar div.files > a:hover, details.dir-entry summary:hover,
+#src-sidebar div.files > a:focus, details.dir-entry summary:focus {
+ background-color: var(--src-sidebar-background-hover);
}
-#source-sidebar div.files > a.selected {
- background-color: var(--source-sidebar-background-selected);
+#src-sidebar div.files > a.selected {
+ background-color: var(--src-sidebar-background-selected);
}
#src-sidebar-toggle > button {
font-size: inherit;
@@ -1562,7 +1556,7 @@ However, it's not needed with smaller screen width because the doc/code block is
/*
WARNING: RUSTDOC_MOBILE_BREAKPOINT MEDIA QUERY
If you update this line, then you also need to update the line with the same warning
-in source-script.js
+in src-script.js
*/
@media (max-width: 700px) {
/* When linking to an item with an `id` (for instance, by clicking a link in the sidebar,
@@ -1619,8 +1613,8 @@ in source-script.js
/* The source view uses a different design for the sidebar toggle, and doesn't have a topbar,
so don't bump down the main content or the sidebar. */
- .source main,
- .rustdoc.source .sidebar {
+ .src main,
+ .rustdoc.src .sidebar {
top: 0;
padding: 0;
height: 100vh;
@@ -1628,8 +1622,8 @@ in source-script.js
}
.sidebar.shown,
- .source-sidebar-expanded .source .sidebar,
- .rustdoc:not(.source) .sidebar:focus-within {
+ .src-sidebar-expanded .src .sidebar,
+ .rustdoc:not(.src) .sidebar:focus-within {
left: 0;
}
@@ -1709,7 +1703,7 @@ in source-script.js
border-left: 0;
}
- .source-sidebar-expanded #src-sidebar-toggle {
+ .src-sidebar-expanded #src-sidebar-toggle {
left: unset;
top: unset;
width: unset;
@@ -1749,7 +1743,7 @@ in source-script.js
display: inline;
}
- .source-sidebar-expanded .source .sidebar {
+ .src-sidebar-expanded .src .sidebar {
max-width: 100vw;
width: 100vw;
}
@@ -1769,7 +1763,7 @@ in source-script.js
margin-left: 34px;
}
- .source nav.sub {
+ .src nav.sub {
margin: 0;
padding: var(--nav-sub-mobile-padding);
}
@@ -1792,7 +1786,7 @@ in source-script.js
}
@media print {
- nav.sidebar, nav.sub, .out-of-band, a.srclink, #copy-path,
+ nav.sidebar, nav.sub, .out-of-band, a.src, #copy-path,
details.toggle[open] > summary::before, details.toggle > summary::before,
details.toggle.top-doc > summary {
display: none;
diff --git a/src/librustdoc/html/static/css/themes/ayu.css b/src/librustdoc/html/static/css/themes/ayu.css
index 7145baad2..d8dae51eb 100644
--- a/src/librustdoc/html/static/css/themes/ayu.css
+++ b/src/librustdoc/html/static/css/themes/ayu.css
@@ -89,8 +89,8 @@ Original by Dempfi (https://github.com/dempfi/ayu)
--crate-search-div-hover-filter: invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg)
brightness(113%) contrast(76%);
--crate-search-hover-border: #e0e0e0;
- --source-sidebar-background-selected: #14191f;
- --source-sidebar-background-hover: #14191f;
+ --src-sidebar-background-selected: #14191f;
+ --src-sidebar-background-hover: #14191f;
--table-alt-row-background-color: #191f26;
--codeblock-link-background: #333;
--scrape-example-toggle-line-background: #999;
@@ -107,7 +107,7 @@ Original by Dempfi (https://github.com/dempfi/ayu)
h1, h2, h3, h4,
h1 a, .sidebar h2 a, .sidebar h3 a,
-#source-sidebar > .title {
+#src-sidebar > .title {
color: #fff;
}
h4 {
@@ -124,15 +124,15 @@ h4 {
.docblock pre > code,
pre, pre > code,
.item-info code,
-.rustdoc.source .example-wrap {
+.rustdoc.src .example-wrap {
color: #e6e1cf;
}
.sidebar .current,
.sidebar a:hover,
-#source-sidebar div.files > a:hover, details.dir-entry summary:hover,
-#source-sidebar div.files > a:focus, details.dir-entry summary:focus,
-#source-sidebar div.files > a.selected {
+#src-sidebar div.files > a:hover, details.dir-entry summary:hover,
+#src-sidebar div.files > a:focus, details.dir-entry summary:focus,
+#src-sidebar div.files > a.selected {
color: #ffb44c;
}
diff --git a/src/librustdoc/html/static/css/themes/dark.css b/src/librustdoc/html/static/css/themes/dark.css
index 3c1186a56..2b3029887 100644
--- a/src/librustdoc/html/static/css/themes/dark.css
+++ b/src/librustdoc/html/static/css/themes/dark.css
@@ -68,7 +68,7 @@
--test-arrow-color: #dedede;
--test-arrow-background-color: rgba(78, 139, 202, 0.2);
--test-arrow-hover-color: #dedede;
- --test-arrow-hover-background-color: #4e8bca;
+ --test-arrow-hover-background-color: rgb(78, 139, 202);
--target-background-color: #494a3d;
--target-border-color: #bb7410;
--kbd-color: #000;
@@ -84,8 +84,8 @@
--crate-search-div-hover-filter: invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg)
brightness(100%) contrast(91%);
--crate-search-hover-border: #2196f3;
- --source-sidebar-background-selected: #333;
- --source-sidebar-background-hover: #444;
+ --src-sidebar-background-selected: #333;
+ --src-sidebar-background-hover: #444;
--table-alt-row-background-color: #2A2A2A;
--codeblock-link-background: #333;
--scrape-example-toggle-line-background: #999;
diff --git a/src/librustdoc/html/static/css/themes/light.css b/src/librustdoc/html/static/css/themes/light.css
index f8c287137..56fd8cbef 100644
--- a/src/librustdoc/html/static/css/themes/light.css
+++ b/src/librustdoc/html/static/css/themes/light.css
@@ -68,7 +68,7 @@
--test-arrow-color: #f5f5f5;
--test-arrow-background-color: rgba(78, 139, 202, 0.2);
--test-arrow-hover-color: #f5f5f5;
- --test-arrow-hover-background-color: #4e8bca;
+ --test-arrow-hover-background-color: rgb(78, 139, 202);
--target-background-color: #fdffd3;
--target-border-color: #ad7c37;
--kbd-color: #000;
@@ -81,8 +81,8 @@
--crate-search-div-hover-filter: invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg)
brightness(96%) contrast(93%);
--crate-search-hover-border: #717171;
- --source-sidebar-background-selected: #fff;
- --source-sidebar-background-hover: #e0e0e0;
+ --src-sidebar-background-selected: #fff;
+ --src-sidebar-background-hover: #e0e0e0;
--table-alt-row-background-color: #F5F5F5;
--codeblock-link-background: #eee;
--scrape-example-toggle-line-background: #ccc;
diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js
index 51d8e81ca..42088e735 100644
--- a/src/librustdoc/html/static/js/search.js
+++ b/src/librustdoc/html/static/js/search.js
@@ -2108,29 +2108,22 @@ function initSearch(rawSearchIndex) {
const resultName = document.createElement("div");
resultName.className = "result-name";
- if (item.is_alias) {
- const alias = document.createElement("span");
- alias.className = "alias";
-
- const bold = document.createElement("b");
- bold.innerText = item.alias;
- alias.appendChild(bold);
-
- alias.insertAdjacentHTML(
- "beforeend",
- "<i class=\"grey\">&nbsp;- see&nbsp;</i>");
+ resultName.insertAdjacentHTML(
+ "beforeend",
+ `<span class="typename">${typeName}</span>`);
+ link.appendChild(resultName);
- resultName.appendChild(alias);
+ let alias = " ";
+ if (item.is_alias) {
+ alias = ` <div class="alias">\
+<b>${item.alias}</b><i class="grey">&nbsp;- see&nbsp;</i>\
+</div>`;
}
-
resultName.insertAdjacentHTML(
"beforeend",
- `\
-<span class="typename">${typeName}</span>\
-<div class="path">\
- ${item.displayPath}<span class="${type}">${name}</span>\
+ `<div class="path">${alias}\
+${item.displayPath}<span class="${type}">${name}</span>\
</div>`);
- link.appendChild(resultName);
const description = document.createElement("div");
description.className = "desc";
diff --git a/src/librustdoc/html/static/js/source-script.js b/src/librustdoc/html/static/js/src-script.js
index 6eb991360..679c2341f 100644
--- a/src/librustdoc/html/static/js/source-script.js
+++ b/src/librustdoc/html/static/js/src-script.js
@@ -1,5 +1,5 @@
// From rust:
-/* global sourcesIndex */
+/* global srcIndex */
// Local js definitions:
/* global addClass, getCurrentValue, onEachLazy, removeClass, browserSupportsHistoryApi */
@@ -74,11 +74,11 @@ function createDirEntry(elem, parent, fullPath, hasFoundFile) {
function toggleSidebar() {
const child = this.parentNode.children[0];
if (child.innerText === ">") {
- addClass(document.documentElement, "source-sidebar-expanded");
+ addClass(document.documentElement, "src-sidebar-expanded");
child.innerText = "<";
updateLocalStorage("source-sidebar-show", "true");
} else {
- removeClass(document.documentElement, "source-sidebar-expanded");
+ removeClass(document.documentElement, "src-sidebar-expanded");
child.innerText = ">";
updateLocalStorage("source-sidebar-show", "false");
}
@@ -101,16 +101,16 @@ function createSidebarToggle() {
return sidebarToggle;
}
-// This function is called from "source-files.js", generated in `html/render/write_shared.rs`.
+// This function is called from "src-files.js", generated in `html/render/write_shared.rs`.
// eslint-disable-next-line no-unused-vars
-function createSourceSidebar() {
+function createSrcSidebar() {
const container = document.querySelector("nav.sidebar");
const sidebarToggle = createSidebarToggle();
container.insertBefore(sidebarToggle, container.firstChild);
const sidebar = document.createElement("div");
- sidebar.id = "source-sidebar";
+ sidebar.id = "src-sidebar";
let hasFoundFile = false;
@@ -118,9 +118,9 @@ function createSourceSidebar() {
title.className = "title";
title.innerText = "Files";
sidebar.appendChild(title);
- Object.keys(sourcesIndex).forEach(key => {
- sourcesIndex[key][NAME_OFFSET] = key;
- hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "", hasFoundFile);
+ Object.keys(srcIndex).forEach(key => {
+ srcIndex[key][NAME_OFFSET] = key;
+ hasFoundFile = createDirEntry(srcIndex[key], sidebar, "", hasFoundFile);
});
container.appendChild(sidebar);
@@ -133,7 +133,7 @@ function createSourceSidebar() {
const lineNumbersRegex = /^#?(\d+)(?:-(\d+))?$/;
-function highlightSourceLines(match) {
+function highlightSrcLines(match) {
if (typeof match === "undefined") {
match = window.location.hash.match(lineNumbersRegex);
}
@@ -172,7 +172,7 @@ function highlightSourceLines(match) {
}
}
-const handleSourceHighlight = (function() {
+const handleSrcHighlight = (function() {
let prev_line_id = 0;
const set_fragment = name => {
@@ -180,7 +180,7 @@ const handleSourceHighlight = (function() {
y = window.scrollY;
if (browserSupportsHistoryApi()) {
history.replaceState(null, null, "#" + name);
- highlightSourceLines();
+ highlightSrcLines();
} else {
location.replace("#" + name);
}
@@ -221,15 +221,15 @@ const handleSourceHighlight = (function() {
window.addEventListener("hashchange", () => {
const match = window.location.hash.match(lineNumbersRegex);
if (match) {
- return highlightSourceLines(match);
+ return highlightSrcLines(match);
}
});
onEachLazy(document.getElementsByClassName("src-line-numbers"), el => {
- el.addEventListener("click", handleSourceHighlight);
+ el.addEventListener("click", handleSrcHighlight);
});
-highlightSourceLines();
+highlightSrcLines();
-window.createSourceSidebar = createSourceSidebar;
+window.createSrcSidebar = createSrcSidebar;
})();
diff --git a/src/librustdoc/html/static/js/storage.js b/src/librustdoc/html/static/js/storage.js
index 71961f6f2..af3ca42a6 100644
--- a/src/librustdoc/html/static/js/storage.js
+++ b/src/librustdoc/html/static/js/storage.js
@@ -185,7 +185,7 @@ updateTheme();
if (getSettingValue("source-sidebar-show") === "true") {
// At this point in page load, `document.body` is not available yet.
// Set a class on the `<html>` element instead.
- addClass(document.documentElement, "source-sidebar-expanded");
+ addClass(document.documentElement, "src-sidebar-expanded");
}
// If we navigate away (for example to a settings page), and then use the back or
diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs
index 767b974cc..a27aa2b58 100644
--- a/src/librustdoc/html/static_files.rs
+++ b/src/librustdoc/html/static_files.rs
@@ -53,7 +53,7 @@ pub(crate) fn suffix_path(filename: &str, suffix: &str) -> PathBuf {
// which would result in `style.min-suffix.css` which isn't what we
// want.
let (base, ext) = filename.split_once('.').unwrap();
- let filename = format!("{}{}.{}", base, suffix, ext);
+ let filename = format!("{base}{suffix}.{ext}");
filename.into()
}
@@ -97,7 +97,7 @@ static_files! {
main_js => "static/js/main.js",
search_js => "static/js/search.js",
settings_js => "static/js/settings.js",
- source_script_js => "static/js/source-script.js",
+ src_script_js => "static/js/src-script.js",
storage_js => "static/js/storage.js",
scrape_examples_js => "static/js/scrape-examples.js",
wheel_svg => "static/images/wheel.svg",
diff --git a/src/librustdoc/html/templates/STYLE.md b/src/librustdoc/html/templates/STYLE.md
index 0281b1c47..38aac2a60 100644
--- a/src/librustdoc/html/templates/STYLE.md
+++ b/src/librustdoc/html/templates/STYLE.md
@@ -32,7 +32,7 @@ Askama templates support quite sophisticated control flow. To keep our templates
simple and understandable, we use only a subset: `if` and `for`. In particular
we avoid [assignments in the template logic][assignments] and [Askama
macros][macros]. This also may make things easier if we switch to a different
-Jinja-style template system, like Askama, in the future.
+Jinja-style template system in the future.
[assignments]: https://djc.github.io/askama/template_syntax.html#assignments
[macros]: https://djc.github.io/askama/template_syntax.html#macros
diff --git a/src/librustdoc/html/templates/page.html b/src/librustdoc/html/templates/page.html
index d4ec9c34b..60ccfe4da 100644
--- a/src/librustdoc/html/templates/page.html
+++ b/src/librustdoc/html/templates/page.html
@@ -42,9 +42,9 @@
<script src="{{static_root_path|safe}}{{files.storage_js}}"></script> {# #}
{% if page.css_class.contains("crate") %}
<script defer src="{{page.root_path|safe}}crates{{page.resource_suffix}}.js"></script> {# #}
- {% else if page.css_class == "source" %}
- <script defer src="{{static_root_path|safe}}{{files.source_script_js}}"></script> {# #}
- <script defer src="{{page.root_path|safe}}source-files{{page.resource_suffix}}.js"></script> {# #}
+ {% else if page.css_class == "src" %}
+ <script defer src="{{static_root_path|safe}}{{files.src_script_js}}"></script> {# #}
+ <script defer src="{{page.root_path|safe}}src-files{{page.resource_suffix}}.js"></script> {# #}
{% else if !page.css_class.contains("mod") %}
<script defer src="sidebar-items{{page.resource_suffix}}.js"></script> {# #}
{% endif %}
@@ -85,7 +85,7 @@
</div> {# #}
<![endif]--> {# #}
{{ layout.external_html.before_content|safe }}
- {% if page.css_class != "source" %}
+ {% if page.css_class != "src" %}
<nav class="mobile-topbar"> {# #}
<button class="sidebar-menu-toggle">&#9776;</button> {# #}
<a class="logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #}
@@ -99,7 +99,7 @@
</nav> {# #}
{% endif %}
<nav class="sidebar"> {# #}
- {% if page.css_class != "source" %}
+ {% if page.css_class != "src" %}
<a class="logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #}
{% if !layout.logo.is_empty() %}
<img src="{{layout.logo}}" alt="logo"> {# #}
@@ -111,9 +111,9 @@
{{ sidebar|safe }}
</nav> {# #}
<main> {# #}
- {% if page.css_class != "source" %}<div class="width-limiter">{% endif %}
+ {% if page.css_class != "src" %}<div class="width-limiter">{% endif %}
<nav class="sub"> {# #}
- {% if page.css_class == "source" %}
+ {% if page.css_class == "src" %}
<a class="sub-logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #}
{% if !layout.logo.is_empty() %}
<img src="{{layout.logo}}" alt="logo"> {# #}
@@ -144,7 +144,7 @@
</form> {# #}
</nav> {# #}
<section id="main-content" class="content">{{ content|safe }}</section> {# #}
- {% if page.css_class != "source" %}</div>{% endif %}
+ {% if page.css_class != "src" %}</div>{% endif %}
</main> {# #}
{{ layout.external_html.after_content|safe }}
</body> {# #}
diff --git a/src/librustdoc/html/templates/print_item.html b/src/librustdoc/html/templates/print_item.html
index 68a295ae0..1d215c269 100644
--- a/src/librustdoc/html/templates/print_item.html
+++ b/src/librustdoc/html/templates/print_item.html
@@ -18,7 +18,7 @@
{% endif %}
{% match src_href %}
{% when Some with (href) %}
- <a class="srclink" href="{{href|safe}}">source</a> · {#+ #}
+ <a class="src" href="{{href|safe}}">source</a> · {#+ #}
{% else %}
{% endmatch %}
<button id="toggle-all-docs" title="collapse all docs"> {# #}
diff --git a/src/librustdoc/html/templates/type_layout.html b/src/librustdoc/html/templates/type_layout.html
index 20e09a548..287cbab07 100644
--- a/src/librustdoc/html/templates/type_layout.html
+++ b/src/librustdoc/html/templates/type_layout.html
@@ -44,6 +44,11 @@
<strong>Note:</strong> Encountered an error during type layout; {#+ #}
the type was too big. {# #}
</p> {# #}
+ {% when Err(LayoutError::ReferencesError(_)) %}
+ <p> {# #}
+ <strong>Note:</strong> Encountered an error during type layout; {#+ #}
+ the type references errors. {# #}
+ </p> {# #}
{% when Err(LayoutError::NormalizationFailure(_, _)) %}
<p> {# #}
<strong>Note:</strong> Encountered an error during type layout; {#+ #}