]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/html/render.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustdoc / html / render.rs
CommitLineData
48663c56
XL
1// ignore-tidy-filelength
2
9fa01778 3//! Rustdoc's HTML rendering module.
1a4d82fc
JJ
4//!
5//! This modules contains the bulk of the logic necessary for rendering a
6//! rustdoc `clean::Crate` instance to a set of static HTML pages. This
7//! rendering process is largely driven by the `format!` syntax extension to
8//! perform all I/O into files and streams.
9//!
10//! The rendering process is largely driven by the `Context` and `Cache`
11//! structures. The cache is pre-populated by crawling the crate in question,
bd371182 12//! and then it is shared among the various rendering threads. The cache is meant
1a4d82fc 13//! to be a fairly large structure not implementing `Clone` (because it's shared
bd371182
AL
14//! among threads). The context, however, should be a lightweight structure. This
15//! is cloned per-thread and contains information about what is currently being
1a4d82fc
JJ
16//! rendered.
17//!
18//! In order to speed up rendering (mostly because of markdown rendering), the
19//! rendering process has been parallelized. This parallelization is only
20//! exposed through the `crate` method on the context, and then also from the
21//! fact that the shared cache is stored in TLS (and must be accessed as such).
22//!
23//! In addition to rendering the crate itself, this module is also responsible
24//! for creating the corresponding search index and source file renderings.
bd371182 25//! These threads are not parallelized (they haven't been a bottleneck yet), and
1a4d82fc 26//! both occur before the crate is rendered.
0531ce1d 27
ff7c6d11 28use std::borrow::Cow;
e1599b0c 29use std::cell::{Cell, RefCell};
85aaf69f 30use std::cmp::Ordering;
b7449926 31use std::collections::{BTreeMap, VecDeque};
1a4d82fc 32use std::default::Default;
b039eaaf 33use std::error;
60c5eb7d
XL
34
35use std::fmt::{self, Formatter, Write};
8faf50e0 36use std::ffi::OsStr;
dc9dc135 37use std::fs::{self, File};
c34b1796 38use std::io::prelude::*;
dc9dc135 39use std::io::{self, BufReader};
7453a54e 40use std::path::{PathBuf, Path, Component};
1a4d82fc
JJ
41use std::str;
42use std::sync::Arc;
b7449926 43use std::rc::Rc;
1a4d82fc 44
a1dfa0c6 45use errors;
60c5eb7d
XL
46use serde::{Serialize, Serializer};
47use serde::ser::SerializeSeq;
83c7162d 48use syntax::ast;
48663c56 49use syntax::edition::Edition;
e74abb32
XL
50use syntax::print::pprust;
51use syntax::source_map::FileName;
48663c56 52use syntax::symbol::{Symbol, sym};
e74abb32
XL
53use syntax_pos::hygiene::MacroKind;
54use rustc::hir::def_id::DefId;
92a42be0 55use rustc::middle::privacy::AccessLevels;
b039eaaf 56use rustc::middle::stability;
54a0048b 57use rustc::hir;
476ff2be 58use rustc::util::nodemap::{FxHashMap, FxHashSet};
9e0c209e 59use rustc_data_structures::flock;
60c5eb7d 60use rustc_feature::UnstableFeatures;
1a4d82fc 61
9fa01778
XL
62use crate::clean::{self, AttributesExt, Deprecation, GetDefId, SelfTy, Mutability};
63use crate::config::RenderOptions;
dc9dc135 64use crate::docfs::{DocFS, ErrorStorage, PathError};
9fa01778 65use crate::doctree;
9fa01778 66use crate::html::escape::Escape;
e74abb32
XL
67use crate::html::format::{Buffer, PrintWithSpace, print_abi_with_space};
68use crate::html::format::{print_generic_bounds, WhereClause, href, print_default_space};
69use crate::html::format::{Function};
9fa01778
XL
70use crate::html::format::fmt_impl_for_trait_page;
71use crate::html::item_type::ItemType;
72use crate::html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
73use crate::html::{highlight, layout, static_files};
e1599b0c 74use crate::html::sources;
1a4d82fc 75
94b46f34
XL
76use minifier;
77
416331ca
XL
78#[cfg(test)]
79mod tests;
80
e74abb32
XL
81mod cache;
82
83use cache::Cache;
84crate use cache::ExternalLocation::{self, *};
85
85aaf69f 86/// A pair of name and its optional document.
c34b1796 87pub type NameDoc = (String, Option<String>);
85aaf69f 88
e74abb32
XL
89crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
90 crate::html::format::display_fn(move |f| {
91 if !v.ends_with("/") && !v.is_empty() {
92 write!(f, "{}/", v)
9fa01778 93 } else {
e74abb32 94 write!(f, "{}", v)
9fa01778 95 }
e74abb32 96 })
9fa01778
XL
97}
98
dc9dc135
XL
99#[derive(Debug)]
100pub struct Error {
101 pub file: PathBuf,
102 pub error: io::Error,
103}
104
105impl error::Error for Error {
106 fn description(&self) -> &str {
107 self.error.description()
108 }
109}
110
e74abb32 111impl std::fmt::Display for Error {
dc9dc135
XL
112 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
113 let file = self.file.display().to_string();
114 if file.is_empty() {
115 write!(f, "{}", self.error)
116 } else {
117 write!(f, "\"{}\": {}", self.file.display(), self.error)
118 }
119 }
120}
121
122impl PathError for Error {
123 fn new<P: AsRef<Path>>(e: io::Error, path: P) -> Error {
124 Error {
125 file: path.as_ref().to_path_buf(),
126 error: e,
127 }
128 }
129}
130
131macro_rules! try_none {
132 ($e:expr, $file:expr) => ({
133 use std::io;
134 match $e {
135 Some(e) => e,
136 None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
137 $file))
138 }
139 })
140}
141
142macro_rules! try_err {
143 ($e:expr, $file:expr) => ({
144 match $e {
145 Ok(e) => e,
146 Err(e) => return Err(Error::new(e, $file)),
147 }
148 })
149}
150
1a4d82fc
JJ
151/// Major driving force in all rustdoc rendering. This contains information
152/// about where in the tree-like hierarchy rendering is occurring and controls
153/// how the current page is being rendered.
154///
155/// It is intended that this context is a lightweight object which can be fairly
156/// easily cloned because it is cloned per work-job (about once per item in the
157/// rustdoc tree).
158#[derive(Clone)]
b7449926 159struct Context {
1a4d82fc
JJ
160 /// Current hierarchy of components leading down to what's currently being
161 /// rendered
162 pub current: Vec<String>,
1a4d82fc
JJ
163 /// The current destination folder of where HTML artifacts should be placed.
164 /// This changes as the context descends into the module hierarchy.
c34b1796 165 pub dst: PathBuf,
54a0048b
SL
166 /// A flag, which when `true`, will render pages which redirect to the
167 /// real location of an item. This is used to allow external links to
168 /// publicly reused items to redirect to the right location.
169 pub render_redirect_pages: bool,
b7449926
XL
170 /// The map used to ensure all generated 'id=' attributes are unique.
171 id_map: Rc<RefCell<IdMap>>,
54a0048b 172 pub shared: Arc<SharedContext>,
e74abb32 173 pub cache: Arc<Cache>,
54a0048b
SL
174}
175
e1599b0c 176crate struct SharedContext {
54a0048b
SL
177 /// The path to the crate root source minus the file name.
178 /// Used for simplifying paths to the highlighted source code files.
179 pub src_root: PathBuf,
1a4d82fc
JJ
180 /// This describes the layout of each page, and is not modified after
181 /// creation of the context (contains info like the favicon and added html).
182 pub layout: layout::Layout,
83c7162d 183 /// This flag indicates whether `[src]` links should be generated or not. If
1a4d82fc
JJ
184 /// the source files are present in the html rendering, then this will be
185 /// `true`.
186 pub include_sources: bool,
54a0048b 187 /// The local file sources we've emitted and their respective url-paths.
476ff2be 188 pub local_sources: FxHashMap<PathBuf, String>,
416331ca
XL
189 /// Whether the collapsed pass ran
190 pub collapsed: bool,
e9174d1e
SL
191 /// The base-URL of the issue tracker for when an item has been tagged with
192 /// an issue number.
193 pub issue_tracker_base_url: Option<String>,
abe05a73
XL
194 /// The directories that have already been created in this doc run. Used to reduce the number
195 /// of spurious `create_dir_all` calls.
196 pub created_dirs: RefCell<FxHashSet<PathBuf>>,
ff7c6d11
XL
197 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
198 /// should be ordered alphabetically or in order of appearance (in the source code).
199 pub sort_modules_alphabetically: bool,
2c00a5a8
XL
200 /// Additional themes to be added to the generated docs.
201 pub themes: Vec<PathBuf>,
0531ce1d
XL
202 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
203 /// "light-v2.css").
204 pub resource_suffix: String,
0731742a
XL
205 /// Optional path string to be used to load static files on output pages. If not set, uses
206 /// combinations of `../` to reach the documentation root.
207 pub static_root_path: Option<String>,
9fa01778
XL
208 /// Option disabled by default to generate files used by RLS and some other tools.
209 pub generate_redirect_pages: bool,
dc9dc135
XL
210 /// The fs handle we are working with.
211 pub fs: DocFS,
e74abb32
XL
212 /// The default edition used to parse doctests.
213 pub edition: Edition,
214 pub codes: ErrorCodes,
215 playground: Option<markdown::Playground>,
216}
217
218impl Context {
219 fn path(&self, filename: &str) -> PathBuf {
220 // We use splitn vs Path::extension here because we might get a filename
221 // like `style.min.css` and we want to process that into
222 // `style-suffix.min.css`. Path::extension would just return `css`
223 // which would result in `style.min-suffix.css` which isn't what we
224 // want.
225 let mut iter = filename.splitn(2, '.');
226 let base = iter.next().unwrap();
227 let ext = iter.next().unwrap();
228 let filename = format!(
229 "{}{}.{}",
230 base,
231 self.shared.resource_suffix,
232 ext,
233 );
234 self.dst.join(&filename)
235 }
abe05a73
XL
236}
237
238impl SharedContext {
e1599b0c 239 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
abe05a73
XL
240 let mut dirs = self.created_dirs.borrow_mut();
241 if !dirs.contains(dst) {
dc9dc135 242 try_err!(self.fs.create_dir_all(dst), dst);
abe05a73
XL
243 dirs.insert(dst.to_path_buf());
244 }
245
246 Ok(())
247 }
1a4d82fc 248
ff7c6d11
XL
249 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
250 /// `collapsed_doc_value` of the given item.
251 pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
416331ca 252 if self.collapsed {
ff7c6d11
XL
253 item.collapsed_doc_value().map(|s| s.into())
254 } else {
255 item.doc_value().map(|s| s.into())
256 }
257 }
258}
259
2c00a5a8 260/// Metadata about implementations for a type or trait.
8faf50e0 261#[derive(Clone, Debug)]
1a4d82fc 262pub struct Impl {
a7813a04 263 pub impl_item: clean::Item,
1a4d82fc
JJ
264}
265
9346a6ac 266impl Impl {
a7813a04
XL
267 fn inner_impl(&self) -> &clean::Impl {
268 match self.impl_item.inner {
269 clean::ImplItem(ref impl_) => impl_,
270 _ => panic!("non-impl item found in impl")
271 }
272 }
273
e9174d1e 274 fn trait_did(&self) -> Option<DefId> {
a7813a04 275 self.inner_impl().trait_.def_id()
9346a6ac
AL
276 }
277}
278
a7813a04
XL
279/// Temporary storage for data obtained during `RustdocVisitor::clean()`.
280/// Later on moved into `CACHE_KEY`.
281#[derive(Default)]
282pub struct RenderInfo {
476ff2be 283 pub inlined: FxHashSet<DefId>,
9fa01778 284 pub external_paths: crate::core::ExternalPaths,
0531ce1d 285 pub exact_paths: FxHashMap<DefId, Vec<String>>,
0bf4aa26 286 pub access_levels: AccessLevels<DefId>,
a7813a04 287 pub deref_trait_did: Option<DefId>,
9e0c209e 288 pub deref_mut_trait_did: Option<DefId>,
041b39d2 289 pub owned_box_did: Option<DefId>,
a7813a04
XL
290}
291
1a4d82fc
JJ
292// Helper structs for rendering items/sidebars and carrying along contextual
293// information
294
1a4d82fc
JJ
295/// Struct representing one entry in the JS search index. These are all emitted
296/// by hand to a large JS file at the end of cache-creation.
83c7162d 297#[derive(Debug)]
1a4d82fc
JJ
298struct IndexItem {
299 ty: ItemType,
300 name: String,
301 path: String,
302 desc: String,
e9174d1e 303 parent: Option<DefId>,
7453a54e 304 parent_idx: Option<usize>,
c34b1796
AL
305 search_type: Option<IndexItemFunctionType>,
306}
307
60c5eb7d
XL
308impl Serialize for IndexItem {
309 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
310 where
311 S: Serializer,
312 {
7453a54e
SL
313 assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
314
60c5eb7d
XL
315 (
316 self.ty,
317 &self.name,
318 &self.path,
319 &self.desc,
320 self.parent_idx,
321 &self.search_type,
322 )
323 .serialize(serializer)
7453a54e
SL
324 }
325}
326
c34b1796 327/// A type used for the search index.
83c7162d 328#[derive(Debug)]
c34b1796
AL
329struct Type {
330 name: Option<String>,
abe05a73 331 generics: Option<Vec<String>>,
c34b1796
AL
332}
333
60c5eb7d
XL
334impl Serialize for Type {
335 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
336 where
337 S: Serializer,
338 {
339 if let Some(name) = &self.name {
340 let mut seq = serializer.serialize_seq(None)?;
341 seq.serialize_element(&name)?;
342 if let Some(generics) = &self.generics {
343 seq.serialize_element(&generics)?;
8faf50e0 344 }
60c5eb7d
XL
345 seq.end()
346 } else {
347 serializer.serialize_none()
c34b1796
AL
348 }
349 }
350}
351
352/// Full type of functions/methods in the search index.
83c7162d 353#[derive(Debug)]
c34b1796
AL
354struct IndexItemFunctionType {
355 inputs: Vec<Type>,
532ac7d7 356 output: Option<Vec<Type>>,
c34b1796
AL
357}
358
60c5eb7d
XL
359impl Serialize for IndexItemFunctionType {
360 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
361 where
362 S: Serializer,
363 {
c34b1796 364 // If we couldn't figure out a type, just write `null`.
532ac7d7
XL
365 let mut iter = self.inputs.iter();
366 if match self.output {
367 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.name.is_none()),
368 None => iter.any(|ref i| i.name.is_none()),
369 } {
60c5eb7d 370 serializer.serialize_none()
7453a54e 371 } else {
60c5eb7d
XL
372 let mut seq = serializer.serialize_seq(None)?;
373 seq.serialize_element(&self.inputs)?;
374 if let Some(output) = &self.output {
532ac7d7 375 if output.len() > 1 {
60c5eb7d 376 seq.serialize_element(&output)?;
532ac7d7 377 } else {
60c5eb7d 378 seq.serialize_element(&output[0])?;
532ac7d7 379 }
94b46f34 380 }
60c5eb7d 381 seq.end()
c34b1796 382 }
c34b1796 383 }
1a4d82fc
JJ
384}
385
1a4d82fc 386thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
e1599b0c 387thread_local!(pub static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
ff7c6d11 388
b7449926 389pub fn initial_ids() -> Vec<String> {
92a42be0
SL
390 [
391 "main",
392 "search",
393 "help",
394 "TOC",
395 "render-detail",
396 "associated-types",
397 "associated-const",
398 "required-methods",
399 "provided-methods",
400 "implementors",
0531ce1d 401 "synthetic-implementors",
92a42be0 402 "implementors-list",
0531ce1d 403 "synthetic-implementors-list",
92a42be0
SL
404 "methods",
405 "deref-methods",
406 "implementations",
48663c56 407 ].iter().map(|id| (String::from(*id))).collect()
92a42be0 408}
1a4d82fc
JJ
409
410/// Generates the documentation for `crate` into the directory `dst`
411pub fn run(mut krate: clean::Crate,
a1dfa0c6 412 options: RenderOptions,
cc61c64b 413 renderinfo: RenderInfo,
48663c56
XL
414 diag: &errors::Handler,
415 edition: Edition) -> Result<(), Error> {
a1dfa0c6
XL
416 // need to save a copy of the options for rendering the index page
417 let md_opts = options.clone();
418 let RenderOptions {
419 output,
420 external_html,
421 id_map,
422 playground_url,
423 sort_modules_alphabetically,
424 themes,
425 extension_css,
426 extern_html_root_urls,
427 resource_suffix,
0731742a
XL
428 static_root_path,
429 generate_search_filter,
9fa01778 430 generate_redirect_pages,
a1dfa0c6
XL
431 ..
432 } = options;
433
ff7c6d11
XL
434 let src_root = match krate.src {
435 FileName::Real(ref p) => match p.parent() {
436 Some(p) => p.to_path_buf(),
437 None => PathBuf::new(),
438 },
439 _ => PathBuf::new(),
c34b1796 440 };
dc9dc135 441 let mut errors = Arc::new(ErrorStorage::new());
476ff2be 442 // If user passed in `--playground-url` arg, we fill in crate name here
416331ca 443 let mut playground = None;
476ff2be 444 if let Some(url) = playground_url {
416331ca
XL
445 playground = Some(markdown::Playground {
446 crate_name: Some(krate.name.clone()),
447 url,
476ff2be
SL
448 });
449 }
e74abb32
XL
450 let mut layout = layout::Layout {
451 logo: String::new(),
452 favicon: String::new(),
453 external_html,
454 krate: krate.name.clone(),
455 css_file_extension: extension_css,
456 generate_search_filter,
457 };
458 let mut issue_tracker_base_url = None;
459 let mut include_sources = true;
476ff2be 460
1a4d82fc
JJ
461 // Crawl the crate attributes looking for attributes which control how we're
462 // going to emit HTML
476ff2be 463 if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
48663c56
XL
464 for attr in attrs.lists(sym::doc) {
465 match (attr.name_or_empty(), attr.value_str()) {
466 (sym::html_favicon_url, Some(s)) => {
e74abb32 467 layout.favicon = s.to_string();
54a0048b 468 }
48663c56 469 (sym::html_logo_url, Some(s)) => {
e74abb32 470 layout.logo = s.to_string();
54a0048b 471 }
48663c56 472 (sym::html_playground_url, Some(s)) => {
416331ca
XL
473 playground = Some(markdown::Playground {
474 crate_name: Some(krate.name.clone()),
475 url: s.to_string(),
54a0048b 476 });
1a4d82fc 477 }
48663c56 478 (sym::issue_tracker_base_url, Some(s)) => {
e74abb32 479 issue_tracker_base_url = Some(s.to_string());
54a0048b 480 }
48663c56 481 (sym::html_no_source, None) if attr.is_word() => {
e74abb32 482 include_sources = false;
54a0048b
SL
483 }
484 _ => {}
1a4d82fc
JJ
485 }
486 }
1a4d82fc 487 }
e74abb32
XL
488 let mut scx = SharedContext {
489 collapsed: krate.collapsed,
490 src_root,
491 include_sources,
492 local_sources: Default::default(),
493 issue_tracker_base_url,
494 layout,
495 created_dirs: Default::default(),
496 sort_modules_alphabetically,
497 themes,
498 resource_suffix,
499 static_root_path,
500 generate_redirect_pages,
501 fs: DocFS::new(&errors),
502 edition,
503 codes: ErrorCodes::from(UnstableFeatures::from_environment().is_nightly_build()),
504 playground,
505 };
506
a1dfa0c6 507 let dst = output;
dc9dc135 508 scx.ensure_dir(&dst)?;
e1599b0c 509 krate = sources::render(&dst, &mut scx, krate)?;
e74abb32
XL
510 let (new_crate, index, cache) = Cache::from_krate(
511 renderinfo,
512 &extern_html_root_urls,
513 &dst,
514 krate,
515 );
516 krate = new_crate;
517 let cache = Arc::new(cache);
dc9dc135 518 let mut cx = Context {
54a0048b 519 current: Vec::new(),
3b2f2976 520 dst,
54a0048b 521 render_redirect_pages: false,
b7449926 522 id_map: Rc::new(RefCell::new(id_map)),
54a0048b 523 shared: Arc::new(scx),
e74abb32 524 cache: cache.clone(),
54a0048b 525 };
1a4d82fc 526
1a4d82fc
JJ
527 // Freeze the cache now that the index has been built. Put an Arc into TLS
528 // for future parallelization opportunities
1a4d82fc 529 CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
e1599b0c 530 CURRENT_DEPTH.with(|s| s.set(0));
1a4d82fc 531
dc9dc135
XL
532 // Write shared runs within a flock; disable thread dispatching of IO temporarily.
533 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true);
e74abb32 534 write_shared(&cx, &krate, index, &md_opts, diag)?;
dc9dc135 535 Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false);
1a4d82fc 536
1a4d82fc 537 // And finally render the whole crate's documentation
dc9dc135
XL
538 let ret = cx.krate(krate);
539 let nb_errors = Arc::get_mut(&mut errors).map_or_else(|| 0, |errors| errors.write_errors(diag));
540 if ret.is_err() {
541 ret
542 } else if nb_errors > 0 {
543 Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), ""))
544 } else {
545 Ok(())
546 }
1a4d82fc
JJ
547}
548
a1dfa0c6
XL
549fn write_shared(
550 cx: &Context,
551 krate: &clean::Crate,
a1dfa0c6
XL
552 search_index: String,
553 options: &RenderOptions,
554 diag: &errors::Handler,
555) -> Result<(), Error> {
1a4d82fc
JJ
556 // Write out the shared files. Note that these are shared among all rustdoc
557 // docs placed in the output directory, so this needs to be a synchronized
558 // operation with respect to all other rustdocs running around.
60c5eb7d
XL
559 let lock_file = cx.dst.join(".lock");
560 let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file);
1a4d82fc
JJ
561
562 // Add all the static files. These may already exist, but we just
563 // overwrite them anyway to make sure that they're fresh and up-to-date.
54a0048b 564
e74abb32 565 write_minify(&cx.shared.fs, cx.path("rustdoc.css"),
a1dfa0c6
XL
566 static_files::RUSTDOC_CSS,
567 options.enable_minification)?;
e74abb32 568 write_minify(&cx.shared.fs, cx.path("settings.css"),
a1dfa0c6
XL
569 static_files::SETTINGS_CSS,
570 options.enable_minification)?;
e74abb32 571 write_minify(&cx.shared.fs, cx.path("noscript.css"),
0731742a
XL
572 static_files::NOSCRIPT_CSS,
573 options.enable_minification)?;
2c00a5a8 574
0531ce1d 575 // To avoid "light.css" to be overwritten, we'll first run over the received themes and only
2c00a5a8 576 // then we'll run over the "official" styles.
b7449926 577 let mut themes: FxHashSet<String> = FxHashSet::default();
2c00a5a8
XL
578
579 for entry in &cx.shared.themes {
0731742a 580 let content = try_err!(fs::read(&entry), &entry);
0531ce1d
XL
581 let theme = try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry);
582 let extension = try_none!(try_none!(entry.extension(), &entry).to_str(), &entry);
e74abb32 583 cx.shared.fs.write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?;
0531ce1d 584 themes.insert(theme.to_owned());
2c00a5a8
XL
585 }
586
dc9dc135 587 let write = |p, c| { cx.shared.fs.write(p, c) };
9fa01778 588 if (*cx.shared).layout.logo.is_empty() {
e74abb32 589 write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?;
9fa01778
XL
590 }
591 if (*cx.shared).layout.favicon.is_empty() {
e74abb32
XL
592 write(cx.path("favicon.ico"), static_files::RUST_FAVICON)?;
593 }
594 write(cx.path("brush.svg"), static_files::BRUSH_SVG)?;
595 write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?;
596 write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?;
597 write_minify(&cx.shared.fs,
598 cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification)?;
0531ce1d 599 themes.insert("light".to_owned());
e74abb32
XL
600 write_minify(&cx.shared.fs,
601 cx.path("dark.css"), static_files::themes::DARK, options.enable_minification)?;
2c00a5a8
XL
602 themes.insert("dark".to_owned());
603
604 let mut themes: Vec<&String> = themes.iter().collect();
605 themes.sort();
606 // To avoid theme switch latencies as much as possible, we put everything theme related
607 // at the beginning of the html files into another js file.
dc9dc135 608 let theme_js = format!(
60c5eb7d 609 r#"var themes = document.getElementById("theme-choices");
2c00a5a8 610var themePicker = document.getElementById("theme-picker");
94b46f34 611
416331ca 612function showThemeButtonState() {{
416331ca
XL
613 themes.style.display = "block";
614 themePicker.style.borderBottomRightRadius = "0";
615 themePicker.style.borderBottomLeftRadius = "0";
616}}
617
e1599b0c
XL
618function hideThemeButtonState() {{
619 themes.style.display = "none";
620 themePicker.style.borderBottomRightRadius = "3px";
621 themePicker.style.borderBottomLeftRadius = "3px";
622}}
623
94b46f34 624function switchThemeButtonState() {{
2c00a5a8 625 if (themes.style.display === "block") {{
416331ca 626 hideThemeButtonState();
e1599b0c
XL
627 }} else {{
628 showThemeButtonState();
2c00a5a8
XL
629 }}
630}};
94b46f34
XL
631
632function handleThemeButtonsBlur(e) {{
633 var active = document.activeElement;
634 var related = e.relatedTarget;
635
636 if (active.id !== "themePicker" &&
637 (!active.parentNode || active.parentNode.id !== "theme-choices") &&
638 (!related ||
639 (related.id !== "themePicker" &&
640 (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{
416331ca 641 hideThemeButtonState();
94b46f34
XL
642 }}
643}}
644
645themePicker.onclick = switchThemeButtonState;
646themePicker.onblur = handleThemeButtonsBlur;
60c5eb7d 647{}.forEach(function(item) {{
2c00a5a8 648 var but = document.createElement('button');
60c5eb7d 649 but.textContent = item;
2c00a5a8 650 but.onclick = function(el) {{
e1599b0c 651 switchTheme(currentTheme, mainTheme, item, true);
2c00a5a8 652 }};
94b46f34 653 but.onblur = handleThemeButtonsBlur;
2c00a5a8 654 themes.appendChild(but);
60c5eb7d 655}});"#, serde_json::to_string(&themes).unwrap());
2c00a5a8 656
60c5eb7d
XL
657 write_minify(&cx.shared.fs, cx.path("theme.js"),
658 &theme_js,
659 options.enable_minification)?;
e74abb32 660 write_minify(&cx.shared.fs, cx.path("main.js"),
a1dfa0c6
XL
661 static_files::MAIN_JS,
662 options.enable_minification)?;
e74abb32 663 write_minify(&cx.shared.fs, cx.path("settings.js"),
a1dfa0c6
XL
664 static_files::SETTINGS_JS,
665 options.enable_minification)?;
666 if cx.shared.include_sources {
dc9dc135
XL
667 write_minify(
668 &cx.shared.fs,
e74abb32 669 cx.path("source-script.js"),
dc9dc135
XL
670 static_files::sidebar::SOURCE_SCRIPT,
671 options.enable_minification)?;
a1dfa0c6 672 }
0531ce1d
XL
673
674 {
dc9dc135
XL
675 write_minify(
676 &cx.shared.fs,
e74abb32 677 cx.path("storage.js"),
dc9dc135
XL
678 &format!("var resourcesSuffix = \"{}\";{}",
679 cx.shared.resource_suffix,
680 static_files::STORAGE_JS),
681 options.enable_minification)?;
0531ce1d 682 }
2c00a5a8 683
e1599b0c 684 if let Some(ref css) = cx.shared.layout.css_file_extension {
e74abb32 685 let out = cx.path("theme.css");
dc9dc135 686 let buffer = try_err!(fs::read_to_string(css), css);
a1dfa0c6 687 if !options.enable_minification {
dc9dc135 688 cx.shared.fs.write(&out, &buffer)?;
8faf50e0 689 } else {
dc9dc135 690 write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?;
8faf50e0 691 }
54a0048b 692 }
e74abb32 693 write_minify(&cx.shared.fs, cx.path("normalize.css"),
a1dfa0c6
XL
694 static_files::NORMALIZE_CSS,
695 options.enable_minification)?;
54a0048b 696 write(cx.dst.join("FiraSans-Regular.woff"),
a1dfa0c6 697 static_files::fira_sans::REGULAR)?;
54a0048b 698 write(cx.dst.join("FiraSans-Medium.woff"),
a1dfa0c6 699 static_files::fira_sans::MEDIUM)?;
54a0048b 700 write(cx.dst.join("FiraSans-LICENSE.txt"),
a1dfa0c6 701 static_files::fira_sans::LICENSE)?;
0731742a 702 write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"),
a1dfa0c6 703 static_files::source_serif_pro::REGULAR)?;
0731742a 704 write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"),
a1dfa0c6 705 static_files::source_serif_pro::BOLD)?;
0731742a
XL
706 write(cx.dst.join("SourceSerifPro-It.ttf.woff"),
707 static_files::source_serif_pro::ITALIC)?;
48663c56 708 write(cx.dst.join("SourceSerifPro-LICENSE.md"),
a1dfa0c6 709 static_files::source_serif_pro::LICENSE)?;
54a0048b 710 write(cx.dst.join("SourceCodePro-Regular.woff"),
a1dfa0c6 711 static_files::source_code_pro::REGULAR)?;
54a0048b 712 write(cx.dst.join("SourceCodePro-Semibold.woff"),
a1dfa0c6 713 static_files::source_code_pro::SEMIBOLD)?;
54a0048b 714 write(cx.dst.join("SourceCodePro-LICENSE.txt"),
a1dfa0c6 715 static_files::source_code_pro::LICENSE)?;
54a0048b 716 write(cx.dst.join("LICENSE-MIT.txt"),
a1dfa0c6 717 static_files::LICENSE_MIT)?;
54a0048b 718 write(cx.dst.join("LICENSE-APACHE.txt"),
a1dfa0c6 719 static_files::LICENSE_APACHE)?;
54a0048b 720 write(cx.dst.join("COPYRIGHT.txt"),
a1dfa0c6 721 static_files::COPYRIGHT)?;
1a4d82fc 722
9fa01778
XL
723 fn collect(
724 path: &Path,
725 krate: &str,
726 key: &str,
60c5eb7d 727 ) -> io::Result<(Vec<String>, Vec<String>)> {
1a4d82fc 728 let mut ret = Vec::new();
a1dfa0c6 729 let mut krates = Vec::new();
9fa01778 730
1a4d82fc 731 if path.exists() {
54a0048b
SL
732 for line in BufReader::new(File::open(path)?).lines() {
733 let line = line?;
1a4d82fc 734 if !line.starts_with(key) {
9e0c209e 735 continue;
1a4d82fc 736 }
7453a54e 737 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
9e0c209e 738 continue;
1a4d82fc
JJ
739 }
740 ret.push(line.to_string());
a1dfa0c6
XL
741 krates.push(line[key.len() + 2..].split('"')
742 .next()
743 .map(|s| s.to_owned())
744 .unwrap_or_else(|| String::new()));
1a4d82fc
JJ
745 }
746 }
60c5eb7d 747 Ok((ret, krates))
1a4d82fc
JJ
748 }
749
83c7162d 750 fn show_item(item: &IndexItem, krate: &str) -> String {
94b46f34
XL
751 format!("{{'crate':'{}','ty':{},'name':'{}','desc':'{}','p':'{}'{}}}",
752 krate, item.ty as usize, item.name, item.desc.replace("'", "\\'"), item.path,
83c7162d
XL
753 if let Some(p) = item.parent_idx {
754 format!(",'parent':{}", p)
755 } else {
756 String::new()
757 })
758 }
759
48663c56 760 let dst = cx.dst.join(&format!("aliases{}.js", cx.shared.resource_suffix));
83c7162d 761 {
60c5eb7d 762 let (mut all_aliases, _) = try_err!(collect(&dst, &krate.name, "ALIASES"), &dst);
83c7162d 763 let mut output = String::with_capacity(100);
e74abb32 764 for (alias, items) in &cx.cache.aliases {
83c7162d
XL
765 if items.is_empty() {
766 continue
767 }
768 output.push_str(&format!("\"{}\":[{}],",
769 alias,
770 items.iter()
771 .map(|v| show_item(v, &krate.name))
772 .collect::<Vec<_>>()
773 .join(",")));
774 }
0731742a 775 all_aliases.push(format!("ALIASES[\"{}\"] = {{{}}};", krate.name, output));
83c7162d 776 all_aliases.sort();
e1599b0c
XL
777 let mut v = Buffer::html();
778 writeln!(&mut v, "var ALIASES = {{}};");
83c7162d 779 for aliases in &all_aliases {
e1599b0c 780 writeln!(&mut v, "{}", aliases);
83c7162d 781 }
e1599b0c 782 cx.shared.fs.write(&dst, v.into_inner().into_bytes())?;
83c7162d
XL
783 }
784
a1dfa0c6
XL
785 use std::ffi::OsString;
786
787 #[derive(Debug)]
788 struct Hierarchy {
789 elem: OsString,
790 children: FxHashMap<OsString, Hierarchy>,
791 elems: FxHashSet<OsString>,
792 }
793
794 impl Hierarchy {
795 fn new(elem: OsString) -> Hierarchy {
796 Hierarchy {
797 elem,
798 children: FxHashMap::default(),
799 elems: FxHashSet::default(),
800 }
801 }
802
803 fn to_json_string(&self) -> String {
804 let mut subs: Vec<&Hierarchy> = self.children.values().collect();
805 subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem));
806 let mut files = self.elems.iter()
807 .map(|s| format!("\"{}\"",
808 s.to_str()
809 .expect("invalid osstring conversion")))
810 .collect::<Vec<_>>();
811 files.sort_unstable_by(|a, b| a.cmp(b));
48663c56
XL
812 let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
813 let dirs = if subs.is_empty() {
814 String::new()
815 } else {
816 format!(",\"dirs\":[{}]", subs)
817 };
818 let files = files.join(",");
819 let files = if files.is_empty() {
820 String::new()
821 } else {
822 format!(",\"files\":[{}]", files)
823 };
824 format!("{{\"name\":\"{name}\"{dirs}{files}}}",
a1dfa0c6 825 name=self.elem.to_str().expect("invalid osstring conversion"),
48663c56
XL
826 dirs=dirs,
827 files=files)
a1dfa0c6
XL
828 }
829 }
830
831 if cx.shared.include_sources {
a1dfa0c6
XL
832 let mut hierarchy = Hierarchy::new(OsString::new());
833 for source in cx.shared.local_sources.iter()
834 .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root)
835 .ok()) {
836 let mut h = &mut hierarchy;
837 let mut elems = source.components()
838 .filter_map(|s| {
839 match s {
840 Component::Normal(s) => Some(s.to_owned()),
841 _ => None,
842 }
843 })
844 .peekable();
845 loop {
846 let cur_elem = elems.next().expect("empty file path");
847 if elems.peek().is_none() {
848 h.elems.insert(cur_elem);
849 break;
850 } else {
851 let e = cur_elem.clone();
852 h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e));
853 h = h.children.get_mut(&cur_elem).expect("not found child");
854 }
855 }
856 }
857
48663c56 858 let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix));
60c5eb7d 859 let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name, "sourcesIndex"), &dst);
0731742a 860 all_sources.push(format!("sourcesIndex[\"{}\"] = {};",
a1dfa0c6
XL
861 &krate.name,
862 hierarchy.to_json_string()));
863 all_sources.sort();
e1599b0c
XL
864 let v = format!("var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n",
865 all_sources.join("\n"));
866 cx.shared.fs.write(&dst, v.as_bytes())?;
a1dfa0c6
XL
867 }
868
1a4d82fc 869 // Update the search index
48663c56 870 let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix));
60c5eb7d 871 let (mut all_indexes, mut krates) = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
476ff2be 872 all_indexes.push(search_index);
a1dfa0c6 873
476ff2be
SL
874 // Sort the indexes by crate so the file will be generated identically even
875 // with rustdoc running in parallel.
876 all_indexes.sort();
dc9dc135 877 {
60c5eb7d
XL
878 let mut v = String::from("var searchIndex={};\n");
879 v.push_str(&all_indexes.join("\n"));
880 // "addSearchOptions" has to be called first so the crate filtering can be set before the
881 // search might start (if it's set into the URL for example).
882 v.push_str("\naddSearchOptions(searchIndex);initSearch(searchIndex);");
dc9dc135
XL
883 cx.shared.fs.write(&dst, &v)?;
884 }
a1dfa0c6
XL
885 if options.enable_index_page {
886 if let Some(index_page) = options.index_page.clone() {
887 let mut md_opts = options.clone();
888 md_opts.output = cx.dst.clone();
889 md_opts.external_html = (*cx.shared).layout.external_html.clone();
890
e74abb32 891 crate::markdown::render(index_page, md_opts, diag, cx.shared.edition);
a1dfa0c6
XL
892 } else {
893 let dst = cx.dst.join("index.html");
a1dfa0c6
XL
894 let page = layout::Page {
895 title: "Index of crates",
896 css_class: "mod",
897 root_path: "./",
416331ca 898 static_root_path: cx.shared.static_root_path.as_deref(),
a1dfa0c6
XL
899 description: "List of crates",
900 keywords: BASIC_KEYWORDS,
901 resource_suffix: &cx.shared.resource_suffix,
0731742a
XL
902 extra_scripts: &[],
903 static_extra_scripts: &[],
a1dfa0c6
XL
904 };
905 krates.push(krate.name.clone());
906 krates.sort();
907 krates.dedup();
908
909 let content = format!(
910"<h1 class='fqn'>\
911 <span class='in-band'>List of all crates</span>\
912</h1><ul class='mod'>{}</ul>",
913 krates
914 .iter()
915 .map(|s| {
9fa01778 916 format!("<li><a href=\"{}index.html\">{}</li>",
e74abb32 917 ensure_trailing_slash(s), s)
a1dfa0c6
XL
918 })
919 .collect::<String>());
e1599b0c
XL
920 let v = layout::render(&cx.shared.layout,
921 &page, "", content,
922 &cx.shared.themes);
923 cx.shared.fs.write(&dst, v.as_bytes())?;
a1dfa0c6
XL
924 }
925 }
926
1a4d82fc
JJ
927 // Update the list of all implementors for traits
928 let dst = cx.dst.join("implementors");
e74abb32 929 for (&did, imps) in &cx.cache.implementors {
1a4d82fc
JJ
930 // Private modules can leak through to this phase of rustdoc, which
931 // could contain implementations for otherwise private types. In some
932 // rare cases we could find an implementation for an item which wasn't
933 // indexed, so we just skip this step in that case.
934 //
935 // FIXME: this is a vague explanation for why this can't be a `get`, in
936 // theory it should be...
e74abb32 937 let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) {
1a4d82fc 938 Some(p) => p,
e74abb32 939 None => match cx.cache.external_paths.get(&did) {
5bcae85e
SL
940 Some(p) => p,
941 None => continue,
942 }
1a4d82fc
JJ
943 };
944
60c5eb7d
XL
945 #[derive(Serialize)]
946 struct Implementor {
947 text: String,
948 synthetic: bool,
949 types: Vec<String>,
950 }
951
952 let implementors = imps
953 .iter()
954 .filter_map(|imp| {
955 // If the trait and implementation are in the same crate, then
956 // there's no need to emit information about it (there's inlining
957 // going on). If they're in different crates then the crate defining
958 // the trait will be interested in our implementation.
959 //
960 // If the implementation is from another crate then that crate
961 // should add it.
962 if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() {
963 None
964 } else {
965 Some(Implementor {
966 text: imp.inner_impl().print().to_string(),
967 synthetic: imp.inner_impl().synthetic,
968 types: collect_paths_for_type(imp.inner_impl().for_.clone()),
969 })
970 }
971 })
972 .collect::<Vec<_>>();
476ff2be 973
3b2f2976
XL
974 // Only create a js file if we have impls to add to it. If the trait is
975 // documented locally though we always create the file to avoid dead
976 // links.
60c5eb7d 977 if implementors.is_empty() && !cx.cache.paths.contains_key(&did) {
3b2f2976
XL
978 continue;
979 }
980
60c5eb7d
XL
981 let implementors = format!(
982 r#"implementors["{}"] = {};"#,
983 krate.name,
984 serde_json::to_string(&implementors).unwrap()
985 );
986
1a4d82fc 987 let mut mydst = dst.clone();
85aaf69f
SL
988 for part in &remote_path[..remote_path.len() - 1] {
989 mydst.push(part);
1a4d82fc 990 }
dc9dc135 991 cx.shared.ensure_dir(&mydst)?;
c34b1796 992 mydst.push(&format!("{}.{}.js",
e74abb32 993 remote_item_type,
c34b1796 994 remote_path[remote_path.len() - 1]));
1a4d82fc 995
60c5eb7d
XL
996 let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name, "implementors"),
997 &mydst);
476ff2be
SL
998 all_implementors.push(implementors);
999 // Sort the implementors by crate so the file will be generated
1000 // identically even with rustdoc running in parallel.
1001 all_implementors.sort();
1a4d82fc 1002
e1599b0c 1003 let mut v = String::from("(function() {var implementors = {};\n");
85aaf69f 1004 for implementor in &all_implementors {
e1599b0c 1005 writeln!(v, "{}", *implementor).unwrap();
1a4d82fc 1006 }
e1599b0c 1007 v.push_str(r"
1a4d82fc
JJ
1008 if (window.register_implementors) {
1009 window.register_implementors(implementors);
1010 } else {
1011 window.pending_implementors = implementors;
1012 }
e1599b0c
XL
1013 ");
1014 v.push_str("})()");
dc9dc135 1015 cx.shared.fs.write(&mydst, &v)?;
1a4d82fc
JJ
1016 }
1017 Ok(())
1018}
1019
dc9dc135
XL
1020fn write_minify(fs:&DocFS, dst: PathBuf, contents: &str, enable_minification: bool
1021 ) -> Result<(), Error> {
94b46f34 1022 if enable_minification {
8faf50e0
XL
1023 if dst.extension() == Some(&OsStr::new("css")) {
1024 let res = try_none!(minifier::css::minify(contents).ok(), &dst);
dc9dc135 1025 fs.write(dst, res.as_bytes())
8faf50e0 1026 } else {
dc9dc135 1027 fs.write(dst, minifier::js::minify(contents).as_bytes())
8faf50e0 1028 }
94b46f34 1029 } else {
dc9dc135 1030 fs.write(dst, contents.as_bytes())
94b46f34
XL
1031 }
1032}
1033
83c7162d
XL
1034#[derive(Debug, Eq, PartialEq, Hash)]
1035struct ItemEntry {
1036 url: String,
1037 name: String,
1038}
1039
1040impl ItemEntry {
1041 fn new(mut url: String, name: String) -> ItemEntry {
1042 while url.starts_with('/') {
1043 url.remove(0);
1044 }
1045 ItemEntry {
1046 url,
1047 name,
1048 }
1049 }
1050}
1051
e74abb32
XL
1052impl ItemEntry {
1053 crate fn print(&self) -> impl fmt::Display + '_ {
1054 crate::html::format::display_fn(move |f| {
1055 write!(f, "<a href='{}'>{}</a>", self.url, Escape(&self.name))
1056 })
83c7162d
XL
1057 }
1058}
1059
1060impl PartialOrd for ItemEntry {
1061 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
1062 Some(self.cmp(other))
1063 }
1064}
1065
1066impl Ord for ItemEntry {
1067 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
1068 self.name.cmp(&other.name)
1069 }
1070}
1071
1072#[derive(Debug)]
1073struct AllTypes {
b7449926
XL
1074 structs: FxHashSet<ItemEntry>,
1075 enums: FxHashSet<ItemEntry>,
1076 unions: FxHashSet<ItemEntry>,
1077 primitives: FxHashSet<ItemEntry>,
1078 traits: FxHashSet<ItemEntry>,
1079 macros: FxHashSet<ItemEntry>,
1080 functions: FxHashSet<ItemEntry>,
1081 typedefs: FxHashSet<ItemEntry>,
416331ca 1082 opaque_tys: FxHashSet<ItemEntry>,
b7449926
XL
1083 statics: FxHashSet<ItemEntry>,
1084 constants: FxHashSet<ItemEntry>,
1085 keywords: FxHashSet<ItemEntry>,
0bf4aa26
XL
1086 attributes: FxHashSet<ItemEntry>,
1087 derives: FxHashSet<ItemEntry>,
9fa01778 1088 trait_aliases: FxHashSet<ItemEntry>,
83c7162d
XL
1089}
1090
1091impl AllTypes {
1092 fn new() -> AllTypes {
b7449926 1093 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
83c7162d 1094 AllTypes {
b7449926
XL
1095 structs: new_set(100),
1096 enums: new_set(100),
1097 unions: new_set(100),
1098 primitives: new_set(26),
1099 traits: new_set(100),
1100 macros: new_set(100),
1101 functions: new_set(100),
1102 typedefs: new_set(100),
416331ca 1103 opaque_tys: new_set(100),
b7449926
XL
1104 statics: new_set(100),
1105 constants: new_set(100),
1106 keywords: new_set(100),
0bf4aa26
XL
1107 attributes: new_set(100),
1108 derives: new_set(100),
9fa01778 1109 trait_aliases: new_set(100),
83c7162d
XL
1110 }
1111 }
1112
1113 fn append(&mut self, item_name: String, item_type: &ItemType) {
1114 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
1115 if let Some(name) = url.pop() {
1116 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
1117 url.push(name);
1118 let name = url.join("::");
1119 match *item_type {
1120 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
1121 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
1122 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
1123 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
1124 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
1125 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
1126 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
1127 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
416331ca 1128 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
83c7162d
XL
1129 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
1130 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
0bf4aa26
XL
1131 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
1132 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
9fa01778 1133 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
83c7162d
XL
1134 _ => true,
1135 };
1136 }
1137 }
1138}
1139
e1599b0c 1140fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
83c7162d
XL
1141 if !e.is_empty() {
1142 let mut e: Vec<&ItemEntry> = e.iter().collect();
1143 e.sort();
1144 write!(f, "<h3 id='{}'>{}</h3><ul class='{} docblock'>{}</ul>",
1145 title,
1146 Escape(title),
1147 class,
e74abb32 1148 e.iter().map(|s| format!("<li>{}</li>", s.print())).collect::<String>());
83c7162d 1149 }
83c7162d
XL
1150}
1151
e1599b0c
XL
1152impl AllTypes {
1153 fn print(self, f: &mut Buffer) {
83c7162d 1154 write!(f,
e1599b0c
XL
1155 "<h1 class='fqn'>\
1156 <span class='out-of-band'>\
1157 <span id='render-detail'>\
1158 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" title=\"collapse all docs\">\
1159 [<span class='inner'>&#x2212;</span>]\
1160 </a>\
1161 </span>
1162 </span>
1163 <span class='in-band'>List of all items</span>\
1164 </h1>");
1165 print_entries(f, &self.structs, "Structs", "structs");
1166 print_entries(f, &self.enums, "Enums", "enums");
1167 print_entries(f, &self.unions, "Unions", "unions");
1168 print_entries(f, &self.primitives, "Primitives", "primitives");
1169 print_entries(f, &self.traits, "Traits", "traits");
1170 print_entries(f, &self.macros, "Macros", "macros");
1171 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
1172 print_entries(f, &self.derives, "Derive Macros", "derives");
1173 print_entries(f, &self.functions, "Functions", "functions");
1174 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
1175 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
1176 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
1177 print_entries(f, &self.statics, "Statics", "statics");
83c7162d
XL
1178 print_entries(f, &self.constants, "Constants", "constants")
1179 }
1180}
1181
60c5eb7d
XL
1182#[derive(Debug)]
1183enum Setting {
1184 Section {
1185 description: &'static str,
1186 sub_settings: Vec<Setting>,
1187 },
1188 Entry {
1189 js_data_name: &'static str,
1190 description: &'static str,
1191 default_value: bool,
1192 }
1193}
1194
1195impl Setting {
1196 fn display(&self) -> String {
1197 match *self {
1198 Setting::Section { ref description, ref sub_settings } => {
1199 format!(
1200 "<div class='setting-line'>\
1201 <div class='title'>{}</div>\
1202 <div class='sub-settings'>{}</div>
1203 </div>",
1204 description,
1205 sub_settings.iter().map(|s| s.display()).collect::<String>()
1206 )
1207 }
1208 Setting::Entry { ref js_data_name, ref description, ref default_value } => {
1209 format!(
1210 "<div class='setting-line'>\
1211 <label class='toggle'>\
1212 <input type='checkbox' id='{}' {}>\
1213 <span class='slider'></span>\
1214 </label>\
1215 <div>{}</div>\
1216 </div>",
1217 js_data_name,
1218 if *default_value { " checked" } else { "" },
1219 description,
1220 )
1221 }
1222 }
1223 }
1224}
1225
1226impl From<(&'static str, &'static str, bool)> for Setting {
1227 fn from(values: (&'static str, &'static str, bool)) -> Setting {
1228 Setting::Entry {
1229 js_data_name: values.0,
1230 description: values.1,
1231 default_value: values.2,
1232 }
1233 }
1234}
1235
1236impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
1237 fn from(values: (&'static str, Vec<T>)) -> Setting {
1238 Setting::Section {
1239 description: values.0,
1240 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
1241 }
1242 }
1243}
1244
e1599b0c 1245fn settings(root_path: &str, suffix: &str) -> String {
83c7162d 1246 // (id, explanation, default value)
60c5eb7d
XL
1247 let settings: &[Setting] = &[
1248 ("Auto-hide item declarations", vec![
1249 ("auto-hide-struct", "Auto-hide structs declaration", true),
1250 ("auto-hide-enum", "Auto-hide enums declaration", false),
1251 ("auto-hide-union", "Auto-hide unions declaration", true),
1252 ("auto-hide-trait", "Auto-hide traits declaration", true),
1253 ("auto-hide-macro", "Auto-hide macros declaration", false),
1254 ]).into(),
1255 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
1256 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
1257 ("auto-hide-trait-implementations", "Auto-hide trait implementations documentation",
1258 true).into(),
e1599b0c 1259 ("go-to-only-result", "Directly go to item in search if there is only one result",
60c5eb7d
XL
1260 false).into(),
1261 ("line-numbers", "Show line numbers on code examples", false).into(),
1262 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
e1599b0c
XL
1263 ];
1264 format!(
83c7162d 1265"<h1 class='fqn'>\
e1599b0c 1266 <span class='in-band'>Rustdoc settings</span>\
83c7162d
XL
1267</h1>\
1268<div class='settings'>{}</div>\
1269<script src='{}settings{}.js'></script>",
60c5eb7d 1270 settings.iter().map(|s| s.display()).collect::<String>(),
e1599b0c
XL
1271 root_path,
1272 suffix)
1a4d82fc
JJ
1273}
1274
1275impl Context {
b7449926
XL
1276 fn derive_id(&self, id: String) -> String {
1277 let mut map = self.id_map.borrow_mut();
1278 map.derive(id)
1279 }
1280
c30ab7b3
SL
1281 /// String representation of how to get back to the root path of the 'doc/'
1282 /// folder in terms of a relative URL.
1283 fn root_path(&self) -> String {
8faf50e0 1284 "../".repeat(self.current.len())
c30ab7b3
SL
1285 }
1286
1a4d82fc
JJ
1287 /// Main method for rendering a crate.
1288 ///
1289 /// This currently isn't parallelized, but it'd be pretty easy to add
1290 /// parallelization to this function.
b039eaaf 1291 fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1a4d82fc
JJ
1292 let mut item = match krate.module.take() {
1293 Some(i) => i,
476ff2be 1294 None => return Ok(()),
1a4d82fc 1295 };
83c7162d
XL
1296 let final_file = self.dst.join(&krate.name)
1297 .join("all.html");
1298 let settings_file = self.dst.join("settings.html");
1299
1300 let crate_name = krate.name.clone();
1a4d82fc
JJ
1301 item.name = Some(krate.name);
1302
83c7162d
XL
1303 let mut all = AllTypes::new();
1304
1305 {
1306 // Render the crate documentation
1307 let mut work = vec![(self.clone(), item)];
1308
1309 while let Some((mut cx, item)) = work.pop() {
1310 cx.item(item, &mut all, |cx, item| {
1311 work.push((cx.clone(), item))
1312 })?
1313 }
1314 }
1a4d82fc 1315
83c7162d
XL
1316 let mut root_path = self.dst.to_str().expect("invalid path").to_owned();
1317 if !root_path.ends_with('/') {
1318 root_path.push('/');
54a0048b 1319 }
83c7162d
XL
1320 let mut page = layout::Page {
1321 title: "List of all items in this crate",
1322 css_class: "mod",
1323 root_path: "../",
416331ca 1324 static_root_path: self.shared.static_root_path.as_deref(),
83c7162d
XL
1325 description: "List of all items in this crate",
1326 keywords: BASIC_KEYWORDS,
1327 resource_suffix: &self.shared.resource_suffix,
0731742a
XL
1328 extra_scripts: &[],
1329 static_extra_scripts: &[],
83c7162d 1330 };
e74abb32 1331 let sidebar = if let Some(ref version) = self.cache.crate_version {
83c7162d
XL
1332 format!("<p class='location'>Crate {}</p>\
1333 <div class='block version'>\
1334 <p>Version {}</p>\
1335 </div>\
1336 <a id='all-types' href='index.html'><p>Back to index</p></a>",
1337 crate_name, version)
1338 } else {
1339 String::new()
1340 };
e1599b0c
XL
1341 let v = layout::render(&self.shared.layout,
1342 &page, sidebar, |buf: &mut Buffer| all.print(buf),
1343 &self.shared.themes);
1344 self.shared.fs.write(&final_file, v.as_bytes())?;
83c7162d
XL
1345
1346 // Generating settings page.
83c7162d
XL
1347 page.title = "Rustdoc settings";
1348 page.description = "Settings of Rustdoc";
1349 page.root_path = "./";
1350
83c7162d
XL
1351 let mut themes = self.shared.themes.clone();
1352 let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
1353 themes.push(PathBuf::from("settings.css"));
e1599b0c
XL
1354 let v = layout::render(
1355 &self.shared.layout,
1356 &page, sidebar, settings(
1357 self.shared.static_root_path.as_deref().unwrap_or("./"),
1358 &self.shared.resource_suffix
1359 ),
1360 &themes);
1361 self.shared.fs.write(&settings_file, v.as_bytes())?;
83c7162d 1362
1a4d82fc
JJ
1363 Ok(())
1364 }
1365
9e0c209e 1366 fn render_item(&self,
9e0c209e 1367 it: &clean::Item,
e1599b0c 1368 pushname: bool) -> String {
9e0c209e
SL
1369 // A little unfortunate that this is done like this, but it sure
1370 // does make formatting *a lot* nicer.
e1599b0c
XL
1371 CURRENT_DEPTH.with(|slot| {
1372 slot.set(self.current.len());
9e0c209e 1373 });
1a4d82fc 1374
0bf4aa26
XL
1375 let mut title = if it.is_primitive() || it.is_keyword() {
1376 // No need to include the namespace for primitive types and keywords
9e0c209e
SL
1377 String::new()
1378 } else {
1379 self.current.join("::")
1380 };
1381 if pushname {
1382 if !title.is_empty() {
1383 title.push_str("::");
1a4d82fc 1384 }
9e0c209e
SL
1385 title.push_str(it.name.as_ref().unwrap());
1386 }
1387 title.push_str(" - Rust");
e74abb32 1388 let tyname = it.type_();
9e0c209e
SL
1389 let desc = if it.is_crate() {
1390 format!("API documentation for the Rust `{}` crate.",
1391 self.shared.layout.krate)
1392 } else {
1393 format!("API documentation for the Rust `{}` {} in crate `{}`.",
1394 it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1395 };
1396 let keywords = make_item_keywords(it);
1397 let page = layout::Page {
e74abb32 1398 css_class: tyname.as_str(),
c30ab7b3 1399 root_path: &self.root_path(),
416331ca 1400 static_root_path: self.shared.static_root_path.as_deref(),
9e0c209e
SL
1401 title: &title,
1402 description: &desc,
1403 keywords: &keywords,
0531ce1d 1404 resource_suffix: &self.shared.resource_suffix,
0731742a
XL
1405 extra_scripts: &[],
1406 static_extra_scripts: &[],
9e0c209e 1407 };
1a4d82fc 1408
b7449926
XL
1409 {
1410 self.id_map.borrow_mut().reset();
1411 self.id_map.borrow_mut().populate(initial_ids());
1412 }
1a4d82fc 1413
9e0c209e 1414 if !self.render_redirect_pages {
e1599b0c
XL
1415 layout::render(&self.shared.layout, &page,
1416 |buf: &mut _| print_sidebar(self, it, buf),
1417 |buf: &mut _| print_item(self, it, buf),
1418 &self.shared.themes)
9e0c209e 1419 } else {
c30ab7b3 1420 let mut url = self.root_path();
e74abb32 1421 if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) {
9e0c209e
SL
1422 for name in &names[..names.len() - 1] {
1423 url.push_str(name);
1424 url.push_str("/");
1a4d82fc 1425 }
9e0c209e 1426 url.push_str(&item_path(ty, names.last().unwrap()));
e1599b0c
XL
1427 layout::redirect(&url)
1428 } else {
1429 String::new()
1a4d82fc 1430 }
1a4d82fc 1431 }
9e0c209e 1432 }
1a4d82fc 1433
9e0c209e
SL
1434 /// Non-parallelized version of rendering an item. This will take the input
1435 /// item, render its contents, and then invoke the specified closure with
1436 /// all sub-items which need to be rendered.
1437 ///
1438 /// The rendering driver uses this closure to queue up more work.
83c7162d
XL
1439 fn item<F>(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error>
1440 where F: FnMut(&mut Context, clean::Item),
9e0c209e 1441 {
0731742a 1442 // Stripped modules survive the rustdoc passes (i.e., `strip-private`)
54a0048b 1443 // if they contain impls for public types. These modules can also
2c00a5a8 1444 // contain items such as publicly re-exported structures.
1a4d82fc
JJ
1445 //
1446 // External crates will provide links to these structures, so
54a0048b
SL
1447 // these modules are recursed into, but not rendered normally
1448 // (a flag on the context).
1a4d82fc 1449 if !self.render_redirect_pages {
041b39d2 1450 self.render_redirect_pages = item.is_stripped();
1a4d82fc
JJ
1451 }
1452
54a0048b 1453 if item.is_mod() {
1a4d82fc
JJ
1454 // modules are special because they add a namespace. We also need to
1455 // recurse into the items of the module as well.
54a0048b 1456 let name = item.name.as_ref().unwrap().to_string();
e1599b0c
XL
1457 let scx = &self.shared;
1458 if name.is_empty() {
1459 panic!("Unexpected empty destination: {:?}", self.current);
1460 }
1461 let prev = self.dst.clone();
1462 self.dst.push(&name);
1463 self.current.push(name);
c34b1796 1464
e1599b0c 1465 info!("Recursing into {}", self.dst.display());
1a4d82fc 1466
e1599b0c
XL
1467 let buf = self.render_item(&item, false);
1468 // buf will be empty if the module is stripped and there is no redirect for it
1469 if !buf.is_empty() {
1470 self.shared.ensure_dir(&self.dst)?;
1471 let joint_dst = self.dst.join("index.html");
1472 scx.fs.write(&joint_dst, buf.as_bytes())?;
1473 }
b039eaaf 1474
e1599b0c
XL
1475 let m = match item.inner {
1476 clean::StrippedItem(box clean::ModuleItem(m)) |
1477 clean::ModuleItem(m) => m,
1478 _ => unreachable!()
1479 };
1480
1481 // Render sidebar-items.js used throughout this module.
1482 if !self.render_redirect_pages {
1483 let items = self.build_sidebar_items(&m);
1484 let js_dst = self.dst.join("sidebar-items.js");
60c5eb7d 1485 let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap());
e1599b0c
XL
1486 scx.fs.write(&js_dst, &v)?;
1487 }
9e0c209e 1488
e1599b0c
XL
1489 for item in m.items {
1490 f(self, item);
1491 }
1492
1493 info!("Recursed; leaving {}", self.dst.display());
1494
1495 // Go back to where we were at
1496 self.dst = prev;
1497 self.current.pop().unwrap();
54a0048b 1498 } else if item.name.is_some() {
e1599b0c 1499 let buf = self.render_item(&item, true);
3157f602
XL
1500 // buf will be empty if the item is stripped and there is no redirect for it
1501 if !buf.is_empty() {
9e0c209e 1502 let name = item.name.as_ref().unwrap();
c30ab7b3 1503 let item_type = item.type_();
9e0c209e 1504 let file_name = &item_path(item_type, name);
dc9dc135 1505 self.shared.ensure_dir(&self.dst)?;
9e0c209e 1506 let joint_dst = self.dst.join(file_name);
e1599b0c 1507 self.shared.fs.write(&joint_dst, buf.as_bytes())?;
9e0c209e 1508
83c7162d
XL
1509 if !self.render_redirect_pages {
1510 all.append(full_path(self, &item), &item_type);
1511 }
9fa01778
XL
1512 if self.shared.generate_redirect_pages {
1513 // Redirect from a sane URL using the namespace to Rustdoc's
1514 // URL for the page.
1515 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1516 let redir_dst = self.dst.join(redir_name);
e1599b0c
XL
1517 let v = layout::redirect(file_name);
1518 self.shared.fs.write(&redir_dst, v.as_bytes())?;
9e0c209e 1519 }
9e0c209e
SL
1520 // If the item is a macro, redirect from the old macro URL (with !)
1521 // to the new one (without).
9e0c209e
SL
1522 if item_type == ItemType::Macro {
1523 let redir_name = format!("{}.{}!.html", item_type, name);
1524 let redir_dst = self.dst.join(redir_name);
e1599b0c
XL
1525 let v = layout::redirect(file_name);
1526 self.shared.fs.write(&redir_dst, v.as_bytes())?;
9e0c209e 1527 }
3157f602 1528 }
1a4d82fc 1529 }
9e0c209e 1530 Ok(())
1a4d82fc
JJ
1531 }
1532
d9579d0f
AL
1533 fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1534 // BTreeMap instead of HashMap to get a sorted output
b7449926 1535 let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new();
85aaf69f 1536 for item in &m.items {
041b39d2 1537 if item.is_stripped() { continue }
1a4d82fc 1538
e74abb32 1539 let short = item.type_();
1a4d82fc
JJ
1540 let myname = match item.name {
1541 None => continue,
1542 Some(ref s) => s.to_string(),
1543 };
1544 let short = short.to_string();
b7449926 1545 map.entry(short).or_default()
c34b1796 1546 .push((myname, Some(plain_summary_line(item.doc_value()))));
1a4d82fc
JJ
1547 }
1548
ff7c6d11
XL
1549 if self.shared.sort_modules_alphabetically {
1550 for (_, items) in &mut map {
1551 items.sort();
1552 }
1a4d82fc 1553 }
c30ab7b3 1554 map
1a4d82fc 1555 }
1a4d82fc
JJ
1556}
1557
e1599b0c 1558impl Context {
9fa01778 1559 /// Generates a url appropriate for an `href` attribute back to the source of
1a4d82fc
JJ
1560 /// this item.
1561 ///
1562 /// The url generated, when clicked, will redirect the browser back to the
1563 /// original source code.
1564 ///
1565 /// If `None` is returned, then a source link couldn't be generated. This
1566 /// may happen, for example, with externally inlined items where the source
1567 /// of their crate documentation isn't known.
e1599b0c
XL
1568 fn src_href(&self, item: &clean::Item) -> Option<String> {
1569 let mut root = self.root_path();
d9579d0f 1570
476ff2be 1571 let mut path = String::new();
ff7c6d11
XL
1572
1573 // We can safely ignore macros from other libraries
e1599b0c 1574 let file = match item.source.filename {
ff7c6d11
XL
1575 FileName::Real(ref path) => path,
1576 _ => return None,
1577 };
1578
e1599b0c
XL
1579 let (krate, path) = if item.def_id.is_local() {
1580 if let Some(path) = self.shared.local_sources.get(file) {
1581 (&self.shared.layout.krate, path)
476ff2be
SL
1582 } else {
1583 return None;
1584 }
1a4d82fc 1585 } else {
e74abb32 1586 let (krate, src_root) = match *self.cache.extern_locations.get(&item.def_id.krate)? {
0731742a
XL
1587 (ref name, ref src, Local) => (name, src),
1588 (ref name, ref src, Remote(ref s)) => {
476ff2be
SL
1589 root = s.to_string();
1590 (name, src)
1591 }
0731742a 1592 (_, _, Unknown) => return None,
476ff2be
SL
1593 };
1594
e1599b0c 1595 sources::clean_path(&src_root, file, false, |component| {
0731742a 1596 path.push_str(&component.to_string_lossy());
476ff2be
SL
1597 path.push('/');
1598 });
1599 let mut fname = file.file_name().expect("source has no filename")
1600 .to_os_string();
1601 fname.push(".html");
1602 path.push_str(&fname.to_string_lossy());
1603 (krate, &path)
1604 };
1605
e1599b0c
XL
1606 let lines = if item.source.loline == item.source.hiline {
1607 item.source.loline.to_string()
476ff2be 1608 } else {
e1599b0c 1609 format!("{}-{}", item.source.loline, item.source.hiline)
476ff2be
SL
1610 };
1611 Some(format!("{root}src/{krate}/{path}#{lines}",
abe05a73 1612 root = Escape(&root),
476ff2be
SL
1613 krate = krate,
1614 path = path,
1615 lines = lines))
1a4d82fc
JJ
1616 }
1617}
1618
e1599b0c
XL
1619fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1620 where F: FnOnce(&mut Buffer)
1621{
1622 write!(w, "<div class=\"docblock type-decl hidden-by-usual-hider\">");
1623 f(w);
0531ce1d
XL
1624 write!(w, "</div>")
1625}
1626
e1599b0c
XL
1627fn print_item(cx: &Context, item: &clean::Item, buf: &mut Buffer) {
1628 debug_assert!(!item.is_stripped());
1629 // Write the breadcrumb trail header for the top
1630 write!(buf, "<h1 class='fqn'><span class='out-of-band'>");
1631 if let Some(version) = item.stable_since() {
1632 write!(buf, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1633 version);
1634 }
1635 write!(buf,
1636 "<span id='render-detail'>\
1637 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
1638 title=\"collapse all docs\">\
1639 [<span class='inner'>&#x2212;</span>]\
1640 </a>\
1641 </span>");
b7449926 1642
e1599b0c
XL
1643 // Write `src` tag
1644 //
1645 // When this item is part of a `pub use` in a downstream crate, the
1646 // [src] link in the downstream documentation will actually come back to
1647 // this page, and this link will be auto-clicked. The `id` attribute is
1648 // used to find the link to auto-click.
1649 if cx.shared.include_sources && !item.is_primitive() {
1650 if let Some(l) = cx.src_href(item) {
1651 write!(buf, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1652 l, "goto source code");
1653 }
1654 }
1655
1656 write!(buf, "</span>"); // out-of-band
1657 write!(buf, "<span class='in-band'>");
1658 let name = match item.inner {
1659 clean::ModuleItem(ref m) => if m.is_crate {
1660 "Crate "
1661 } else {
1662 "Module "
1663 },
1664 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
1665 clean::TraitItem(..) => "Trait ",
1666 clean::StructItem(..) => "Struct ",
1667 clean::UnionItem(..) => "Union ",
1668 clean::EnumItem(..) => "Enum ",
1669 clean::TypedefItem(..) => "Type Definition ",
1670 clean::MacroItem(..) => "Macro ",
1671 clean::ProcMacroItem(ref mac) => match mac.kind {
1672 MacroKind::Bang => "Macro ",
1673 MacroKind::Attr => "Attribute Macro ",
1674 MacroKind::Derive => "Derive Macro ",
1675 }
1676 clean::PrimitiveItem(..) => "Primitive Type ",
1677 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
1678 clean::ConstantItem(..) => "Constant ",
1679 clean::ForeignTypeItem => "Foreign Type ",
1680 clean::KeywordItem(..) => "Keyword ",
1681 clean::OpaqueTyItem(..) => "Opaque Type ",
1682 clean::TraitAliasItem(..) => "Trait Alias ",
1683 _ => {
1684 // We don't generate pages for any other type.
1685 unreachable!();
1a4d82fc 1686 }
e1599b0c
XL
1687 };
1688 buf.write_str(name);
1689 if !item.is_primitive() && !item.is_keyword() {
1690 let cur = &cx.current;
1691 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
1692 for (i, component) in cur.iter().enumerate().take(amt) {
1693 write!(buf, "<a href='{}index.html'>{}</a>::<wbr>",
1694 "../".repeat(cur.len() - i - 1),
1695 component);
1a4d82fc 1696 }
e1599b0c
XL
1697 }
1698 write!(buf, "<a class=\"{}\" href=''>{}</a>",
1699 item.type_(), item.name.as_ref().unwrap());
1700
1701 write!(buf, "</span></h1>"); // in-band
1702
1703 match item.inner {
1704 clean::ModuleItem(ref m) =>
1705 item_module(buf, cx, item, &m.items),
1706 clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1707 item_function(buf, cx, item, f),
1708 clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
1709 clean::StructItem(ref s) => item_struct(buf, cx, item, s),
1710 clean::UnionItem(ref s) => item_union(buf, cx, item, s),
1711 clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
1712 clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t),
1713 clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
1714 clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
e74abb32 1715 clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
e1599b0c
XL
1716 clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1717 item_static(buf, cx, item, i),
1718 clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
1719 clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
e74abb32 1720 clean::KeywordItem(_) => item_keyword(buf, cx, item),
e1599b0c
XL
1721 clean::OpaqueTyItem(ref e, _) => item_opaque_ty(buf, cx, item, e),
1722 clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
1723 _ => {
1724 // We don't generate pages for any other type.
1725 unreachable!();
1a4d82fc
JJ
1726 }
1727 }
1728}
1729
3157f602
XL
1730fn item_path(ty: ItemType, name: &str) -> String {
1731 match ty {
e74abb32
XL
1732 ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1733 _ => format!("{}.{}.html", ty, name),
1a4d82fc
JJ
1734 }
1735}
1736
1737fn full_path(cx: &Context, item: &clean::Item) -> String {
c1a9b12d 1738 let mut s = cx.current.join("::");
1a4d82fc 1739 s.push_str("::");
85aaf69f 1740 s.push_str(item.name.as_ref().unwrap());
c30ab7b3 1741 s
1a4d82fc
JJ
1742}
1743
85aaf69f 1744#[inline]
c34b1796 1745fn plain_summary_line(s: Option<&str>) -> String {
e1599b0c
XL
1746 let s = s.unwrap_or("");
1747 // This essentially gets the first paragraph of text in one line.
1748 let mut line = s.lines()
1749 .skip_while(|line| line.chars().all(|c| c.is_whitespace()))
1750 .take_while(|line| line.chars().any(|c| !c.is_whitespace()))
1751 .fold(String::new(), |mut acc, line| {
1752 acc.push_str(line);
1753 acc.push(' ');
1754 acc
1755 });
1756 // remove final whitespace
1757 line.pop();
1758 markdown::plain_summary_line(&line[..])
1759}
1760
1761fn shorten(s: String) -> String {
1762 if s.chars().count() > 60 {
1763 let mut len = 0;
1764 let mut ret = s.split_whitespace()
1765 .take_while(|p| {
1766 // + 1 for the added character after the word.
1767 len += p.chars().count() + 1;
1768 len < 60
1769 })
1770 .collect::<Vec<_>>()
1771 .join(" ");
1772 ret.push('…');
1773 ret
1774 } else {
1775 s
1776 }
85aaf69f
SL
1777}
1778
e1599b0c 1779fn document(w: &mut Buffer, cx: &Context, item: &clean::Item) {
ff7c6d11
XL
1780 if let Some(ref name) = item.name {
1781 info!("Documenting {}", name);
1782 }
e1599b0c
XL
1783 document_stability(w, cx, item, false);
1784 document_full(w, item, cx, "", false);
1a4d82fc
JJ
1785}
1786
0531ce1d 1787/// Render md_text as markdown.
e1599b0c
XL
1788fn render_markdown(
1789 w: &mut Buffer,
1790 cx: &Context,
1791 md_text: &str,
1792 links: Vec<(String, String)>,
1793 prefix: &str,
1794 is_hidden: bool,
1795) {
b7449926 1796 let mut ids = cx.id_map.borrow_mut();
a1dfa0c6
XL
1797 write!(w, "<div class='docblock{}'>{}{}</div>",
1798 if is_hidden { " hidden" } else { "" },
1799 prefix,
416331ca 1800 Markdown(md_text, &links, &mut ids,
e74abb32 1801 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string())
ea8adc8c
XL
1802}
1803
9fa01778 1804fn document_short(
e1599b0c 1805 w: &mut Buffer,
9fa01778
XL
1806 cx: &Context,
1807 item: &clean::Item,
1808 link: AssocItemLink<'_>,
e1599b0c
XL
1809 prefix: &str,
1810 is_hidden: bool,
1811) {
a7813a04
XL
1812 if let Some(s) = item.doc_value() {
1813 let markdown = if s.contains('\n') {
1814 format!("{} [Read more]({})",
1815 &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1816 } else {
0bf4aa26 1817 plain_summary_line(Some(s))
a7813a04 1818 };
e1599b0c 1819 render_markdown(w, cx, &markdown, item.links(), prefix, is_hidden);
041b39d2 1820 } else if !prefix.is_empty() {
a1dfa0c6
XL
1821 write!(w, "<div class='docblock{}'>{}</div>",
1822 if is_hidden { " hidden" } else { "" },
e1599b0c 1823 prefix);
a7813a04 1824 }
a7813a04
XL
1825}
1826
e1599b0c 1827fn document_full(w: &mut Buffer, item: &clean::Item, cx: &Context, prefix: &str, is_hidden: bool) {
ff7c6d11
XL
1828 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1829 debug!("Doc block: =====\n{}\n=====", s);
e1599b0c 1830 render_markdown(w, cx, &*s, item.links(), prefix, is_hidden);
041b39d2 1831 } else if !prefix.is_empty() {
a1dfa0c6
XL
1832 write!(w, "<div class='docblock{}'>{}</div>",
1833 if is_hidden { " hidden" } else { "" },
e1599b0c 1834 prefix);
3157f602 1835 }
3157f602
XL
1836}
1837
e1599b0c 1838fn document_stability(w: &mut Buffer, cx: &Context, item: &clean::Item, is_hidden: bool) {
0731742a 1839 let stabilities = short_stability(item, cx);
32a655c1 1840 if !stabilities.is_empty() {
e1599b0c 1841 write!(w, "<div class='stability{}'>", if is_hidden { " hidden" } else { "" });
32a655c1 1842 for stability in stabilities {
e1599b0c 1843 write!(w, "{}", stability);
32a655c1 1844 }
e1599b0c 1845 write!(w, "</div>");
3157f602 1846 }
3157f602
XL
1847}
1848
8faf50e0
XL
1849fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1850 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1851}
1852
e1599b0c 1853fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
8faf50e0
XL
1854 if item.is_non_exhaustive() {
1855 write!(w, "<div class='docblock non-exhaustive non-exhaustive-{}'>", {
532ac7d7
XL
1856 if item.is_struct() {
1857 "struct"
1858 } else if item.is_enum() {
1859 "enum"
1860 } else if item.is_variant() {
1861 "variant"
1862 } else {
1863 "type"
1864 }
e1599b0c 1865 });
8faf50e0
XL
1866
1867 if item.is_struct() {
1868 write!(w, "Non-exhaustive structs could have additional fields added in future. \
1869 Therefore, non-exhaustive structs cannot be constructed in external crates \
1870 using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \
1871 matched against without a wildcard <code>..</code>; and \
e1599b0c 1872 struct update syntax will not work.");
8faf50e0
XL
1873 } else if item.is_enum() {
1874 write!(w, "Non-exhaustive enums could have additional variants added in future. \
1875 Therefore, when matching against variants of non-exhaustive enums, an \
e1599b0c 1876 extra wildcard arm must be added to account for any future variants.");
532ac7d7
XL
1877 } else if item.is_variant() {
1878 write!(w, "Non-exhaustive enum variants could have additional fields added in future. \
1879 Therefore, non-exhaustive enum variants cannot be constructed in external \
e1599b0c 1880 crates and cannot be matched against.");
8faf50e0
XL
1881 } else {
1882 write!(w, "This type will require a wildcard arm in any match statements or \
e1599b0c 1883 constructors.");
8faf50e0
XL
1884 }
1885
e1599b0c 1886 write!(w, "</div>");
8faf50e0 1887 }
8faf50e0
XL
1888}
1889
cc61c64b 1890fn name_key(name: &str) -> (&str, u64, usize) {
b7449926
XL
1891 let end = name.bytes()
1892 .rposition(|b| b.is_ascii_digit()).map_or(name.len(), |i| i + 1);
1893
cc61c64b 1894 // find number at end
b7449926
XL
1895 let split = name[0..end].bytes()
1896 .rposition(|b| !b.is_ascii_digit()).map_or(0, |i| i + 1);
cc61c64b
XL
1897
1898 // count leading zeroes
1899 let after_zeroes =
b7449926 1900 name[split..end].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
cc61c64b
XL
1901
1902 // sort leading zeroes last
1903 let num_zeroes = after_zeroes - split;
1904
b7449926 1905 match name[split..end].parse() {
cc61c64b
XL
1906 Ok(n) => (&name[..split], n, num_zeroes),
1907 Err(_) => (name, 0, num_zeroes),
1908 }
1909}
1910
e1599b0c
XL
1911fn item_module(w: &mut Buffer, cx: &Context, item: &clean::Item, items: &[clean::Item]) {
1912 document(w, cx, item);
1a4d82fc 1913
0531ce1d 1914 let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
1a4d82fc
JJ
1915
1916 // the order of item types in the listing
1917 fn reorder(ty: ItemType) -> u8 {
1918 match ty {
85aaf69f
SL
1919 ItemType::ExternCrate => 0,
1920 ItemType::Import => 1,
1921 ItemType::Primitive => 2,
1922 ItemType::Module => 3,
1923 ItemType::Macro => 4,
1924 ItemType::Struct => 5,
1925 ItemType::Enum => 6,
1926 ItemType::Constant => 7,
1927 ItemType::Static => 8,
1928 ItemType::Trait => 9,
1929 ItemType::Function => 10,
1930 ItemType::Typedef => 12,
9e0c209e
SL
1931 ItemType::Union => 13,
1932 _ => 14 + ty as u8,
1a4d82fc
JJ
1933 }
1934 }
1935
c34b1796 1936 fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
c30ab7b3
SL
1937 let ty1 = i1.type_();
1938 let ty2 = i2.type_();
d9579d0f
AL
1939 if ty1 != ty2 {
1940 return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1941 }
1942 let s1 = i1.stability.as_ref().map(|s| s.level);
1943 let s2 = i2.stability.as_ref().map(|s| s.level);
1944 match (s1, s2) {
b039eaaf
SL
1945 (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1946 (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
d9579d0f 1947 _ => {}
1a4d82fc 1948 }
cc61c64b
XL
1949 let lhs = i1.name.as_ref().map_or("", |s| &**s);
1950 let rhs = i2.name.as_ref().map_or("", |s| &**s);
1951 name_key(lhs).cmp(&name_key(rhs))
1a4d82fc
JJ
1952 }
1953
ff7c6d11
XL
1954 if cx.shared.sort_modules_alphabetically {
1955 indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1956 }
2c00a5a8 1957 // This call is to remove re-export duplicates in cases such as:
3b2f2976
XL
1958 //
1959 // ```
1960 // pub mod foo {
1961 // pub mod bar {
1962 // pub trait Double { fn foo(); }
1963 // }
1964 // }
1965 //
1966 // pub use foo::bar::*;
1967 // pub use foo::*;
1968 // ```
1969 //
1970 // `Double` will appear twice in the generated docs.
1971 //
1972 // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1973 // can be identical even if the elements are different (mostly in imports).
1974 // So in case this is an import, we keep everything by adding a "unique id"
1975 // (which is the position in the vector).
1976 indices.dedup_by_key(|i| (items[*i].def_id,
1977 if items[*i].name.as_ref().is_some() {
0bf4aa26 1978 Some(full_path(cx, &items[*i]))
3b2f2976
XL
1979 } else {
1980 None
1981 },
1982 items[*i].type_(),
1983 if items[*i].is_import() {
1984 *i
1985 } else {
1986 0
1987 }));
1a4d82fc
JJ
1988
1989 debug!("{:?}", indices);
1990 let mut curty = None;
85aaf69f 1991 for &idx in &indices {
1a4d82fc 1992 let myitem = &items[idx];
54a0048b
SL
1993 if myitem.is_stripped() {
1994 continue;
1995 }
1a4d82fc 1996
c30ab7b3 1997 let myty = Some(myitem.type_());
85aaf69f
SL
1998 if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1999 // Put `extern crate` and `use` re-exports in the same section.
2000 curty = myty;
2001 } else if myty != curty {
1a4d82fc 2002 if curty.is_some() {
e1599b0c 2003 write!(w, "</table>");
1a4d82fc
JJ
2004 }
2005 curty = myty;
94b46f34 2006 let (short, name) = item_ty_to_strs(&myty.unwrap());
54a0048b
SL
2007 write!(w, "<h2 id='{id}' class='section-header'>\
2008 <a href=\"#{id}\">{name}</a></h2>\n<table>",
e1599b0c 2009 id = cx.derive_id(short.to_owned()), name = name);
1a4d82fc
JJ
2010 }
2011
2012 match myitem.inner {
85aaf69f 2013 clean::ExternCrateItem(ref name, ref src) => {
e1599b0c 2014 use crate::html::format::anchor;
a7813a04 2015
85aaf69f
SL
2016 match *src {
2017 Some(ref src) => {
54a0048b 2018 write!(w, "<tr><td><code>{}extern crate {} as {};",
e74abb32 2019 myitem.visibility.print_with_space(),
e1599b0c
XL
2020 anchor(myitem.def_id, src),
2021 name)
1a4d82fc 2022 }
85aaf69f 2023 None => {
54a0048b 2024 write!(w, "<tr><td><code>{}extern crate {};",
e74abb32 2025 myitem.visibility.print_with_space(),
e1599b0c 2026 anchor(myitem.def_id, name))
1a4d82fc
JJ
2027 }
2028 }
e1599b0c 2029 write!(w, "</code></td></tr>");
85aaf69f 2030 }
1a4d82fc 2031
85aaf69f 2032 clean::ImportItem(ref import) => {
54a0048b 2033 write!(w, "<tr><td><code>{}{}</code></td></tr>",
e74abb32 2034 myitem.visibility.print_with_space(), import.print());
1a4d82fc
JJ
2035 }
2036
2037 _ => {
2038 if myitem.name.is_none() { continue }
a7813a04 2039
8bb4bdeb
XL
2040 let unsafety_flag = match myitem.inner {
2041 clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
8faf50e0 2042 if func.header.unsafety == hir::Unsafety::Unsafe => {
8bb4bdeb 2043 "<a title='unsafe function' href='#'><sup>⚠</sup></a>"
476ff2be 2044 }
8bb4bdeb
XL
2045 _ => "",
2046 };
476ff2be 2047
a1dfa0c6
XL
2048 let stab = myitem.stability_class();
2049 let add = if stab.is_some() {
2050 " "
2051 } else {
2052 ""
2053 };
2054
7453a54e 2055 let doc_value = myitem.doc_value().unwrap_or("");
a1dfa0c6
XL
2056 write!(w, "\
2057 <tr class='{stab}{add}module-item'>\
2058 <td><a class=\"{class}\" href=\"{href}\" \
2059 title='{title}'>{name}</a>{unsafety_flag}</td>\
9fa01778 2060 <td class='docblock-short'>{stab_tags}{docs}</td>\
54a0048b
SL
2061 </tr>",
2062 name = *myitem.name.as_ref().unwrap(),
0731742a 2063 stab_tags = stability_tags(myitem),
416331ca 2064 docs = MarkdownSummaryLine(doc_value, &myitem.links()).to_string(),
c30ab7b3 2065 class = myitem.type_(),
a1dfa0c6
XL
2066 add = add,
2067 stab = stab.unwrap_or_else(|| String::new()),
476ff2be 2068 unsafety_flag = unsafety_flag,
c30ab7b3 2069 href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
a1dfa0c6
XL
2070 title = [full_path(cx, myitem), myitem.type_().to_string()]
2071 .iter()
2072 .filter_map(|s| if !s.is_empty() {
2073 Some(s.as_str())
2074 } else {
2075 None
2076 })
2077 .collect::<Vec<_>>()
2078 .join(" "),
e1599b0c 2079 );
1a4d82fc
JJ
2080 }
2081 }
2082 }
2083
3157f602 2084 if curty.is_some() {
e1599b0c 2085 write!(w, "</table>");
3157f602 2086 }
1a4d82fc
JJ
2087}
2088
0731742a
XL
2089/// Render the stability and deprecation tags that are displayed in the item's summary at the
2090/// module level.
2091fn stability_tags(item: &clean::Item) -> String {
2092 let mut tags = String::new();
2093
9fa01778
XL
2094 fn tag_html(class: &str, contents: &str) -> String {
2095 format!(r#"<span class="stab {}">{}</span>"#, class, contents)
2096 }
2097
0731742a
XL
2098 // The trailing space after each tag is to space it properly against the rest of the docs.
2099 if item.deprecation().is_some() {
9fa01778
XL
2100 let mut message = "Deprecated";
2101 if let Some(ref stab) = item.stability {
2102 if let Some(ref depr) = stab.deprecation {
2103 if let Some(ref since) = depr.since {
2104 if !stability::deprecation_in_effect(&since) {
2105 message = "Deprecation planned";
2106 }
2107 }
2108 }
2109 }
2110 tags += &tag_html("deprecated", message);
0731742a
XL
2111 }
2112
2113 if let Some(stab) = item
2114 .stability
2115 .as_ref()
2116 .filter(|s| s.level == stability::Unstable)
2117 {
2118 if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
9fa01778 2119 tags += &tag_html("internal", "Internal");
0731742a 2120 } else {
9fa01778 2121 tags += &tag_html("unstable", "Experimental");
0731742a
XL
2122 }
2123 }
2124
2125 if let Some(ref cfg) = item.attrs.cfg {
9fa01778 2126 tags += &tag_html("portability", &cfg.render_short_html());
0731742a
XL
2127 }
2128
2129 tags
2130}
2131
2132/// Render the stability and/or deprecation warning that is displayed at the top of the item's
2133/// documentation.
2134fn short_stability(item: &clean::Item, cx: &Context) -> Vec<String> {
a7813a04 2135 let mut stability = vec![];
e74abb32 2136 let error_codes = cx.shared.codes;
a7813a04 2137
9fa01778
XL
2138 if let Some(Deprecation { note, since }) = &item.deprecation() {
2139 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
2140 // but only display the future-deprecation messages for #[rustc_deprecated].
0731742a 2141 let mut message = if let Some(since) = since {
9fa01778 2142 format!("Deprecated since {}", Escape(since))
d9579d0f 2143 } else {
0731742a 2144 String::from("Deprecated")
d9579d0f 2145 };
9fa01778
XL
2146 if let Some(ref stab) = item.stability {
2147 if let Some(ref depr) = stab.deprecation {
2148 if let Some(ref since) = depr.since {
2149 if !stability::deprecation_in_effect(&since) {
2150 message = format!("Deprecating in {}", Escape(&since));
2151 }
2152 }
2153 }
2154 }
0731742a
XL
2155
2156 if let Some(note) = note {
b7449926 2157 let mut ids = cx.id_map.borrow_mut();
e74abb32
XL
2158 let html = MarkdownHtml(
2159 &note, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground);
416331ca 2160 message.push_str(&format!(": {}", html.to_string()));
0731742a
XL
2161 }
2162 stability.push(format!("<div class='stab deprecated'>{}</div>", message));
2163 }
2164
2165 if let Some(stab) = item
2166 .stability
2167 .as_ref()
2168 .filter(|stab| stab.level == stability::Unstable)
2169 {
2170 let is_rustc_private = stab.feature.as_ref().map(|s| &**s) == Some("rustc_private");
2171
2172 let mut message = if is_rustc_private {
2173 "<span class='emoji'>⚙️</span> This is an internal compiler API."
2174 } else {
2175 "<span class='emoji'>🔬</span> This is a nightly-only experimental API."
2176 }
2177 .to_owned();
2178
2179 if let Some(feature) = stab.feature.as_ref() {
2180 let mut feature = format!("<code>{}</code>", Escape(&feature));
2181 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, stab.issue) {
2182 feature.push_str(&format!(
2183 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
2184 url = url,
2185 issue = issue
2186 ));
2187 }
2188
2189 message.push_str(&format!(" ({})", feature));
2190 }
2191
2192 if let Some(unstable_reason) = &stab.unstable_reason {
2193 // Provide a more informative message than the compiler help.
2194 let unstable_reason = if is_rustc_private {
2195 "This crate is being loaded from the sysroot, a permanently unstable location \
2196 for private compiler dependencies. It is not intended for general use. Prefer \
2197 using a public version of this crate from \
2198 [crates.io](https://crates.io) via [`Cargo.toml`]\
2199 (https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html)."
83c7162d 2200 } else {
0731742a 2201 unstable_reason
83c7162d 2202 };
a7813a04 2203
0731742a
XL
2204 let mut ids = cx.id_map.borrow_mut();
2205 message = format!(
2206 "<details><summary>{}</summary>{}</details>",
2207 message,
416331ca
XL
2208 MarkdownHtml(
2209 &unstable_reason,
2210 &mut ids,
2211 error_codes,
e74abb32
XL
2212 cx.shared.edition,
2213 &cx.shared.playground,
416331ca 2214 ).to_string()
0731742a
XL
2215 );
2216 }
9cc50fc6 2217
0731742a
XL
2218 let class = if is_rustc_private {
2219 "internal"
83c7162d 2220 } else {
0731742a 2221 "unstable"
83c7162d 2222 };
0731742a 2223 stability.push(format!("<div class='stab {}'>{}</div>", class, message));
a7813a04
XL
2224 }
2225
3b2f2976 2226 if let Some(ref cfg) = item.attrs.cfg {
0731742a
XL
2227 stability.push(format!(
2228 "<div class='stab portability'>{}</div>",
3b2f2976 2229 cfg.render_long_html()
0731742a 2230 ));
3b2f2976
XL
2231 }
2232
a7813a04 2233 stability
d9579d0f
AL
2234}
2235
e1599b0c
XL
2236fn item_constant(w: &mut Buffer, cx: &Context, it: &clean::Item, c: &clean::Constant) {
2237 write!(w, "<pre class='rust const'>");
2238 render_attributes(w, it, false);
8bb4bdeb 2239 write!(w, "{vis}const \
b7449926 2240 {name}: {typ}</pre>",
e74abb32 2241 vis = it.visibility.print_with_space(),
85aaf69f 2242 name = it.name.as_ref().unwrap(),
e74abb32 2243 typ = c.type_.print());
e9174d1e 2244 document(w, cx, it)
1a4d82fc
JJ
2245}
2246
e1599b0c
XL
2247fn item_static(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Static) {
2248 write!(w, "<pre class='rust static'>");
2249 render_attributes(w, it, false);
8bb4bdeb 2250 write!(w, "{vis}static {mutability}\
b7449926 2251 {name}: {typ}</pre>",
e74abb32
XL
2252 vis = it.visibility.print_with_space(),
2253 mutability = s.mutability.print_with_space(),
85aaf69f 2254 name = it.name.as_ref().unwrap(),
e74abb32 2255 typ = s.type_.print());
e9174d1e 2256 document(w, cx, it)
1a4d82fc
JJ
2257}
2258
e1599b0c 2259fn item_function(w: &mut Buffer, cx: &Context, it: &clean::Item, f: &clean::Function) {
9fa01778
XL
2260 let header_len = format!(
2261 "{}{}{}{}{:#}fn {}{:#}",
e74abb32
XL
2262 it.visibility.print_with_space(),
2263 f.header.constness.print_with_space(),
2264 f.header.unsafety.print_with_space(),
2265 f.header.asyncness.print_with_space(),
2266 print_abi_with_space(f.header.abi),
9fa01778 2267 it.name.as_ref().unwrap(),
e74abb32 2268 f.generics.print()
9fa01778 2269 ).len();
e1599b0c
XL
2270 write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it));
2271 render_attributes(w, it, false);
ff7c6d11 2272 write!(w,
8faf50e0
XL
2273 "{vis}{constness}{unsafety}{asyncness}{abi}fn \
2274 {name}{generics}{decl}{where_clause}</pre>",
e74abb32
XL
2275 vis = it.visibility.print_with_space(),
2276 constness = f.header.constness.print_with_space(),
2277 unsafety = f.header.unsafety.print_with_space(),
2278 asyncness = f.header.asyncness.print_with_space(),
2279 abi = print_abi_with_space(f.header.abi),
85aaf69f 2280 name = it.name.as_ref().unwrap(),
e74abb32 2281 generics = f.generics.print(),
cc61c64b 2282 where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
9fa01778 2283 decl = Function {
ff7c6d11 2284 decl: &f.decl,
9fa01778 2285 header_len,
ff7c6d11 2286 indent: 0,
9fa01778 2287 asyncness: f.header.asyncness,
e74abb32 2288 }.print());
e9174d1e 2289 document(w, cx, it)
1a4d82fc
JJ
2290}
2291
e1599b0c
XL
2292fn render_implementor(cx: &Context, implementor: &Impl, w: &mut Buffer,
2293 implementor_dups: &FxHashMap<&str, (DefId, bool)>) {
0531ce1d
XL
2294 // If there's already another implementor that has the same abbridged name, use the
2295 // full path, for example in `std::iter::ExactSizeIterator`
2296 let use_absolute = match implementor.inner_impl().for_ {
2297 clean::ResolvedPath { ref path, is_generic: false, .. } |
2298 clean::BorrowedRef {
2299 type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2300 ..
2301 } => implementor_dups[path.last_name()].1,
2302 _ => false,
2303 };
b7449926 2304 render_impl(w, cx, implementor, AssocItemLink::Anchor(None), RenderMode::Normal,
e1599b0c 2305 implementor.impl_item.stable_since(), false, Some(use_absolute), false, false);
0531ce1d
XL
2306}
2307
e1599b0c 2308fn render_impls(cx: &Context, w: &mut Buffer,
83c7162d 2309 traits: &[&&Impl],
e1599b0c 2310 containing_item: &clean::Item) {
60c5eb7d
XL
2311 let mut impls = traits.iter()
2312 .map(|i| {
2313 let did = i.trait_did().unwrap();
2314 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
2315 let mut buffer = if w.is_for_html() {
2316 Buffer::html()
2317 } else {
2318 Buffer::new()
2319 };
2320 render_impl(&mut buffer, cx, i, assoc_link,
2321 RenderMode::Normal, containing_item.stable_since(),
2322 true, None, false, true);
2323 buffer.into_inner()
2324 })
2325 .collect::<Vec<_>>();
2326 impls.sort();
2327 w.write_str(&impls.join(""));
0531ce1d
XL
2328}
2329
9fa01778 2330fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
1a4d82fc 2331 let mut bounds = String::new();
8faf50e0 2332 if !t_bounds.is_empty() {
9fa01778
XL
2333 if !trait_alias {
2334 bounds.push_str(": ");
1a4d82fc 2335 }
8faf50e0 2336 for (i, p) in t_bounds.iter().enumerate() {
476ff2be
SL
2337 if i > 0 {
2338 bounds.push_str(" + ");
476ff2be 2339 }
e74abb32 2340 bounds.push_str(&p.print().to_string());
1a4d82fc
JJ
2341 }
2342 }
8faf50e0
XL
2343 bounds
2344}
1a4d82fc 2345
b7449926 2346fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl) -> Ordering {
e74abb32
XL
2347 let lhs = format!("{}", lhs.inner_impl().print());
2348 let rhs = format!("{}", rhs.inner_impl().print());
b7449926
XL
2349
2350 // lhs and rhs are formatted as HTML, which may be unnecessary
2351 name_key(&lhs).cmp(&name_key(&rhs))
2352}
2353
8faf50e0 2354fn item_trait(
e1599b0c 2355 w: &mut Buffer,
8faf50e0
XL
2356 cx: &Context,
2357 it: &clean::Item,
2358 t: &clean::Trait,
e1599b0c 2359) {
9fa01778 2360 let bounds = bounds(&t.bounds, false);
54a0048b
SL
2361 let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2362 let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2363 let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2364 let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
1a4d82fc 2365
0531ce1d
XL
2366 // Output the trait definition
2367 wrap_into_docblock(w, |w| {
e1599b0c
XL
2368 write!(w, "<pre class='rust trait'>");
2369 render_attributes(w, it, true);
0531ce1d 2370 write!(w, "{}{}{}trait {}{}{}",
e74abb32
XL
2371 it.visibility.print_with_space(),
2372 t.unsafety.print_with_space(),
0531ce1d
XL
2373 if t.is_auto { "auto " } else { "" },
2374 it.name.as_ref().unwrap(),
e74abb32 2375 t.generics.print(),
e1599b0c 2376 bounds);
0531ce1d
XL
2377
2378 if !t.generics.where_predicates.is_empty() {
e1599b0c 2379 write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true });
0531ce1d 2380 } else {
e1599b0c 2381 write!(w, " ");
1a4d82fc 2382 }
041b39d2 2383
0531ce1d 2384 if t.items.is_empty() {
e1599b0c 2385 write!(w, "{{ }}");
0531ce1d
XL
2386 } else {
2387 // FIXME: we should be using a derived_id for the Anchors here
e1599b0c 2388 write!(w, "{{\n");
0531ce1d 2389 for t in &types {
e1599b0c
XL
2390 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2391 write!(w, ";\n");
041b39d2 2392 }
0531ce1d 2393 if !types.is_empty() && !consts.is_empty() {
e1599b0c 2394 w.write_str("\n");
0531ce1d
XL
2395 }
2396 for t in &consts {
e1599b0c
XL
2397 render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait);
2398 write!(w, ";\n");
0531ce1d
XL
2399 }
2400 if !consts.is_empty() && !required.is_empty() {
e1599b0c 2401 w.write_str("\n");
0531ce1d
XL
2402 }
2403 for (pos, m) in required.iter().enumerate() {
e1599b0c
XL
2404 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
2405 write!(w, ";\n");
0531ce1d
XL
2406
2407 if pos < required.len() - 1 {
e1599b0c 2408 write!(w, "<div class='item-spacer'></div>");
0531ce1d
XL
2409 }
2410 }
2411 if !required.is_empty() && !provided.is_empty() {
e1599b0c 2412 w.write_str("\n");
cc61c64b 2413 }
0531ce1d 2414 for (pos, m) in provided.iter().enumerate() {
e1599b0c 2415 render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait);
0531ce1d
XL
2416 match m.inner {
2417 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
e1599b0c 2418 write!(w, ",\n {{ ... }}\n");
0531ce1d
XL
2419 },
2420 _ => {
e1599b0c 2421 write!(w, " {{ ... }}\n");
0531ce1d
XL
2422 },
2423 }
2424 if pos < provided.len() - 1 {
e1599b0c 2425 write!(w, "<div class='item-spacer'></div>");
0531ce1d 2426 }
041b39d2 2427 }
e1599b0c 2428 write!(w, "}}");
1a4d82fc 2429 }
0531ce1d 2430 write!(w, "</pre>")
e1599b0c 2431 });
1a4d82fc
JJ
2432
2433 // Trait documentation
e1599b0c 2434 document(w, cx, it);
1a4d82fc 2435
0731742a 2436 fn write_small_section_header(
e1599b0c 2437 w: &mut Buffer,
0731742a
XL
2438 id: &str,
2439 title: &str,
2440 extra_content: &str,
e1599b0c 2441 ) {
0731742a
XL
2442 write!(w, "
2443 <h2 id='{0}' class='small-section-header'>\
2444 {1}<a href='#{0}' class='anchor'></a>\
2445 </h2>{2}", id, title, extra_content)
2446 }
2447
e1599b0c 2448 fn write_loading_content(w: &mut Buffer, extra_content: &str) {
0731742a
XL
2449 write!(w, "{}<span class='loading-content'>Loading content...</span>", extra_content)
2450 }
2451
e1599b0c 2452 fn trait_item(w: &mut Buffer, cx: &Context, m: &clean::Item, t: &clean::Item) {
92a42be0 2453 let name = m.name.as_ref().unwrap();
c30ab7b3 2454 let item_type = m.type_();
b7449926
XL
2455 let id = cx.derive_id(format!("{}.{}", item_type, name));
2456 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
0731742a 2457 write!(w, "<h3 id='{id}' class='method'>{extra}<code id='{ns_id}'>",
e1599b0c 2458 extra = render_spotlight_traits(m),
54a0048b 2459 id = id,
e1599b0c
XL
2460 ns_id = ns_id);
2461 render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl);
2462 write!(w, "</code>");
2463 render_stability_since(w, m, t);
2464 write!(w, "</h3>");
2465 document(w, cx, m);
1a4d82fc
JJ
2466 }
2467
9346a6ac 2468 if !types.is_empty() {
0731742a 2469 write_small_section_header(w, "associated-types", "Associated Types",
e1599b0c 2470 "<div class='methods'>");
85aaf69f 2471 for t in &types {
e1599b0c 2472 trait_item(w, cx, *t, it);
1a4d82fc 2473 }
e1599b0c 2474 write_loading_content(w, "</div>");
1a4d82fc
JJ
2475 }
2476
d9579d0f 2477 if !consts.is_empty() {
0731742a 2478 write_small_section_header(w, "associated-const", "Associated Constants",
e1599b0c 2479 "<div class='methods'>");
d9579d0f 2480 for t in &consts {
e1599b0c 2481 trait_item(w, cx, *t, it);
d9579d0f 2482 }
e1599b0c 2483 write_loading_content(w, "</div>");
d9579d0f
AL
2484 }
2485
1a4d82fc 2486 // Output the documentation for each function individually
9346a6ac 2487 if !required.is_empty() {
0731742a 2488 write_small_section_header(w, "required-methods", "Required methods",
e1599b0c 2489 "<div class='methods'>");
85aaf69f 2490 for m in &required {
e1599b0c 2491 trait_item(w, cx, *m, it);
1a4d82fc 2492 }
e1599b0c 2493 write_loading_content(w, "</div>");
1a4d82fc 2494 }
9346a6ac 2495 if !provided.is_empty() {
0731742a 2496 write_small_section_header(w, "provided-methods", "Provided methods",
e1599b0c 2497 "<div class='methods'>");
85aaf69f 2498 for m in &provided {
e1599b0c 2499 trait_item(w, cx, *m, it);
1a4d82fc 2500 }
e1599b0c 2501 write_loading_content(w, "</div>");
1a4d82fc
JJ
2502 }
2503
9346a6ac 2504 // If there are methods directly on this trait object, render them here.
e1599b0c 2505 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All);
9346a6ac 2506
0531ce1d
XL
2507 let mut synthetic_types = Vec::new();
2508
e74abb32 2509 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
8bb4bdeb
XL
2510 // The DefId is for the first Type found with that name. The bool is
2511 // if any Types with the same name but different DefId have been found.
0bf4aa26 2512 let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap::default();
32a655c1 2513 for implementor in implementors {
2c00a5a8 2514 match implementor.inner_impl().for_ {
8bb4bdeb
XL
2515 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2516 clean::BorrowedRef {
2517 type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2518 ..
2519 } => {
2520 let &mut (prev_did, ref mut has_duplicates) =
2521 implementor_dups.entry(path.last_name()).or_insert((did, false));
2522 if prev_did != did {
2523 *has_duplicates = true;
2524 }
2525 }
2526 _ => {}
32a655c1
SL
2527 }
2528 }
2529
ea8adc8c 2530 let (local, foreign) = implementors.iter()
2c00a5a8 2531 .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
e74abb32 2532 .map_or(true, |d| cx.cache.paths.contains_key(&d)));
ea8adc8c 2533
0531ce1d 2534
b7449926 2535 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter()
8faf50e0 2536 .partition(|i| i.inner_impl().synthetic);
0531ce1d 2537
b7449926
XL
2538 synthetic.sort_by(compare_impl);
2539 concrete.sort_by(compare_impl);
2540
ea8adc8c 2541 if !foreign.is_empty() {
e1599b0c 2542 write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
ea8adc8c
XL
2543
2544 for implementor in foreign {
2c00a5a8 2545 let assoc_link = AssocItemLink::GotoSource(
b7449926
XL
2546 implementor.impl_item.def_id,
2547 &implementor.inner_impl().provided_trait_methods
2c00a5a8
XL
2548 );
2549 render_impl(w, cx, &implementor, assoc_link,
b7449926 2550 RenderMode::Normal, implementor.impl_item.stable_since(), false,
e1599b0c 2551 None, true, false);
ea8adc8c 2552 }
e1599b0c 2553 write_loading_content(w, "");
ea8adc8c
XL
2554 }
2555
0731742a 2556 write_small_section_header(w, "implementors", "Implementors",
e1599b0c 2557 "<div class='item-list' id='implementors-list'>");
0531ce1d 2558 for implementor in concrete {
e1599b0c 2559 render_implementor(cx, implementor, w, &implementor_dups);
0531ce1d 2560 }
e1599b0c 2561 write_loading_content(w, "</div>");
ea8adc8c 2562
0531ce1d 2563 if t.auto {
0731742a 2564 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
e1599b0c 2565 "<div class='item-list' id='synthetic-implementors-list'>");
0531ce1d
XL
2566 for implementor in synthetic {
2567 synthetic_types.extend(
2568 collect_paths_for_type(implementor.inner_impl().for_.clone())
2569 );
e1599b0c 2570 render_implementor(cx, implementor, w, &implementor_dups);
3b2f2976 2571 }
e1599b0c 2572 write_loading_content(w, "</div>");
1a4d82fc 2573 }
ea8adc8c
XL
2574 } else {
2575 // even without any implementations to write in, we still want the heading and list, so the
2576 // implementors javascript file pulled in below has somewhere to write the impls into
0731742a 2577 write_small_section_header(w, "implementors", "Implementors",
e1599b0c
XL
2578 "<div class='item-list' id='implementors-list'>");
2579 write_loading_content(w, "</div>");
0531ce1d
XL
2580
2581 if t.auto {
0731742a 2582 write_small_section_header(w, "synthetic-implementors", "Auto implementors",
e1599b0c
XL
2583 "<div class='item-list' id='synthetic-implementors-list'>");
2584 write_loading_content(w, "</div>");
0531ce1d 2585 }
1a4d82fc 2586 }
60c5eb7d
XL
2587 write!(
2588 w,
2589 r#"<script type="text/javascript">window.inlined_types=new Set({});</script>"#,
2590 serde_json::to_string(&synthetic_types).unwrap(),
2591 );
0531ce1d 2592
54a0048b
SL
2593 write!(w, r#"<script type="text/javascript" async
2594 src="{root_path}/implementors/{path}/{ty}.{name}.js">
2595 </script>"#,
2596 root_path = vec![".."; cx.current.len()].join("/"),
2597 path = if it.def_id.is_local() {
2598 cx.current.join("/")
2599 } else {
e74abb32 2600 let (ref path, _) = cx.cache.external_paths[&it.def_id];
54a0048b
SL
2601 path[..path.len() - 1].join("/")
2602 },
e74abb32 2603 ty = it.type_(),
e1599b0c 2604 name = *it.name.as_ref().unwrap());
1a4d82fc
JJ
2605}
2606
9fa01778
XL
2607fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String {
2608 use crate::html::item_type::ItemType::*;
54a0048b
SL
2609
2610 let name = it.name.as_ref().unwrap();
c30ab7b3 2611 let ty = match it.type_() {
dc9dc135 2612 Typedef | AssocType => AssocType,
54a0048b
SL
2613 s@_ => s,
2614 };
2615
2616 let anchor = format!("#{}.{}", ty, name);
2617 match link {
a7813a04
XL
2618 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2619 AssocItemLink::Anchor(None) => anchor,
54a0048b
SL
2620 AssocItemLink::GotoSource(did, _) => {
2621 href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2622 }
2623 }
2624}
2625
e1599b0c 2626fn assoc_const(w: &mut Buffer,
54a0048b
SL
2627 it: &clean::Item,
2628 ty: &clean::Type,
8bb4bdeb 2629 _default: Option<&String>,
48663c56 2630 link: AssocItemLink<'_>,
e1599b0c 2631 extra: &str) {
48663c56
XL
2632 write!(w, "{}{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2633 extra,
e74abb32 2634 it.visibility.print_with_space(),
54a0048b 2635 naive_assoc_href(it, link),
8bb4bdeb 2636 it.name.as_ref().unwrap(),
e74abb32 2637 ty.print());
d9579d0f
AL
2638}
2639
e1599b0c
XL
2640fn assoc_type(w: &mut Buffer, it: &clean::Item,
2641 bounds: &[clean::GenericBound],
2642 default: Option<&clean::Type>,
2643 link: AssocItemLink<'_>,
2644 extra: &str) {
48663c56
XL
2645 write!(w, "{}type <a href='{}' class=\"type\">{}</a>",
2646 extra,
54a0048b 2647 naive_assoc_href(it, link),
e1599b0c 2648 it.name.as_ref().unwrap());
9346a6ac 2649 if !bounds.is_empty() {
e74abb32 2650 write!(w, ": {}", print_generic_bounds(bounds))
1a4d82fc 2651 }
54a0048b 2652 if let Some(default) = default {
e74abb32 2653 write!(w, " = {}", default.print())
1a4d82fc 2654 }
1a4d82fc
JJ
2655}
2656
e1599b0c 2657fn render_stability_since_raw(w: &mut Buffer, ver: Option<&str>, containing_ver: Option<&str>) {
54a0048b
SL
2658 if let Some(v) = ver {
2659 if containing_ver != ver && v.len() > 0 {
e1599b0c 2660 write!(w, "<span class='since' title='Stable since Rust version {0}'>{0}</span>", v)
7453a54e
SL
2661 }
2662 }
7453a54e
SL
2663}
2664
e1599b0c 2665fn render_stability_since(w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item) {
7453a54e
SL
2666 render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2667}
2668
e1599b0c 2669fn render_assoc_item(w: &mut Buffer,
54a0048b 2670 item: &clean::Item,
9fa01778 2671 link: AssocItemLink<'_>,
e1599b0c
XL
2672 parent: ItemType) {
2673 fn method(w: &mut Buffer,
54a0048b 2674 meth: &clean::Item,
8faf50e0 2675 header: hir::FnHeader,
62682a34 2676 g: &clean::Generics,
62682a34 2677 d: &clean::FnDecl,
9fa01778 2678 link: AssocItemLink<'_>,
e1599b0c 2679 parent: ItemType) {
54a0048b 2680 let name = meth.name.as_ref().unwrap();
c30ab7b3 2681 let anchor = format!("#{}.{}", meth.type_(), name);
9346a6ac 2682 let href = match link {
a7813a04
XL
2683 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2684 AssocItemLink::Anchor(None) => anchor,
54a0048b
SL
2685 AssocItemLink::GotoSource(did, provided_methods) => {
2686 // We're creating a link from an impl-item to the corresponding
2687 // trait-item and need to map the anchored type accordingly.
2688 let ty = if provided_methods.contains(name) {
2689 ItemType::Method
2690 } else {
2691 ItemType::TyMethod
2692 };
2693
2694 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
9346a6ac
AL
2695 }
2696 };
9fa01778 2697 let mut header_len = format!(
532ac7d7 2698 "{}{}{}{}{}{:#}fn {}{:#}",
e74abb32
XL
2699 meth.visibility.print_with_space(),
2700 header.constness.print_with_space(),
2701 header.unsafety.print_with_space(),
2702 header.asyncness.print_with_space(),
2703 print_default_space(meth.is_default()),
2704 print_abi_with_space(header.abi),
9fa01778 2705 name,
e74abb32 2706 g.print()
9fa01778 2707 ).len();
cc61c64b 2708 let (indent, end_newline) = if parent == ItemType::Trait {
9fa01778 2709 header_len += 4;
cc61c64b 2710 (4, false)
476ff2be 2711 } else {
cc61c64b 2712 (0, true)
476ff2be 2713 };
e1599b0c 2714 render_attributes(w, meth, false);
48663c56 2715 write!(w, "{}{}{}{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
1a4d82fc 2716 {generics}{decl}{where_clause}",
48663c56 2717 if parent == ItemType::Trait { " " } else { "" },
e74abb32
XL
2718 meth.visibility.print_with_space(),
2719 header.constness.print_with_space(),
2720 header.unsafety.print_with_space(),
2721 header.asyncness.print_with_space(),
2722 print_default_space(meth.is_default()),
2723 print_abi_with_space(header.abi),
9346a6ac
AL
2724 href = href,
2725 name = name,
e74abb32 2726 generics = g.print(),
9fa01778 2727 decl = Function {
cc61c64b 2728 decl: d,
9fa01778 2729 header_len,
3b2f2976 2730 indent,
9fa01778 2731 asyncness: header.asyncness,
e74abb32 2732 }.print(),
cc61c64b
XL
2733 where_clause = WhereClause {
2734 gens: g,
3b2f2976
XL
2735 indent,
2736 end_newline,
cc61c64b 2737 })
1a4d82fc 2738 }
54a0048b 2739 match item.inner {
e1599b0c 2740 clean::StrippedItem(..) => {},
1a4d82fc 2741 clean::TyMethodItem(ref m) => {
8faf50e0 2742 method(w, item, m.header, &m.generics, &m.decl, link, parent)
1a4d82fc
JJ
2743 }
2744 clean::MethodItem(ref m) => {
8faf50e0 2745 method(w, item, m.header, &m.generics, &m.decl, link, parent)
1a4d82fc 2746 }
dc9dc135 2747 clean::AssocConstItem(ref ty, ref default) => {
48663c56
XL
2748 assoc_const(w, item, ty, default.as_ref(), link,
2749 if parent == ItemType::Trait { " " } else { "" })
d9579d0f 2750 }
dc9dc135 2751 clean::AssocTypeItem(ref bounds, ref default) => {
48663c56
XL
2752 assoc_type(w, item, bounds, default.as_ref(), link,
2753 if parent == ItemType::Trait { " " } else { "" })
1a4d82fc 2754 }
d9579d0f 2755 _ => panic!("render_assoc_item called on non-associated-item")
1a4d82fc
JJ
2756 }
2757}
2758
e1599b0c 2759fn item_struct(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Struct) {
0531ce1d 2760 wrap_into_docblock(w, |w| {
e1599b0c
XL
2761 write!(w, "<pre class='rust struct'>");
2762 render_attributes(w, it, true);
0531ce1d
XL
2763 render_struct(w,
2764 it,
2765 Some(&s.generics),
2766 s.struct_type,
2767 &s.fields,
2768 "",
e1599b0c 2769 true);
0531ce1d 2770 write!(w, "</pre>")
e1599b0c 2771 });
54a0048b 2772
e1599b0c 2773 document(w, cx, it);
3157f602 2774 let mut fields = s.fields.iter().filter_map(|f| {
1a4d82fc 2775 match f.inner {
3157f602
XL
2776 clean::StructFieldItem(ref ty) => Some((f, ty)),
2777 _ => None,
1a4d82fc
JJ
2778 }
2779 }).peekable();
2780 if let doctree::Plain = s.struct_type {
2781 if fields.peek().is_some() {
3b2f2976 2782 write!(w, "<h2 id='fields' class='fields small-section-header'>
8faf50e0 2783 Fields{}<a href='#fields' class='anchor'></a></h2>",
e1599b0c
XL
2784 document_non_exhaustive_header(it));
2785 document_non_exhaustive(w, it);
3157f602 2786 for (field, ty) in fields {
b7449926 2787 let id = cx.derive_id(format!("{}.{}",
9e0c209e
SL
2788 ItemType::StructField,
2789 field.name.as_ref().unwrap()));
b7449926 2790 let ns_id = cx.derive_id(format!("{}.{}",
9e0c209e
SL
2791 field.name.as_ref().unwrap(),
2792 ItemType::StructField.name_space()));
0731742a
XL
2793 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
2794 <a href=\"#{id}\" class=\"anchor field\"></a>\
2795 <code id=\"{ns_id}\">{name}: {ty}</code>\
2796 </span>",
9e0c209e
SL
2797 item_type = ItemType::StructField,
2798 id = id,
2799 ns_id = ns_id,
3157f602 2800 name = field.name.as_ref().unwrap(),
e74abb32 2801 ty = ty.print());
e1599b0c 2802 document(w, cx, field);
1a4d82fc 2803 }
1a4d82fc
JJ
2804 }
2805 }
7453a54e 2806 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1a4d82fc
JJ
2807}
2808
e1599b0c 2809fn item_union(w: &mut Buffer, cx: &Context, it: &clean::Item, s: &clean::Union) {
0531ce1d 2810 wrap_into_docblock(w, |w| {
e1599b0c
XL
2811 write!(w, "<pre class='rust union'>");
2812 render_attributes(w, it, true);
0531ce1d
XL
2813 render_union(w,
2814 it,
2815 Some(&s.generics),
2816 &s.fields,
2817 "",
e1599b0c 2818 true);
0531ce1d 2819 write!(w, "</pre>")
e1599b0c 2820 });
9e0c209e 2821
e1599b0c 2822 document(w, cx, it);
9e0c209e
SL
2823 let mut fields = s.fields.iter().filter_map(|f| {
2824 match f.inner {
2825 clean::StructFieldItem(ref ty) => Some((f, ty)),
2826 _ => None,
2827 }
2828 }).peekable();
2829 if fields.peek().is_some() {
3b2f2976 2830 write!(w, "<h2 id='fields' class='fields small-section-header'>
e1599b0c 2831 Fields<a href='#fields' class='anchor'></a></h2>");
9e0c209e 2832 for (field, ty) in fields {
83c7162d
XL
2833 let name = field.name.as_ref().expect("union field name");
2834 let id = format!("{}.{}", ItemType::StructField, name);
2835 write!(w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
2836 <a href=\"#{id}\" class=\"anchor field\"></a>\
0731742a 2837 <code>{name}: {ty}</code>\
8bb4bdeb 2838 </span>",
83c7162d
XL
2839 id = id,
2840 name = name,
9e0c209e 2841 shortty = ItemType::StructField,
e74abb32 2842 ty = ty.print());
8bb4bdeb
XL
2843 if let Some(stability_class) = field.stability_class() {
2844 write!(w, "<span class='stab {stab}'></span>",
e1599b0c 2845 stab = stability_class);
8bb4bdeb 2846 }
e1599b0c 2847 document(w, cx, field);
9e0c209e
SL
2848 }
2849 }
2850 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2851}
2852
e1599b0c 2853fn item_enum(w: &mut Buffer, cx: &Context, it: &clean::Item, e: &clean::Enum) {
0531ce1d 2854 wrap_into_docblock(w, |w| {
e1599b0c
XL
2855 write!(w, "<pre class='rust enum'>");
2856 render_attributes(w, it, true);
0531ce1d 2857 write!(w, "{}enum {}{}{}",
e74abb32 2858 it.visibility.print_with_space(),
0531ce1d 2859 it.name.as_ref().unwrap(),
e74abb32 2860 e.generics.print(),
e1599b0c 2861 WhereClause { gens: &e.generics, indent: 0, end_newline: true });
0531ce1d 2862 if e.variants.is_empty() && !e.variants_stripped {
e1599b0c 2863 write!(w, " {{}}");
0531ce1d 2864 } else {
e1599b0c 2865 write!(w, " {{\n");
0531ce1d 2866 for v in &e.variants {
e1599b0c 2867 write!(w, " ");
0531ce1d
XL
2868 let name = v.name.as_ref().unwrap();
2869 match v.inner {
2870 clean::VariantItem(ref var) => {
2871 match var.kind {
e1599b0c 2872 clean::VariantKind::CLike => write!(w, "{}", name),
0531ce1d 2873 clean::VariantKind::Tuple(ref tys) => {
e1599b0c 2874 write!(w, "{}(", name);
0531ce1d
XL
2875 for (i, ty) in tys.iter().enumerate() {
2876 if i > 0 {
e1599b0c 2877 write!(w, ",&nbsp;")
0531ce1d 2878 }
e74abb32 2879 write!(w, "{}", ty.print());
1a4d82fc 2880 }
e1599b0c 2881 write!(w, ")");
0531ce1d
XL
2882 }
2883 clean::VariantKind::Struct(ref s) => {
2884 render_struct(w,
2885 v,
2886 None,
2887 s.struct_type,
2888 &s.fields,
2889 " ",
e1599b0c 2890 false);
1a4d82fc 2891 }
1a4d82fc
JJ
2892 }
2893 }
0531ce1d 2894 _ => unreachable!()
1a4d82fc 2895 }
e1599b0c 2896 write!(w, ",\n");
1a4d82fc 2897 }
1a4d82fc 2898
0531ce1d 2899 if e.variants_stripped {
e1599b0c 2900 write!(w, " // some variants omitted\n");
0531ce1d 2901 }
e1599b0c 2902 write!(w, "}}");
1a4d82fc 2903 }
0531ce1d 2904 write!(w, "</pre>")
e1599b0c 2905 });
1a4d82fc 2906
e1599b0c 2907 document(w, cx, it);
9346a6ac 2908 if !e.variants.is_empty() {
3b2f2976 2909 write!(w, "<h2 id='variants' class='variants small-section-header'>
8faf50e0 2910 Variants{}<a href='#variants' class='anchor'></a></h2>\n",
e1599b0c
XL
2911 document_non_exhaustive_header(it));
2912 document_non_exhaustive(w, it);
85aaf69f 2913 for variant in &e.variants {
b7449926 2914 let id = cx.derive_id(format!("{}.{}",
9e0c209e
SL
2915 ItemType::Variant,
2916 variant.name.as_ref().unwrap()));
b7449926 2917 let ns_id = cx.derive_id(format!("{}.{}",
9e0c209e
SL
2918 variant.name.as_ref().unwrap(),
2919 ItemType::Variant.name_space()));
e1599b0c 2920 write!(w, "<div id=\"{id}\" class=\"variant small-section-header\">\
ea8adc8c 2921 <a href=\"#{id}\" class=\"anchor field\"></a>\
0731742a 2922 <code id='{ns_id}'>{name}",
9e0c209e
SL
2923 id = id,
2924 ns_id = ns_id,
e1599b0c 2925 name = variant.name.as_ref().unwrap());
3157f602 2926 if let clean::VariantItem(ref var) = variant.inner {
c30ab7b3 2927 if let clean::VariantKind::Tuple(ref tys) = var.kind {
e1599b0c 2928 write!(w, "(");
3157f602
XL
2929 for (i, ty) in tys.iter().enumerate() {
2930 if i > 0 {
e1599b0c 2931 write!(w, ",&nbsp;");
3157f602 2932 }
e74abb32 2933 write!(w, "{}", ty.print());
3157f602 2934 }
e1599b0c 2935 write!(w, ")");
3157f602
XL
2936 }
2937 }
e1599b0c
XL
2938 write!(w, "</code></div>");
2939 document(w, cx, variant);
2940 document_non_exhaustive(w, variant);
54a0048b 2941
9fa01778 2942 use crate::clean::{Variant, VariantKind};
c30ab7b3
SL
2943 if let clean::VariantItem(Variant {
2944 kind: VariantKind::Struct(ref s)
2945 }) = variant.inner {
b7449926 2946 let variant_id = cx.derive_id(format!("{}.{}.fields",
476ff2be
SL
2947 ItemType::Variant,
2948 variant.name.as_ref().unwrap()));
e1599b0c
XL
2949 write!(w, "<div class='autohide sub-variant' id='{id}'>",
2950 id = variant_id);
a1dfa0c6 2951 write!(w, "<h3>Fields of <b>{name}</b></h3><div>",
e1599b0c 2952 name = variant.name.as_ref().unwrap());
3157f602 2953 for field in &s.fields {
9fa01778 2954 use crate::clean::StructFieldItem;
3157f602 2955 if let StructFieldItem(ref ty) = field.inner {
b7449926 2956 let id = cx.derive_id(format!("variant.{}.field.{}",
9e0c209e
SL
2957 variant.name.as_ref().unwrap(),
2958 field.name.as_ref().unwrap()));
b7449926 2959 let ns_id = cx.derive_id(format!("{}.{}.{}.{}",
9e0c209e
SL
2960 variant.name.as_ref().unwrap(),
2961 ItemType::Variant.name_space(),
2962 field.name.as_ref().unwrap(),
2963 ItemType::StructField.name_space()));
a1dfa0c6
XL
2964 write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2965 <a href=\"#{id}\" class=\"anchor field\"></a>\
0731742a
XL
2966 <code id='{ns_id}'>{f}:&nbsp;{t}\
2967 </code></span>",
9e0c209e
SL
2968 id = id,
2969 ns_id = ns_id,
3157f602 2970 f = field.name.as_ref().unwrap(),
e74abb32 2971 t = ty.print());
e1599b0c 2972 document(w, cx, field);
3157f602 2973 }
1a4d82fc 2974 }
e1599b0c 2975 write!(w, "</div></div>");
1a4d82fc 2976 }
e1599b0c 2977 render_stability_since(w, variant, it);
1a4d82fc 2978 }
1a4d82fc 2979 }
e1599b0c 2980 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1a4d82fc
JJ
2981}
2982
476ff2be 2983fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
e74abb32 2984 let path = pprust::path_to_string(&attr.path);
476ff2be
SL
2985
2986 if attr.is_word() {
9fa01778 2987 Some(path)
476ff2be 2988 } else if let Some(v) = attr.value_str() {
60c5eb7d 2989 Some(format!("{} = {:?}", path, v))
476ff2be
SL
2990 } else if let Some(values) = attr.meta_item_list() {
2991 let display: Vec<_> = values.iter().filter_map(|attr| {
2992 attr.meta_item().and_then(|mi| render_attribute(mi))
2993 }).collect();
2994
2995 if display.len() > 0 {
9fa01778 2996 Some(format!("{}({})", path, display.join(", ")))
476ff2be
SL
2997 } else {
2998 None
2999 }
3000 } else {
3001 None
3002 }
3003}
3004
48663c56
XL
3005const ATTRIBUTE_WHITELIST: &'static [Symbol] = &[
3006 sym::export_name,
3007 sym::lang,
3008 sym::link_section,
3009 sym::must_use,
3010 sym::no_mangle,
3011 sym::repr,
48663c56 3012 sym::non_exhaustive
476ff2be
SL
3013];
3014
48663c56
XL
3015// The `top` parameter is used when generating the item declaration to ensure it doesn't have a
3016// left padding. For example:
3017//
3018// #[foo] <----- "top" attribute
3019// struct Foo {
3020// #[bar] <---- not "top" attribute
3021// bar: usize,
3022// }
e1599b0c 3023fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
476ff2be
SL
3024 let mut attrs = String::new();
3025
3026 for attr in &it.attrs.other_attrs {
48663c56 3027 if !ATTRIBUTE_WHITELIST.contains(&attr.name_or_empty()) {
476ff2be 3028 continue;
85aaf69f 3029 }
cc61c64b 3030 if let Some(s) = render_attribute(&attr.meta().unwrap()) {
476ff2be
SL
3031 attrs.push_str(&format!("#[{}]\n", s));
3032 }
3033 }
3034 if attrs.len() > 0 {
dc9dc135 3035 write!(w, "<span class=\"docblock attributes{}\">{}</span>",
e1599b0c 3036 if top { " top-attr" } else { "" }, &attrs);
85aaf69f 3037 }
85aaf69f
SL
3038}
3039
e1599b0c 3040fn render_struct(w: &mut Buffer, it: &clean::Item,
1a4d82fc
JJ
3041 g: Option<&clean::Generics>,
3042 ty: doctree::StructType,
3043 fields: &[clean::Item],
3044 tab: &str,
e1599b0c 3045 structhead: bool) {
54a0048b 3046 write!(w, "{}{}{}",
e74abb32 3047 it.visibility.print_with_space(),
54a0048b 3048 if structhead {"struct "} else {""},
e1599b0c 3049 it.name.as_ref().unwrap());
54a0048b 3050 if let Some(g) = g {
e74abb32 3051 write!(w, "{}", g.print())
1a4d82fc
JJ
3052 }
3053 match ty {
3054 doctree::Plain => {
5bcae85e 3055 if let Some(g) = g {
e1599b0c 3056 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })
5bcae85e 3057 }
9e0c209e 3058 let mut has_visible_fields = false;
e1599b0c 3059 write!(w, " {{");
85aaf69f 3060 for field in fields {
54a0048b 3061 if let clean::StructFieldItem(ref ty) = field.inner {
9e0c209e
SL
3062 write!(w, "\n{} {}{}: {},",
3063 tab,
e74abb32 3064 field.visibility.print_with_space(),
54a0048b 3065 field.name.as_ref().unwrap(),
e74abb32 3066 ty.print());
9e0c209e 3067 has_visible_fields = true;
54a0048b 3068 }
1a4d82fc
JJ
3069 }
3070
9e0c209e
SL
3071 if has_visible_fields {
3072 if it.has_stripped_fields().unwrap() {
e1599b0c 3073 write!(w, "\n{} // some fields omitted", tab);
9e0c209e 3074 }
e1599b0c 3075 write!(w, "\n{}", tab);
9e0c209e
SL
3076 } else if it.has_stripped_fields().unwrap() {
3077 // If there are no visible fields we can just display
3078 // `{ /* fields omitted */ }` to save space.
e1599b0c 3079 write!(w, " /* fields omitted */ ");
1a4d82fc 3080 }
e1599b0c 3081 write!(w, "}}");
1a4d82fc 3082 }
9e0c209e 3083 doctree::Tuple => {
e1599b0c 3084 write!(w, "(");
1a4d82fc
JJ
3085 for (i, field) in fields.iter().enumerate() {
3086 if i > 0 {
e1599b0c 3087 write!(w, ", ");
1a4d82fc
JJ
3088 }
3089 match field.inner {
54a0048b 3090 clean::StrippedItem(box clean::StructFieldItem(..)) => {
e1599b0c 3091 write!(w, "_")
1a4d82fc 3092 }
54a0048b 3093 clean::StructFieldItem(ref ty) => {
e74abb32 3094 write!(w, "{}{}", field.visibility.print_with_space(), ty.print())
1a4d82fc
JJ
3095 }
3096 _ => unreachable!()
3097 }
3098 }
e1599b0c 3099 write!(w, ")");
5bcae85e 3100 if let Some(g) = g {
e1599b0c 3101 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
5bcae85e 3102 }
e1599b0c 3103 write!(w, ";");
1a4d82fc
JJ
3104 }
3105 doctree::Unit => {
5bcae85e
SL
3106 // Needed for PhantomData.
3107 if let Some(g) = g {
e1599b0c 3108 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })
5bcae85e 3109 }
e1599b0c 3110 write!(w, ";");
1a4d82fc
JJ
3111 }
3112 }
1a4d82fc
JJ
3113}
3114
e1599b0c 3115fn render_union(w: &mut Buffer, it: &clean::Item,
9e0c209e
SL
3116 g: Option<&clean::Generics>,
3117 fields: &[clean::Item],
3118 tab: &str,
e1599b0c 3119 structhead: bool) {
9e0c209e 3120 write!(w, "{}{}{}",
e74abb32 3121 it.visibility.print_with_space(),
9e0c209e 3122 if structhead {"union "} else {""},
e1599b0c 3123 it.name.as_ref().unwrap());
9e0c209e 3124 if let Some(g) = g {
e74abb32 3125 write!(w, "{}", g.print());
e1599b0c 3126 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true });
9e0c209e
SL
3127 }
3128
e1599b0c 3129 write!(w, " {{\n{}", tab);
9e0c209e
SL
3130 for field in fields {
3131 if let clean::StructFieldItem(ref ty) = field.inner {
3132 write!(w, " {}{}: {},\n{}",
e74abb32 3133 field.visibility.print_with_space(),
9e0c209e 3134 field.name.as_ref().unwrap(),
e74abb32 3135 ty.print(),
e1599b0c 3136 tab);
9e0c209e
SL
3137 }
3138 }
3139
3140 if it.has_stripped_fields().unwrap() {
e1599b0c 3141 write!(w, " // some fields omitted\n{}", tab);
9e0c209e 3142 }
e1599b0c 3143 write!(w, "}}");
9e0c209e
SL
3144}
3145
9346a6ac 3146#[derive(Copy, Clone)]
54a0048b 3147enum AssocItemLink<'a> {
a7813a04 3148 Anchor(Option<&'a str>),
476ff2be 3149 GotoSource(DefId, &'a FxHashSet<String>),
9346a6ac
AL
3150}
3151
a7813a04
XL
3152impl<'a> AssocItemLink<'a> {
3153 fn anchor(&self, id: &'a String) -> Self {
3154 match *self {
3155 AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3156 ref other => *other,
3157 }
3158 }
3159}
3160
d9579d0f
AL
3161enum AssocItemRender<'a> {
3162 All,
9e0c209e
SL
3163 DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3164}
3165
3166#[derive(Copy, Clone, PartialEq)]
3167enum RenderMode {
3168 Normal,
3169 ForDeref { mut_: bool },
d9579d0f
AL
3170}
3171
e1599b0c 3172fn render_assoc_items(w: &mut Buffer,
e9174d1e 3173 cx: &Context,
7453a54e 3174 containing_item: &clean::Item,
e9174d1e 3175 it: DefId,
e1599b0c 3176 what: AssocItemRender<'_>) {
e74abb32 3177 let c = &cx.cache;
d9579d0f
AL
3178 let v = match c.impls.get(&it) {
3179 Some(v) => v,
e1599b0c 3180 None => return,
9346a6ac 3181 };
d9579d0f 3182 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
a7813a04 3183 i.inner_impl().trait_.is_none()
d9579d0f 3184 });
9346a6ac 3185 if !non_trait.is_empty() {
9e0c209e 3186 let render_mode = match what {
d9579d0f 3187 AssocItemRender::All => {
8faf50e0
XL
3188 write!(w, "\
3189 <h2 id='methods' class='small-section-header'>\
3190 Methods<a href='#methods' class='anchor'></a>\
3191 </h2>\
e1599b0c 3192 ");
9e0c209e 3193 RenderMode::Normal
d9579d0f 3194 }
9e0c209e 3195 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
8faf50e0
XL
3196 write!(w, "\
3197 <h2 id='deref-methods' class='small-section-header'>\
3198 Methods from {}&lt;Target = {}&gt;\
3199 <a href='#deref-methods' class='anchor'></a>\
3200 </h2>\
e74abb32 3201 ", trait_.print(), type_.print());
9e0c209e 3202 RenderMode::ForDeref { mut_: deref_mut_ }
d9579d0f
AL
3203 }
3204 };
9346a6ac 3205 for i in &non_trait {
9e0c209e 3206 render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
e1599b0c 3207 containing_item.stable_since(), true, None, false, true);
9346a6ac
AL
3208 }
3209 }
d9579d0f 3210 if let AssocItemRender::DerefFor { .. } = what {
e1599b0c 3211 return;
d9579d0f 3212 }
9346a6ac 3213 if !traits.is_empty() {
d9579d0f 3214 let deref_impl = traits.iter().find(|t| {
a7813a04 3215 t.inner_impl().trait_.def_id() == c.deref_trait_did
d9579d0f
AL
3216 });
3217 if let Some(impl_) = deref_impl {
9e0c209e
SL
3218 let has_deref_mut = traits.iter().find(|t| {
3219 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3220 }).is_some();
e1599b0c 3221 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
d9579d0f 3222 }
0531ce1d 3223
8faf50e0 3224 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits
0531ce1d 3225 .iter()
8faf50e0 3226 .partition(|t| t.inner_impl().synthetic);
e1599b0c 3227 let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete
8faf50e0
XL
3228 .into_iter()
3229 .partition(|t| t.inner_impl().blanket_impl.is_some());
0531ce1d 3230
e1599b0c
XL
3231 let mut impls = Buffer::empty_from(&w);
3232 render_impls(cx, &mut impls, &concrete, containing_item);
3233 let impls = impls.into_inner();
83c7162d 3234 if !impls.is_empty() {
8faf50e0
XL
3235 write!(w, "\
3236 <h2 id='implementations' class='small-section-header'>\
3237 Trait Implementations<a href='#implementations' class='anchor'></a>\
3238 </h2>\
e1599b0c 3239 <div id='implementations-list'>{}</div>", impls);
83c7162d 3240 }
0531ce1d
XL
3241
3242 if !synthetic.is_empty() {
8faf50e0
XL
3243 write!(w, "\
3244 <h2 id='synthetic-implementations' class='small-section-header'>\
3245 Auto Trait Implementations\
3246 <a href='#synthetic-implementations' class='anchor'></a>\
3247 </h2>\
3248 <div id='synthetic-implementations-list'>\
e1599b0c
XL
3249 ");
3250 render_impls(cx, w, &synthetic, containing_item);
3251 write!(w, "</div>");
9346a6ac 3252 }
8faf50e0
XL
3253
3254 if !blanket_impl.is_empty() {
3255 write!(w, "\
3256 <h2 id='blanket-implementations' class='small-section-header'>\
3257 Blanket Implementations\
3258 <a href='#blanket-implementations' class='anchor'></a>\
3259 </h2>\
3260 <div id='blanket-implementations-list'>\
e1599b0c
XL
3261 ");
3262 render_impls(cx, w, &blanket_impl, containing_item);
3263 write!(w, "</div>");
8faf50e0 3264 }
1a4d82fc 3265 }
1a4d82fc
JJ
3266}
3267
e1599b0c
XL
3268fn render_deref_methods(w: &mut Buffer, cx: &Context, impl_: &Impl,
3269 container_item: &clean::Item, deref_mut: bool) {
a7813a04
XL
3270 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3271 let target = impl_.inner_impl().items.iter().filter_map(|item| {
d9579d0f 3272 match item.inner {
62682a34 3273 clean::TypedefItem(ref t, true) => Some(&t.type_),
d9579d0f
AL
3274 _ => None,
3275 }
62682a34 3276 }).next().expect("Expected associated type binding");
9e0c209e
SL
3277 let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3278 deref_mut_: deref_mut };
54a0048b
SL
3279 if let Some(did) = target.def_id() {
3280 render_assoc_items(w, cx, container_item, did, what)
3281 } else {
3282 if let Some(prim) = target.primitive_type() {
e74abb32 3283 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
e1599b0c 3284 render_assoc_items(w, cx, container_item, did, what);
d9579d0f 3285 }
d9579d0f 3286 }
1a4d82fc 3287 }
d9579d0f
AL
3288}
3289
abe05a73
XL
3290fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3291 let self_type_opt = match item.inner {
3292 clean::MethodItem(ref method) => method.decl.self_type(),
3293 clean::TyMethodItem(ref method) => method.decl.self_type(),
3294 _ => None
3295 };
3296
3297 if let Some(self_ty) = self_type_opt {
3298 let (by_mut_ref, by_box, by_value) = match self_ty {
3299 SelfTy::SelfBorrowed(_, mutability) |
3300 SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3301 (mutability == Mutability::Mutable, false, false)
3302 },
3303 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3304 (false, Some(did) == cache().owned_box_did, false)
3305 },
3306 SelfTy::SelfValue => (false, false, true),
3307 _ => (false, false, false),
3308 };
3309
3310 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3311 } else {
3312 false
3313 }
3314}
3315
e1599b0c 3316fn render_spotlight_traits(item: &clean::Item) -> String {
ff7c6d11
XL
3317 match item.inner {
3318 clean::FunctionItem(clean::Function { ref decl, .. }) |
3319 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3320 clean::MethodItem(clean::Method { ref decl, .. }) |
3321 clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
e74abb32 3322 spotlight_decl(decl)
ff7c6d11 3323 }
e74abb32 3324 _ => String::new()
ff7c6d11 3325 }
ff7c6d11
XL
3326}
3327
e1599b0c
XL
3328fn spotlight_decl(decl: &clean::FnDecl) -> String {
3329 let mut out = Buffer::html();
ff7c6d11
XL
3330 let mut trait_ = String::new();
3331
3332 if let Some(did) = decl.output.def_id() {
3333 let c = cache();
3334 if let Some(impls) = c.impls.get(&did) {
3335 for i in impls {
3336 let impl_ = i.inner_impl();
2c00a5a8 3337 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
ff7c6d11
XL
3338 if out.is_empty() {
3339 out.push_str(
3340 &format!("<h3 class=\"important\">Important traits for {}</h3>\
3341 <code class=\"content\">",
e74abb32
XL
3342 impl_.for_.print()));
3343 trait_.push_str(&impl_.for_.print().to_string());
ff7c6d11
XL
3344 }
3345
3346 //use the "where" class here to make it small
e74abb32
XL
3347 out.push_str(
3348 &format!("<span class=\"where fmt-newline\">{}</span>", impl_.print()));
ff7c6d11
XL
3349 let t_did = impl_.trait_.def_id().unwrap();
3350 for it in &impl_.items {
3351 if let clean::TypedefItem(ref tydef, _) = it.inner {
3352 out.push_str("<span class=\"where fmt-newline\"> ");
8faf50e0 3353 assoc_type(&mut out, it, &[],
ff7c6d11 3354 Some(&tydef.type_),
48663c56 3355 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
e1599b0c 3356 "");
ff7c6d11
XL
3357 out.push_str(";</span>");
3358 }
3359 }
3360 }
3361 }
3362 }
3363 }
3364
3365 if !out.is_empty() {
3366 out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3367 <span class='tooltiptext'>Important traits for {}</span></div>\
3368 <div class=\"content hidden\">",
3369 trait_));
3370 out.push_str("</code></div></div>");
3371 }
3372
e1599b0c 3373 out.into_inner()
ff7c6d11
XL
3374}
3375
e1599b0c 3376fn render_impl(w: &mut Buffer, cx: &Context, i: &Impl, link: AssocItemLink<'_>,
48663c56 3377 render_mode: RenderMode, outer_version: Option<&str>, show_def_docs: bool,
dc9dc135 3378 use_absolute: Option<bool>, is_on_foreign_type: bool,
e1599b0c 3379 show_default_items: bool) {
9e0c209e 3380 if render_mode == RenderMode::Normal {
b7449926 3381 let id = cx.derive_id(match i.inner_impl().trait_ {
48663c56
XL
3382 Some(ref t) => if is_on_foreign_type {
3383 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t)
3384 } else {
e74abb32 3385 format!("impl-{}", small_url_encode(&format!("{:#}", t.print())))
48663c56 3386 },
3b2f2976
XL
3387 None => "impl".to_string(),
3388 });
b7449926 3389 if let Some(use_absolute) = use_absolute {
e1599b0c
XL
3390 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>", id);
3391 fmt_impl_for_trait_page(&i.inner_impl(), w, use_absolute);
b7449926
XL
3392 if show_def_docs {
3393 for it in &i.inner_impl().items {
3394 if let clean::TypedefItem(ref tydef, _) = it.inner {
e1599b0c 3395 write!(w, "<span class=\"where fmt-newline\"> ");
b7449926 3396 assoc_type(w, it, &vec![], Some(&tydef.type_),
48663c56 3397 AssocItemLink::Anchor(None),
e1599b0c
XL
3398 "");
3399 write!(w, ";</span>");
b7449926
XL
3400 }
3401 }
3402 }
e1599b0c 3403 write!(w, "</code>");
b7449926 3404 } else {
0731742a 3405 write!(w, "<h3 id='{}' class='impl'><code class='in-band'>{}</code>",
e74abb32 3406 id, i.inner_impl().print()
e1599b0c 3407 );
b7449926 3408 }
e1599b0c 3409 write!(w, "<a href='#{}' class='anchor'></a>", id);
a7813a04 3410 let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
e1599b0c
XL
3411 render_stability_since_raw(w, since, outer_version);
3412 if let Some(l) = cx.src_href(&i.impl_item) {
476ff2be 3413 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
e1599b0c 3414 l, "goto source code");
a7813a04 3415 }
e1599b0c 3416 write!(w, "</h3>");
ff7c6d11 3417 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
b7449926 3418 let mut ids = cx.id_map.borrow_mut();
2c00a5a8 3419 write!(w, "<div class='docblock'>{}</div>",
416331ca 3420 Markdown(&*dox, &i.impl_item.links(), &mut ids,
e74abb32 3421 cx.shared.codes, cx.shared.edition, &cx.shared.playground).to_string());
d9579d0f 3422 }
1a4d82fc
JJ
3423 }
3424
e1599b0c 3425 fn doc_impl_item(w: &mut Buffer, cx: &Context, item: &clean::Item,
9fa01778 3426 link: AssocItemLink<'_>, render_mode: RenderMode,
9e0c209e 3427 is_default_item: bool, outer_version: Option<&str>,
e1599b0c 3428 trait_: Option<&clean::Trait>, show_def_docs: bool) {
c30ab7b3 3429 let item_type = item.type_();
92a42be0 3430 let name = item.name.as_ref().unwrap();
54a0048b 3431
e74abb32 3432 let render_method_item = match render_mode {
9e0c209e 3433 RenderMode::Normal => true,
abe05a73 3434 RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
54a0048b
SL
3435 };
3436
e1599b0c
XL
3437 let (is_hidden, extra_class) = if (trait_.is_none() ||
3438 item.doc_value().is_some() ||
3439 item.inner.is_associated()) &&
3440 !is_default_item {
a1dfa0c6
XL
3441 (false, "")
3442 } else {
3443 (true, " hidden")
3444 };
1a4d82fc 3445 match item.inner {
ff7c6d11 3446 clean::MethodItem(clean::Method { ref decl, .. }) |
a1dfa0c6 3447 clean::TyMethodItem(clean::TyMethod { ref decl, .. }) => {
62682a34 3448 // Only render when the method is not static or we allow static methods
9e0c209e 3449 if render_method_item {
b7449926 3450 let id = cx.derive_id(format!("{}.{}", item_type, name));
e74abb32
XL
3451 let ns_id = cx.derive_id(format!("{}.{}",
3452 name, item_type.name_space()));
3453 write!(w, "<h4 id='{}' class=\"{}{}\">",
3454 id, item_type, extra_class);
e1599b0c
XL
3455 write!(w, "{}", spotlight_decl(decl));
3456 write!(w, "<code id='{}'>", ns_id);
3457 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl);
3458 write!(w, "</code>");
3459 render_stability_since_raw(w, item.stable_since(), outer_version);
3460 if let Some(l) = cx.src_href(item) {
3b2f2976 3461 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
e1599b0c 3462 l, "goto source code");
3b2f2976 3463 }
e1599b0c 3464 write!(w, "</h4>");
62682a34 3465 }
1a4d82fc 3466 }
62682a34 3467 clean::TypedefItem(ref tydef, _) => {
dc9dc135 3468 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
b7449926 3469 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
e1599b0c
XL
3470 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3471 write!(w, "<code id='{}'>", ns_id);
3472 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "");
3473 write!(w, "</code></h4>");
1a4d82fc 3474 }
dc9dc135 3475 clean::AssocConstItem(ref ty, ref default) => {
b7449926
XL
3476 let id = cx.derive_id(format!("{}.{}", item_type, name));
3477 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
e1599b0c
XL
3478 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3479 write!(w, "<code id='{}'>", ns_id);
3480 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "");
3481 write!(w, "</code>");
3482 render_stability_since_raw(w, item.stable_since(), outer_version);
3483 if let Some(l) = cx.src_href(item) {
0731742a 3484 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
e1599b0c 3485 l, "goto source code");
0731742a 3486 }
e1599b0c 3487 write!(w, "</h4>");
d9579d0f 3488 }
dc9dc135 3489 clean::AssocTypeItem(ref bounds, ref default) => {
b7449926
XL
3490 let id = cx.derive_id(format!("{}.{}", item_type, name));
3491 let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space()));
e1599b0c
XL
3492 write!(w, "<h4 id='{}' class=\"{}{}\">", id, item_type, extra_class);
3493 write!(w, "<code id='{}'>", ns_id);
3494 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "");
3495 write!(w, "</code></h4>");
1a4d82fc 3496 }
e1599b0c 3497 clean::StrippedItem(..) => return,
1a4d82fc
JJ
3498 _ => panic!("can't make docs for trait item with name {:?}", item.name)
3499 }
62682a34 3500
e74abb32 3501 if render_method_item {
a7813a04 3502 if !is_default_item {
3157f602
XL
3503 if let Some(t) = trait_ {
3504 // The trait item may have been stripped so we might not
3505 // find any documentation or stability for it.
3506 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3507 // We need the stability of the item from the trait
3508 // because impls can't have a stability.
e1599b0c 3509 document_stability(w, cx, it, is_hidden);
041b39d2 3510 if item.doc_value().is_some() {
e1599b0c 3511 document_full(w, item, cx, "", is_hidden);
ea8adc8c 3512 } else if show_def_docs {
3157f602
XL
3513 // In case the item isn't documented,
3514 // provide short documentation from the trait.
e1599b0c 3515 document_short(w, cx, it, link, "", is_hidden);
a7813a04
XL
3516 }
3517 }
3157f602 3518 } else {
e1599b0c 3519 document_stability(w, cx, item, is_hidden);
ea8adc8c 3520 if show_def_docs {
e1599b0c 3521 document_full(w, item, cx, "", is_hidden);
ea8adc8c 3522 }
a7813a04
XL
3523 }
3524 } else {
e1599b0c 3525 document_stability(w, cx, item, is_hidden);
ea8adc8c 3526 if show_def_docs {
e1599b0c 3527 document_short(w, cx, item, link, "", is_hidden);
ea8adc8c 3528 }
a7813a04 3529 }
1a4d82fc
JJ
3530 }
3531 }
3532
e74abb32 3533 let traits = &cx.cache.traits;
2c00a5a8 3534 let trait_ = i.trait_did().map(|did| &traits[&did]);
a7813a04 3535
e1599b0c 3536 write!(w, "<div class='impl-items'>");
a7813a04 3537 for trait_item in &i.inner_impl().items {
9e0c209e 3538 doc_impl_item(w, cx, trait_item, link, render_mode,
e1599b0c 3539 false, outer_version, trait_, show_def_docs);
1a4d82fc
JJ
3540 }
3541
e1599b0c 3542 fn render_default_items(w: &mut Buffer,
e9174d1e 3543 cx: &Context,
d9579d0f 3544 t: &clean::Trait,
54a0048b 3545 i: &clean::Impl,
9e0c209e 3546 render_mode: RenderMode,
ea8adc8c 3547 outer_version: Option<&str>,
e1599b0c 3548 show_def_docs: bool) {
85aaf69f 3549 for trait_item in &t.items {
c34b1796 3550 let n = trait_item.name.clone();
54a0048b
SL
3551 if i.items.iter().find(|m| m.name == n).is_some() {
3552 continue;
1a4d82fc 3553 }
54a0048b
SL
3554 let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3555 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1a4d82fc 3556
9e0c209e 3557 doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
e1599b0c 3558 outer_version, None, show_def_docs);
1a4d82fc 3559 }
1a4d82fc
JJ
3560 }
3561
3562 // If we've implemented a trait, then also emit documentation for all
54a0048b 3563 // default items which weren't overridden in the implementation block.
dc9dc135
XL
3564 // We don't emit documentation for default items if they appear in the
3565 // Implementations on Foreign Types or Implementors sections.
3566 if show_default_items {
3567 if let Some(t) = trait_ {
3568 render_default_items(w, cx, t, &i.inner_impl(),
e1599b0c 3569 render_mode, outer_version, show_def_docs);
dc9dc135 3570 }
1a4d82fc 3571 }
e1599b0c 3572 write!(w, "</div>");
1a4d82fc
JJ
3573}
3574
416331ca 3575fn item_opaque_ty(
e1599b0c 3576 w: &mut Buffer,
8faf50e0
XL
3577 cx: &Context,
3578 it: &clean::Item,
416331ca 3579 t: &clean::OpaqueTy,
e1599b0c
XL
3580) {
3581 write!(w, "<pre class='rust opaque'>");
3582 render_attributes(w, it, false);
416331ca 3583 write!(w, "type {}{}{where_clause} = impl {bounds};</pre>",
8faf50e0 3584 it.name.as_ref().unwrap(),
e74abb32 3585 t.generics.print(),
8faf50e0 3586 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
e1599b0c 3587 bounds = bounds(&t.bounds, false));
8faf50e0 3588
e1599b0c 3589 document(w, cx, it);
8faf50e0
XL
3590
3591 // Render any items associated directly to this alias, as otherwise they
3592 // won't be visible anywhere in the docs. It would be nice to also show
3593 // associated items from the aliased type (see discussion in #32077), but
3594 // we need #14072 to make sense of the generics.
3595 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3596}
3597
e1599b0c
XL
3598fn item_trait_alias(w: &mut Buffer, cx: &Context, it: &clean::Item,
3599 t: &clean::TraitAlias) {
3600 write!(w, "<pre class='rust trait-alias'>");
3601 render_attributes(w, it, false);
9fa01778
XL
3602 write!(w, "trait {}{}{} = {};</pre>",
3603 it.name.as_ref().unwrap(),
e74abb32 3604 t.generics.print(),
9fa01778 3605 WhereClause { gens: &t.generics, indent: 0, end_newline: true },
e1599b0c 3606 bounds(&t.bounds, true));
9fa01778 3607
e1599b0c 3608 document(w, cx, it);
9fa01778
XL
3609
3610 // Render any items associated directly to this alias, as otherwise they
3611 // won't be visible anywhere in the docs. It would be nice to also show
3612 // associated items from the aliased type (see discussion in #32077), but
3613 // we need #14072 to make sense of the generics.
3614 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3615}
3616
e1599b0c
XL
3617fn item_typedef(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Typedef) {
3618 write!(w, "<pre class='rust typedef'>");
3619 render_attributes(w, it, false);
8bb4bdeb 3620 write!(w, "type {}{}{where_clause} = {type_};</pre>",
54a0048b 3621 it.name.as_ref().unwrap(),
e74abb32 3622 t.generics.print(),
cc61c64b 3623 where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
e74abb32 3624 type_ = t.type_.print());
1a4d82fc 3625
e1599b0c 3626 document(w, cx, it);
041b39d2
XL
3627
3628 // Render any items associated directly to this alias, as otherwise they
3629 // won't be visible anywhere in the docs. It would be nice to also show
3630 // associated items from the aliased type (see discussion in #32077), but
3631 // we need #14072 to make sense of the generics.
3632 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1a4d82fc
JJ
3633}
3634
e1599b0c
XL
3635fn item_foreign_type(w: &mut Buffer, cx: &Context, it: &clean::Item) {
3636 writeln!(w, "<pre class='rust foreigntype'>extern {{");
3637 render_attributes(w, it, false);
abe05a73
XL
3638 write!(
3639 w,
3640 " {}type {};\n}}</pre>",
e74abb32 3641 it.visibility.print_with_space(),
abe05a73 3642 it.name.as_ref().unwrap(),
e1599b0c 3643 );
abe05a73 3644
e1599b0c 3645 document(w, cx, it);
abe05a73
XL
3646
3647 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3648}
3649
e1599b0c
XL
3650fn print_sidebar(cx: &Context, it: &clean::Item, buffer: &mut Buffer) {
3651 let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3652
3653 if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3654 || it.is_enum() || it.is_mod() || it.is_typedef() {
3655 write!(buffer, "<p class='location'>{}{}</p>",
3656 match it.inner {
3657 clean::StructItem(..) => "Struct ",
3658 clean::TraitItem(..) => "Trait ",
3659 clean::PrimitiveItem(..) => "Primitive Type ",
3660 clean::UnionItem(..) => "Union ",
3661 clean::EnumItem(..) => "Enum ",
3662 clean::TypedefItem(..) => "Type Definition ",
3663 clean::ForeignTypeItem => "Foreign Type ",
3664 clean::ModuleItem(..) => if it.is_crate() {
3665 "Crate "
3666 } else {
3667 "Module "
cc61c64b 3668 },
e1599b0c
XL
3669 _ => "",
3670 },
3671 it.name.as_ref().unwrap());
3672 }
3673
3674 if it.is_crate() {
e74abb32 3675 if let Some(ref version) = cx.cache.crate_version {
e1599b0c
XL
3676 write!(buffer,
3677 "<div class='block version'>\
3678 <p>Version {}</p>\
3679 </div>",
3680 version);
3681 }
3682 }
3683
3684 write!(buffer, "<div class=\"sidebar-elems\">");
3685 if it.is_crate() {
3686 write!(buffer, "<a id='all-types' href='all.html'><p>See all {}'s items</p></a>",
3687 it.name.as_ref().expect("crates always have a name"));
3688 }
3689 match it.inner {
3690 clean::StructItem(ref s) => sidebar_struct(buffer, it, s),
3691 clean::TraitItem(ref t) => sidebar_trait(buffer, it, t),
e74abb32 3692 clean::PrimitiveItem(_) => sidebar_primitive(buffer, it),
e1599b0c
XL
3693 clean::UnionItem(ref u) => sidebar_union(buffer, it, u),
3694 clean::EnumItem(ref e) => sidebar_enum(buffer, it, e),
e74abb32
XL
3695 clean::TypedefItem(_, _) => sidebar_typedef(buffer, it),
3696 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
e1599b0c
XL
3697 clean::ForeignTypeItem => sidebar_foreign_type(buffer, it),
3698 _ => (),
3699 }
3700
3701 // The sidebar is designed to display sibling functions, modules and
3702 // other miscellaneous information. since there are lots of sibling
3703 // items (and that causes quadratic growth in large modules),
3704 // we refactor common parts into a shared JavaScript file per module.
3705 // still, we don't move everything into JS because we want to preserve
3706 // as much HTML as possible in order to allow non-JS-enabled browsers
3707 // to navigate the documentation (though slightly inefficiently).
3708
3709 write!(buffer, "<p class='location'>");
3710 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3711 if i > 0 {
3712 write!(buffer, "::<wbr>");
3713 }
3714 write!(buffer, "<a href='{}index.html'>{}</a>",
3715 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3716 *name);
3717 }
3718 write!(buffer, "</p>");
3719
3720 // Sidebar refers to the enclosing module, not this module.
3721 let relpath = if it.is_mod() { "../" } else { "" };
3722 write!(buffer,
3723 "<script>window.sidebarCurrent = {{\
3724 name: '{name}', \
3725 ty: '{ty}', \
3726 relpath: '{path}'\
3727 }};</script>",
3728 name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
e74abb32 3729 ty = it.type_(),
e1599b0c
XL
3730 path = relpath);
3731 if parentlen == 0 {
3732 // There is no sidebar-items.js beyond the crate root path
3733 // FIXME maybe dynamic crate loading can be merged here
3734 } else {
3735 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>",
3736 path = relpath);
1a4d82fc 3737 }
e1599b0c
XL
3738 // Closes sidebar-elems div.
3739 write!(buffer, "</div>");
1a4d82fc
JJ
3740}
3741
a1dfa0c6
XL
3742fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
3743 if used_links.insert(url.clone()) {
3744 return url;
3745 }
3746 let mut add = 1;
3747 while used_links.insert(format!("{}-{}", url, add)) == false {
3748 add += 1;
3749 }
3750 format!("{}-{}", url, add)
3751}
3752
3753fn get_methods(
3754 i: &clean::Impl,
3755 for_deref: bool,
3756 used_links: &mut FxHashSet<String>,
416331ca 3757 deref_mut: bool,
a1dfa0c6 3758) -> Vec<String> {
abe05a73
XL
3759 i.items.iter().filter_map(|item| {
3760 match item.name {
e74abb32 3761 Some(ref name) if !name.is_empty() && item.is_method() => {
416331ca 3762 if !for_deref || should_render_item(item, deref_mut) {
a1dfa0c6
XL
3763 Some(format!("<a href=\"#{}\">{}</a>",
3764 get_next_url(used_links, format!("method.{}", name)),
3765 name))
abe05a73
XL
3766 } else {
3767 None
3768 }
3769 }
3770 _ => None,
3771 }
3772 }).collect::<Vec<_>>()
3773}
3774
3775// The point is to url encode any potential character from a type with genericity.
3776fn small_url_encode(s: &str) -> String {
3777 s.replace("<", "%3C")
3778 .replace(">", "%3E")
3779 .replace(" ", "%20")
3780 .replace("?", "%3F")
3781 .replace("'", "%27")
3782 .replace("&", "%26")
3783 .replace(",", "%2C")
3784 .replace(":", "%3A")
3785 .replace(";", "%3B")
3786 .replace("[", "%5B")
3787 .replace("]", "%5D")
ff7c6d11 3788 .replace("\"", "%22")
abe05a73
XL
3789}
3790
cc61c64b
XL
3791fn sidebar_assoc_items(it: &clean::Item) -> String {
3792 let mut out = String::new();
3793 let c = cache();
3794 if let Some(v) = c.impls.get(&it.def_id) {
a1dfa0c6
XL
3795 let mut used_links = FxHashSet::default();
3796
3797 {
e74abb32 3798 let used_links_bor = &mut used_links;
9fa01778
XL
3799 let mut ret = v.iter()
3800 .filter(|i| i.inner_impl().trait_.is_none())
3801 .flat_map(move |i| get_methods(i.inner_impl(),
3802 false,
e74abb32 3803 used_links_bor, false))
9fa01778
XL
3804 .collect::<Vec<_>>();
3805 // We want links' order to be reproducible so we don't use unstable sort.
3806 ret.sort();
a1dfa0c6
XL
3807 if !ret.is_empty() {
3808 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
9fa01778 3809 </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
a1dfa0c6 3810 }
cc61c64b
XL
3811 }
3812
3813 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3814 if let Some(impl_) = v.iter()
3815 .filter(|i| i.inner_impl().trait_.is_some())
3816 .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3817 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3818 match item.inner {
3819 clean::TypedefItem(ref t, true) => Some(&t.type_),
3820 _ => None,
3821 }
3822 }).next() {
3823 let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3824 c.primitive_locations.get(&prim).cloned()
3825 })).and_then(|did| c.impls.get(&did));
abe05a73
XL
3826 if let Some(impls) = inner_impl {
3827 out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
ff7c6d11 3828 out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
e74abb32
XL
3829 Escape(&format!(
3830 "{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print()
3831 )),
3832 Escape(&format!("{:#}", target.print()))));
abe05a73 3833 out.push_str("</a>");
9fa01778
XL
3834 let mut ret = impls.iter()
3835 .filter(|i| i.inner_impl().trait_.is_none())
3836 .flat_map(|i| get_methods(i.inner_impl(),
3837 true,
416331ca
XL
3838 &mut used_links,
3839 true))
9fa01778
XL
3840 .collect::<Vec<_>>();
3841 // We want links' order to be reproducible so we don't use unstable sort.
3842 ret.sort();
3843 if !ret.is_empty() {
3844 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
3845 ret.join("")));
3846 }
cc61c64b
XL
3847 }
3848 }
3849 }
0531ce1d 3850 let format_impls = |impls: Vec<&Impl>| {
b7449926 3851 let mut links = FxHashSet::default();
a1dfa0c6 3852
9fa01778
XL
3853 let mut ret = impls.iter()
3854 .filter_map(|i| {
3855 let is_negative_impl = is_negative_impl(i.inner_impl());
3856 if let Some(ref i) = i.inner_impl().trait_ {
e74abb32 3857 let i_display = format!("{:#}", i.print());
9fa01778 3858 let out = Escape(&i_display);
e74abb32 3859 let encoded = small_url_encode(&format!("{:#}", i.print()));
9fa01778
XL
3860 let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3861 encoded,
3862 if is_negative_impl { "!" } else { "" },
3863 out);
3864 if links.insert(generated.clone()) {
3865 Some(generated)
3866 } else {
3867 None
3868 }
3869 } else {
3870 None
3871 }
3872 })
3873 .collect::<Vec<String>>();
3874 ret.sort();
3875 ret.join("")
0531ce1d
XL
3876 };
3877
8faf50e0 3878 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
0531ce1d
XL
3879 .iter()
3880 .partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
8faf50e0
XL
3881 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
3882 .into_iter()
3883 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
0531ce1d
XL
3884
3885 let concrete_format = format_impls(concrete);
3886 let synthetic_format = format_impls(synthetic);
8faf50e0 3887 let blanket_format = format_impls(blanket_impl);
0531ce1d
XL
3888
3889 if !concrete_format.is_empty() {
abe05a73
XL
3890 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3891 Trait Implementations</a>");
0531ce1d
XL
3892 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", concrete_format));
3893 }
3894
3895 if !synthetic_format.is_empty() {
3896 out.push_str("<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
3897 Auto Trait Implementations</a>");
3898 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", synthetic_format));
abe05a73 3899 }
8faf50e0
XL
3900
3901 if !blanket_format.is_empty() {
3902 out.push_str("<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
3903 Blanket Implementations</a>");
3904 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", blanket_format));
3905 }
cc61c64b
XL
3906 }
3907 }
3908
3909 out
3910}
3911
e1599b0c 3912fn sidebar_struct(buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
cc61c64b 3913 let mut sidebar = String::new();
abe05a73 3914 let fields = get_struct_fields_name(&s.fields);
cc61c64b 3915
abe05a73 3916 if !fields.is_empty() {
cc61c64b 3917 if let doctree::Plain = s.struct_type {
abe05a73
XL
3918 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3919 <div class=\"sidebar-links\">{}</div>", fields));
cc61c64b
XL
3920 }
3921 }
3922
3923 sidebar.push_str(&sidebar_assoc_items(it));
3924
3925 if !sidebar.is_empty() {
e1599b0c 3926 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
cc61c64b 3927 }
cc61c64b
XL
3928}
3929
48663c56 3930fn get_id_for_impl_on_foreign_type(for_: &clean::Type, trait_: &clean::Type) -> String {
e74abb32 3931 small_url_encode(&format!("impl-{:#}-for-{:#}", trait_.print(), for_.print()))
48663c56
XL
3932}
3933
abe05a73
XL
3934fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3935 match item.inner {
3936 clean::ItemEnum::ImplItem(ref i) => {
3937 if let Some(ref trait_) = i.trait_ {
e74abb32
XL
3938 Some((
3939 format!("{:#}", i.for_.print()),
3940 get_id_for_impl_on_foreign_type(&i.for_, trait_),
3941 ))
abe05a73
XL
3942 } else {
3943 None
3944 }
3945 },
3946 _ => None,
3947 }
3948}
3949
ff7c6d11
XL
3950fn is_negative_impl(i: &clean::Impl) -> bool {
3951 i.polarity == Some(clean::ImplPolarity::Negative)
3952}
3953
e1599b0c 3954fn sidebar_trait(buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
cc61c64b
XL
3955 let mut sidebar = String::new();
3956
abe05a73
XL
3957 let types = t.items
3958 .iter()
3959 .filter_map(|m| {
3960 match m.name {
3961 Some(ref name) if m.is_associated_type() => {
3962 Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3963 name=name))
3964 }
3965 _ => None,
3966 }
3967 })
3968 .collect::<String>();
3969 let consts = t.items
3970 .iter()
3971 .filter_map(|m| {
3972 match m.name {
3973 Some(ref name) if m.is_associated_const() => {
3974 Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3975 name=name))
3976 }
3977 _ => None,
3978 }
3979 })
3980 .collect::<String>();
9fa01778
XL
3981 let mut required = t.items
3982 .iter()
3983 .filter_map(|m| {
3984 match m.name {
3985 Some(ref name) if m.is_ty_method() => {
3986 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3987 name=name))
3988 }
3989 _ => None,
abe05a73 3990 }
9fa01778
XL
3991 })
3992 .collect::<Vec<String>>();
3993 let mut provided = t.items
3994 .iter()
3995 .filter_map(|m| {
3996 match m.name {
3997 Some(ref name) if m.is_method() => {
3998 Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
3999 }
4000 _ => None,
abe05a73 4001 }
9fa01778
XL
4002 })
4003 .collect::<Vec<String>>();
cc61c64b 4004
abe05a73
XL
4005 if !types.is_empty() {
4006 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
4007 Associated Types</a><div class=\"sidebar-links\">{}</div>",
4008 types));
cc61c64b 4009 }
abe05a73
XL
4010 if !consts.is_empty() {
4011 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
4012 Associated Constants</a><div class=\"sidebar-links\">{}</div>",
4013 consts));
cc61c64b 4014 }
abe05a73 4015 if !required.is_empty() {
9fa01778 4016 required.sort();
abe05a73
XL
4017 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
4018 Required Methods</a><div class=\"sidebar-links\">{}</div>",
9fa01778 4019 required.join("")));
cc61c64b 4020 }
abe05a73 4021 if !provided.is_empty() {
9fa01778 4022 provided.sort();
abe05a73
XL
4023 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
4024 Provided Methods</a><div class=\"sidebar-links\">{}</div>",
9fa01778 4025 provided.join("")));
cc61c64b
XL
4026 }
4027
ea8adc8c
XL
4028 let c = cache();
4029
4030 if let Some(implementors) = c.implementors.get(&it.def_id) {
9fa01778
XL
4031 let mut res = implementors.iter()
4032 .filter(|i| i.inner_impl().for_.def_id()
4033 .map_or(false, |d| !c.paths.contains_key(&d)))
4034 .filter_map(|i| {
4035 match extract_for_impl_name(&i.impl_item) {
48663c56
XL
4036 Some((ref name, ref id)) => {
4037 Some(format!("<a href=\"#{}\">{}</a>",
4038 id,
9fa01778
XL
4039 Escape(name)))
4040 }
4041 _ => None,
abe05a73 4042 }
9fa01778
XL
4043 })
4044 .collect::<Vec<String>>();
abe05a73 4045 if !res.is_empty() {
9fa01778 4046 res.sort();
abe05a73
XL
4047 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
4048 Implementations on Foreign Types</a><div \
4049 class=\"sidebar-links\">{}</div>",
9fa01778 4050 res.join("")));
abe05a73
XL
4051 }
4052 }
4053
4054 sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
0531ce1d
XL
4055 if t.auto {
4056 sidebar.push_str("<a class=\"sidebar-title\" \
4057 href=\"#synthetic-implementors\">Auto Implementors</a>");
4058 }
ea8adc8c 4059
abe05a73 4060 sidebar.push_str(&sidebar_assoc_items(it));
cc61c64b 4061
e1599b0c 4062 write!(buf, "<div class=\"block items\">{}</div>", sidebar)
cc61c64b
XL
4063}
4064
e74abb32 4065fn sidebar_primitive(buf: &mut Buffer, it: &clean::Item) {
cc61c64b
XL
4066 let sidebar = sidebar_assoc_items(it);
4067
4068 if !sidebar.is_empty() {
e1599b0c 4069 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
cc61c64b 4070 }
cc61c64b
XL
4071}
4072
e74abb32 4073fn sidebar_typedef(buf: &mut Buffer, it: &clean::Item) {
041b39d2
XL
4074 let sidebar = sidebar_assoc_items(it);
4075
4076 if !sidebar.is_empty() {
e1599b0c 4077 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
041b39d2 4078 }
041b39d2
XL
4079}
4080
abe05a73
XL
4081fn get_struct_fields_name(fields: &[clean::Item]) -> String {
4082 fields.iter()
4083 .filter(|f| if let clean::StructFieldItem(..) = f.inner {
4084 true
4085 } else {
4086 false
4087 })
4088 .filter_map(|f| match f.name {
4089 Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
4090 {name}</a>", name=name)),
4091 _ => None,
4092 })
4093 .collect()
4094}
4095
e1599b0c 4096fn sidebar_union(buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
cc61c64b 4097 let mut sidebar = String::new();
abe05a73 4098 let fields = get_struct_fields_name(&u.fields);
cc61c64b 4099
abe05a73
XL
4100 if !fields.is_empty() {
4101 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
4102 <div class=\"sidebar-links\">{}</div>", fields));
cc61c64b
XL
4103 }
4104
4105 sidebar.push_str(&sidebar_assoc_items(it));
4106
4107 if !sidebar.is_empty() {
e1599b0c 4108 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
cc61c64b 4109 }
cc61c64b
XL
4110}
4111
e1599b0c 4112fn sidebar_enum(buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
cc61c64b
XL
4113 let mut sidebar = String::new();
4114
abe05a73
XL
4115 let variants = e.variants.iter()
4116 .filter_map(|v| match v.name {
4117 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
4118 </a>", name = name)),
4119 _ => None,
4120 })
4121 .collect::<String>();
4122 if !variants.is_empty() {
4123 sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
4124 <div class=\"sidebar-links\">{}</div>", variants));
cc61c64b
XL
4125 }
4126
4127 sidebar.push_str(&sidebar_assoc_items(it));
4128
4129 if !sidebar.is_empty() {
e1599b0c 4130 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
cc61c64b 4131 }
cc61c64b
XL
4132}
4133
94b46f34
XL
4134fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
4135 match *ty {
4136 ItemType::ExternCrate |
4137 ItemType::Import => ("reexports", "Re-exports"),
4138 ItemType::Module => ("modules", "Modules"),
4139 ItemType::Struct => ("structs", "Structs"),
4140 ItemType::Union => ("unions", "Unions"),
4141 ItemType::Enum => ("enums", "Enums"),
4142 ItemType::Function => ("functions", "Functions"),
4143 ItemType::Typedef => ("types", "Type Definitions"),
4144 ItemType::Static => ("statics", "Statics"),
4145 ItemType::Constant => ("constants", "Constants"),
4146 ItemType::Trait => ("traits", "Traits"),
4147 ItemType::Impl => ("impls", "Implementations"),
4148 ItemType::TyMethod => ("tymethods", "Type Methods"),
4149 ItemType::Method => ("methods", "Methods"),
4150 ItemType::StructField => ("fields", "Struct Fields"),
4151 ItemType::Variant => ("variants", "Variants"),
4152 ItemType::Macro => ("macros", "Macros"),
4153 ItemType::Primitive => ("primitives", "Primitive Types"),
dc9dc135
XL
4154 ItemType::AssocType => ("associated-types", "Associated Types"),
4155 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
94b46f34
XL
4156 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
4157 ItemType::Keyword => ("keywords", "Keywords"),
416331ca 4158 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
0bf4aa26
XL
4159 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
4160 ItemType::ProcDerive => ("derives", "Derive Macros"),
9fa01778 4161 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
94b46f34
XL
4162 }
4163}
4164
e74abb32 4165fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
cc61c64b
XL
4166 let mut sidebar = String::new();
4167
4168 if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
4169 it.type_() == ItemType::Import) {
4170 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4171 id = "reexports",
2c00a5a8 4172 name = "Re-exports"));
cc61c64b
XL
4173 }
4174
4175 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
4176 // to print its headings
4177 for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
4178 ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
4179 ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
4180 ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
416331ca
XL
4181 ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType,
4182 ItemType::Keyword] {
2c00a5a8 4183 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
94b46f34 4184 let (short, name) = item_ty_to_strs(&myty);
cc61c64b
XL
4185 sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
4186 id = short,
4187 name = name));
4188 }
4189 }
4190
4191 if !sidebar.is_empty() {
e1599b0c 4192 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
cc61c64b 4193 }
cc61c64b
XL
4194}
4195
e1599b0c 4196fn sidebar_foreign_type(buf: &mut Buffer, it: &clean::Item) {
abe05a73
XL
4197 let sidebar = sidebar_assoc_items(it);
4198 if !sidebar.is_empty() {
e1599b0c 4199 write!(buf, "<div class=\"block items\">{}</div>", sidebar);
abe05a73 4200 }
abe05a73
XL
4201}
4202
e1599b0c 4203fn item_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, t: &clean::Macro) {
0531ce1d
XL
4204 wrap_into_docblock(w, |w| {
4205 w.write_str(&highlight::render_with_highlighting(&t.source,
4206 Some("macro"),
4207 None,
0531ce1d 4208 None))
e1599b0c 4209 });
e9174d1e 4210 document(w, cx, it)
1a4d82fc
JJ
4211}
4212
e1599b0c 4213fn item_proc_macro(w: &mut Buffer, cx: &Context, it: &clean::Item, m: &clean::ProcMacro) {
0bf4aa26
XL
4214 let name = it.name.as_ref().expect("proc-macros always have names");
4215 match m.kind {
4216 MacroKind::Bang => {
e1599b0c
XL
4217 write!(w, "<pre class='rust macro'>");
4218 write!(w, "{}!() {{ /* proc-macro */ }}", name);
4219 write!(w, "</pre>");
0bf4aa26
XL
4220 }
4221 MacroKind::Attr => {
e1599b0c
XL
4222 write!(w, "<pre class='rust attr'>");
4223 write!(w, "#[{}]", name);
4224 write!(w, "</pre>");
0bf4aa26
XL
4225 }
4226 MacroKind::Derive => {
e1599b0c
XL
4227 write!(w, "<pre class='rust derive'>");
4228 write!(w, "#[derive({})]", name);
0bf4aa26 4229 if !m.helpers.is_empty() {
e1599b0c
XL
4230 writeln!(w, "\n{{");
4231 writeln!(w, " // Attributes available to this derive:");
0bf4aa26 4232 for attr in &m.helpers {
e1599b0c 4233 writeln!(w, " #[{}]", attr);
0bf4aa26 4234 }
e1599b0c 4235 write!(w, "}}");
0bf4aa26 4236 }
e1599b0c 4237 write!(w, "</pre>");
0bf4aa26 4238 }
0bf4aa26
XL
4239 }
4240 document(w, cx, it)
4241}
4242
e74abb32 4243fn item_primitive(w: &mut Buffer, cx: &Context, it: &clean::Item) {
e1599b0c 4244 document(w, cx, it);
7453a54e 4245 render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
1a4d82fc
JJ
4246}
4247
e74abb32 4248fn item_keyword(w: &mut Buffer, cx: &Context, it: &clean::Item) {
94b46f34
XL
4249 document(w, cx, it)
4250}
4251
e1599b0c 4252crate const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
1a4d82fc
JJ
4253
4254fn make_item_keywords(it: &clean::Item) -> String {
54a0048b 4255 format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
1a4d82fc
JJ
4256}
4257
0531ce1d
XL
4258/// Returns a list of all paths used in the type.
4259/// This is used to help deduplicate imported impls
4260/// for reexported types. If any of the contained
4261/// types are re-exported, we don't use the corresponding
4262/// entry from the js file, as inlining will have already
4263/// picked up the impl
4264fn collect_paths_for_type(first_ty: clean::Type) -> Vec<String> {
4265 let mut out = Vec::new();
0bf4aa26 4266 let mut visited = FxHashSet::default();
0531ce1d
XL
4267 let mut work = VecDeque::new();
4268 let cache = cache();
4269
4270 work.push_back(first_ty);
4271
4272 while let Some(ty) = work.pop_front() {
4273 if !visited.insert(ty.clone()) {
4274 continue;
4275 }
4276
4277 match ty {
4278 clean::Type::ResolvedPath { did, .. } => {
4279 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
4280 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
4281
4282 match fqp {
4283 Some(path) => {
4284 out.push(path.join("::"));
4285 },
4286 _ => {}
4287 };
4288
4289 },
4290 clean::Type::Tuple(tys) => {
4291 work.extend(tys.into_iter());
4292 },
4293 clean::Type::Slice(ty) => {
4294 work.push_back(*ty);
4295 }
4296 clean::Type::Array(ty, _) => {
4297 work.push_back(*ty);
4298 },
0531ce1d
XL
4299 clean::Type::RawPointer(_, ty) => {
4300 work.push_back(*ty);
4301 },
4302 clean::Type::BorrowedRef { type_, .. } => {
4303 work.push_back(*type_);
4304 },
4305 clean::Type::QPath { self_type, trait_, .. } => {
4306 work.push_back(*self_type);
4307 work.push_back(*trait_);
4308 },
4309 _ => {}
4310 }
4311 };
4312 out
4313}
4314
e74abb32 4315crate fn cache() -> Arc<Cache> {
1a4d82fc
JJ
4316 CACHE_KEY.with(|c| c.borrow().clone())
4317}