]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/render/mod.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / librustdoc / html / render / mod.rs
1 //! Rustdoc's HTML rendering module.
2 //!
3 //! This modules contains the bulk of the logic necessary for rendering a
4 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
5 //! rendering process is largely driven by the `format!` syntax extension to
6 //! perform all I/O into files and streams.
7 //!
8 //! The rendering process is largely driven by the `Context` and `Cache`
9 //! structures. The cache is pre-populated by crawling the crate in question,
10 //! and then it is shared among the various rendering threads. The cache is meant
11 //! to be a fairly large structure not implementing `Clone` (because it's shared
12 //! among threads). The context, however, should be a lightweight structure. This
13 //! is cloned per-thread and contains information about what is currently being
14 //! rendered.
15 //!
16 //! In order to speed up rendering (mostly because of markdown rendering), the
17 //! rendering process has been parallelized. This parallelization is only
18 //! exposed through the `crate` method on the context, and then also from the
19 //! fact that the shared cache is stored in TLS (and must be accessed as such).
20 //!
21 //! In addition to rendering the crate itself, this module is also responsible
22 //! for creating the corresponding search index and source file renderings.
23 //! These threads are not parallelized (they haven't been a bottleneck yet), and
24 //! both occur before the crate is rendered.
25
26 crate mod cache;
27
28 #[cfg(test)]
29 mod tests;
30
31 mod context;
32 mod print_item;
33 mod write_shared;
34
35 crate use context::*;
36 crate use write_shared::FILES_UNVERSIONED;
37
38 use std::cell::{Cell, RefCell};
39 use std::collections::VecDeque;
40 use std::default::Default;
41 use std::fmt;
42 use std::path::{Path, PathBuf};
43 use std::str;
44 use std::string::ToString;
45 use std::sync::mpsc::Receiver;
46
47 use itertools::Itertools;
48 use rustc_ast_pretty::pprust;
49 use rustc_attr::{Deprecation, StabilityLevel};
50 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
51 use rustc_hir as hir;
52 use rustc_hir::def::CtorKind;
53 use rustc_hir::def_id::DefId;
54 use rustc_hir::Mutability;
55 use rustc_middle::middle::stability;
56 use rustc_middle::ty::TyCtxt;
57 use rustc_span::edition::Edition;
58 use rustc_span::symbol::{kw, sym, Symbol};
59 use serde::ser::SerializeSeq;
60 use serde::{Serialize, Serializer};
61
62 use crate::clean::{self, GetDefId, RenderedLink, SelfTy, TypeKind};
63 use crate::docfs::{DocFS, PathError};
64 use crate::error::Error;
65 use crate::formats::cache::Cache;
66 use crate::formats::item_type::ItemType;
67 use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode};
68 use crate::html::escape::Escape;
69 use crate::html::format::{
70 href, print_abi_with_space, print_default_space, print_generic_bounds, Buffer, Function,
71 PrintWithSpace, WhereClause,
72 };
73 use crate::html::layout;
74 use crate::html::markdown::{self, ErrorCodes, Markdown, MarkdownHtml, MarkdownSummaryLine};
75
76 /// A pair of name and its optional document.
77 crate type NameDoc = (String, Option<String>);
78
79 crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
80 crate::html::format::display_fn(move |f| {
81 if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) }
82 })
83 }
84
85 /// Shared mutable state used in [`Context`] and elsewhere.
86 crate struct SharedContext<'tcx> {
87 crate tcx: TyCtxt<'tcx>,
88 /// The path to the crate root source minus the file name.
89 /// Used for simplifying paths to the highlighted source code files.
90 crate src_root: PathBuf,
91 /// This describes the layout of each page, and is not modified after
92 /// creation of the context (contains info like the favicon and added html).
93 crate layout: layout::Layout,
94 /// This flag indicates whether `[src]` links should be generated or not. If
95 /// the source files are present in the html rendering, then this will be
96 /// `true`.
97 crate include_sources: bool,
98 /// The local file sources we've emitted and their respective url-paths.
99 crate local_sources: FxHashMap<PathBuf, String>,
100 /// Whether the collapsed pass ran
101 collapsed: bool,
102 /// The base-URL of the issue tracker for when an item has been tagged with
103 /// an issue number.
104 issue_tracker_base_url: Option<String>,
105 /// The directories that have already been created in this doc run. Used to reduce the number
106 /// of spurious `create_dir_all` calls.
107 created_dirs: RefCell<FxHashSet<PathBuf>>,
108 /// This flag indicates whether listings of modules (in the side bar and documentation itself)
109 /// should be ordered alphabetically or in order of appearance (in the source code).
110 sort_modules_alphabetically: bool,
111 /// Additional CSS files to be added to the generated docs.
112 crate style_files: Vec<StylePath>,
113 /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes
114 /// "light-v2.css").
115 crate resource_suffix: String,
116 /// Optional path string to be used to load static files on output pages. If not set, uses
117 /// combinations of `../` to reach the documentation root.
118 crate static_root_path: Option<String>,
119 /// The fs handle we are working with.
120 crate fs: DocFS,
121 /// The default edition used to parse doctests.
122 crate edition: Edition,
123 codes: ErrorCodes,
124 playground: Option<markdown::Playground>,
125 all: RefCell<AllTypes>,
126 /// Storage for the errors produced while generating documentation so they
127 /// can be printed together at the end.
128 errors: Receiver<String>,
129 /// `None` by default, depends on the `generate-redirect-map` option flag. If this field is set
130 /// to `Some(...)`, it'll store redirections and then generate a JSON file at the top level of
131 /// the crate.
132 redirections: Option<RefCell<FxHashMap<String, String>>>,
133 }
134
135 impl SharedContext<'_> {
136 crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> {
137 let mut dirs = self.created_dirs.borrow_mut();
138 if !dirs.contains(dst) {
139 try_err!(self.fs.create_dir_all(dst), dst);
140 dirs.insert(dst.to_path_buf());
141 }
142
143 Ok(())
144 }
145
146 /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
147 /// `collapsed_doc_value` of the given item.
148 crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> {
149 if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() }
150 }
151 }
152
153 // Helper structs for rendering items/sidebars and carrying along contextual
154 // information
155
156 /// Struct representing one entry in the JS search index. These are all emitted
157 /// by hand to a large JS file at the end of cache-creation.
158 #[derive(Debug)]
159 crate struct IndexItem {
160 crate ty: ItemType,
161 crate name: String,
162 crate path: String,
163 crate desc: String,
164 crate parent: Option<DefId>,
165 crate parent_idx: Option<usize>,
166 crate search_type: Option<IndexItemFunctionType>,
167 }
168
169 /// A type used for the search index.
170 #[derive(Debug)]
171 crate struct RenderType {
172 ty: Option<DefId>,
173 idx: Option<usize>,
174 name: Option<String>,
175 generics: Option<Vec<Generic>>,
176 }
177
178 impl Serialize for RenderType {
179 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
180 where
181 S: Serializer,
182 {
183 if let Some(name) = &self.name {
184 let mut seq = serializer.serialize_seq(None)?;
185 if let Some(id) = self.idx {
186 seq.serialize_element(&id)?;
187 } else {
188 seq.serialize_element(&name)?;
189 }
190 if let Some(generics) = &self.generics {
191 seq.serialize_element(&generics)?;
192 }
193 seq.end()
194 } else {
195 serializer.serialize_none()
196 }
197 }
198 }
199
200 /// A type used for the search index.
201 #[derive(Debug)]
202 crate struct Generic {
203 name: String,
204 defid: Option<DefId>,
205 idx: Option<usize>,
206 }
207
208 impl Serialize for Generic {
209 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
210 where
211 S: Serializer,
212 {
213 if let Some(id) = self.idx {
214 serializer.serialize_some(&id)
215 } else {
216 serializer.serialize_some(&self.name)
217 }
218 }
219 }
220
221 /// Full type of functions/methods in the search index.
222 #[derive(Debug)]
223 crate struct IndexItemFunctionType {
224 inputs: Vec<TypeWithKind>,
225 output: Option<Vec<TypeWithKind>>,
226 }
227
228 impl Serialize for IndexItemFunctionType {
229 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
230 where
231 S: Serializer,
232 {
233 // If we couldn't figure out a type, just write `null`.
234 let mut iter = self.inputs.iter();
235 if match self.output {
236 Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()),
237 None => iter.any(|ref i| i.ty.name.is_none()),
238 } {
239 serializer.serialize_none()
240 } else {
241 let mut seq = serializer.serialize_seq(None)?;
242 seq.serialize_element(&self.inputs)?;
243 if let Some(output) = &self.output {
244 if output.len() > 1 {
245 seq.serialize_element(&output)?;
246 } else {
247 seq.serialize_element(&output[0])?;
248 }
249 }
250 seq.end()
251 }
252 }
253 }
254
255 #[derive(Debug)]
256 crate struct TypeWithKind {
257 ty: RenderType,
258 kind: TypeKind,
259 }
260
261 impl From<(RenderType, TypeKind)> for TypeWithKind {
262 fn from(x: (RenderType, TypeKind)) -> TypeWithKind {
263 TypeWithKind { ty: x.0, kind: x.1 }
264 }
265 }
266
267 impl Serialize for TypeWithKind {
268 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
269 where
270 S: Serializer,
271 {
272 (&self.ty.name, ItemType::from(self.kind)).serialize(serializer)
273 }
274 }
275
276 #[derive(Debug, Clone)]
277 crate struct StylePath {
278 /// The path to the theme
279 crate path: PathBuf,
280 /// What the `disabled` attribute should be set to in the HTML tag
281 crate disabled: bool,
282 }
283
284 thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0));
285
286 crate const INITIAL_IDS: [&'static str; 15] = [
287 "main",
288 "search",
289 "help",
290 "TOC",
291 "render-detail",
292 "associated-types",
293 "associated-const",
294 "required-methods",
295 "provided-methods",
296 "implementors",
297 "synthetic-implementors",
298 "implementors-list",
299 "synthetic-implementors-list",
300 "methods",
301 "implementations",
302 ];
303
304 fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) {
305 if let Some(l) = cx.src_href(item) {
306 write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l)
307 }
308 }
309
310 #[derive(Debug, Eq, PartialEq, Hash)]
311 struct ItemEntry {
312 url: String,
313 name: String,
314 }
315
316 impl ItemEntry {
317 fn new(mut url: String, name: String) -> ItemEntry {
318 while url.starts_with('/') {
319 url.remove(0);
320 }
321 ItemEntry { url, name }
322 }
323 }
324
325 impl ItemEntry {
326 crate fn print(&self) -> impl fmt::Display + '_ {
327 crate::html::format::display_fn(move |f| {
328 write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name))
329 })
330 }
331 }
332
333 impl PartialOrd for ItemEntry {
334 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
335 Some(self.cmp(other))
336 }
337 }
338
339 impl Ord for ItemEntry {
340 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
341 self.name.cmp(&other.name)
342 }
343 }
344
345 #[derive(Debug)]
346 struct AllTypes {
347 structs: FxHashSet<ItemEntry>,
348 enums: FxHashSet<ItemEntry>,
349 unions: FxHashSet<ItemEntry>,
350 primitives: FxHashSet<ItemEntry>,
351 traits: FxHashSet<ItemEntry>,
352 macros: FxHashSet<ItemEntry>,
353 functions: FxHashSet<ItemEntry>,
354 typedefs: FxHashSet<ItemEntry>,
355 opaque_tys: FxHashSet<ItemEntry>,
356 statics: FxHashSet<ItemEntry>,
357 constants: FxHashSet<ItemEntry>,
358 keywords: FxHashSet<ItemEntry>,
359 attributes: FxHashSet<ItemEntry>,
360 derives: FxHashSet<ItemEntry>,
361 trait_aliases: FxHashSet<ItemEntry>,
362 }
363
364 impl AllTypes {
365 fn new() -> AllTypes {
366 let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default());
367 AllTypes {
368 structs: new_set(100),
369 enums: new_set(100),
370 unions: new_set(100),
371 primitives: new_set(26),
372 traits: new_set(100),
373 macros: new_set(100),
374 functions: new_set(100),
375 typedefs: new_set(100),
376 opaque_tys: new_set(100),
377 statics: new_set(100),
378 constants: new_set(100),
379 keywords: new_set(100),
380 attributes: new_set(100),
381 derives: new_set(100),
382 trait_aliases: new_set(100),
383 }
384 }
385
386 fn append(&mut self, item_name: String, item_type: &ItemType) {
387 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
388 if let Some(name) = url.pop() {
389 let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name);
390 url.push(name);
391 let name = url.join("::");
392 match *item_type {
393 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
394 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
395 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
396 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
397 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
398 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
399 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
400 ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)),
401 ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)),
402 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
403 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
404 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
405 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
406 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
407 _ => true,
408 };
409 }
410 }
411 }
412
413 impl AllTypes {
414 fn print(self, f: &mut Buffer) {
415 fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) {
416 if !e.is_empty() {
417 let mut e: Vec<&ItemEntry> = e.iter().collect();
418 e.sort();
419 write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class);
420
421 for s in e.iter() {
422 write!(f, "<li>{}</li>", s.print());
423 }
424
425 f.write_str("</ul>");
426 }
427 }
428
429 f.write_str(
430 "<h1 class=\"fqn\">\
431 <span class=\"in-band\">List of all items</span>\
432 <span class=\"out-of-band\">\
433 <span id=\"render-detail\">\
434 <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \
435 title=\"collapse all docs\">\
436 [<span class=\"inner\">&#x2212;</span>]\
437 </a>\
438 </span>
439 </span>
440 </h1>",
441 );
442 // Note: print_entries does not escape the title, because we know the current set of titles
443 // don't require escaping.
444 print_entries(f, &self.structs, "Structs", "structs");
445 print_entries(f, &self.enums, "Enums", "enums");
446 print_entries(f, &self.unions, "Unions", "unions");
447 print_entries(f, &self.primitives, "Primitives", "primitives");
448 print_entries(f, &self.traits, "Traits", "traits");
449 print_entries(f, &self.macros, "Macros", "macros");
450 print_entries(f, &self.attributes, "Attribute Macros", "attributes");
451 print_entries(f, &self.derives, "Derive Macros", "derives");
452 print_entries(f, &self.functions, "Functions", "functions");
453 print_entries(f, &self.typedefs, "Typedefs", "typedefs");
454 print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases");
455 print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types");
456 print_entries(f, &self.statics, "Statics", "statics");
457 print_entries(f, &self.constants, "Constants", "constants")
458 }
459 }
460
461 #[derive(Debug)]
462 enum Setting {
463 Section {
464 description: &'static str,
465 sub_settings: Vec<Setting>,
466 },
467 Toggle {
468 js_data_name: &'static str,
469 description: &'static str,
470 default_value: bool,
471 },
472 Select {
473 js_data_name: &'static str,
474 description: &'static str,
475 default_value: &'static str,
476 options: Vec<(String, String)>,
477 },
478 }
479
480 impl Setting {
481 fn display(&self, root_path: &str, suffix: &str) -> String {
482 match *self {
483 Setting::Section { description, ref sub_settings } => format!(
484 "<div class=\"setting-line\">\
485 <div class=\"title\">{}</div>\
486 <div class=\"sub-settings\">{}</div>
487 </div>",
488 description,
489 sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>()
490 ),
491 Setting::Toggle { js_data_name, description, default_value } => format!(
492 "<div class=\"setting-line\">\
493 <label class=\"toggle\">\
494 <input type=\"checkbox\" id=\"{}\" {}>\
495 <span class=\"slider\"></span>\
496 </label>\
497 <div>{}</div>\
498 </div>",
499 js_data_name,
500 if default_value { " checked" } else { "" },
501 description,
502 ),
503 Setting::Select { js_data_name, description, default_value, ref options } => format!(
504 "<div class=\"setting-line\">\
505 <div>{}</div>\
506 <label class=\"select-wrapper\">\
507 <select id=\"{}\" autocomplete=\"off\">{}</select>\
508 <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\
509 </label>\
510 </div>",
511 description,
512 js_data_name,
513 options
514 .iter()
515 .map(|opt| format!(
516 "<option value=\"{}\" {}>{}</option>",
517 opt.0,
518 if opt.0 == default_value { "selected" } else { "" },
519 opt.1,
520 ))
521 .collect::<String>(),
522 root_path,
523 suffix,
524 ),
525 }
526 }
527 }
528
529 impl From<(&'static str, &'static str, bool)> for Setting {
530 fn from(values: (&'static str, &'static str, bool)) -> Setting {
531 Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 }
532 }
533 }
534
535 impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting {
536 fn from(values: (&'static str, Vec<T>)) -> Setting {
537 Setting::Section {
538 description: values.0,
539 sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(),
540 }
541 }
542 }
543
544 fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> {
545 let theme_names: Vec<(String, String)> = themes
546 .iter()
547 .map(|entry| {
548 let theme =
549 try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path)
550 .to_string();
551
552 Ok((theme.clone(), theme))
553 })
554 .collect::<Result<_, Error>>()?;
555
556 // (id, explanation, default value)
557 let settings: &[Setting] = &[
558 (
559 "Theme preferences",
560 vec![
561 Setting::from(("use-system-theme", "Use system theme", true)),
562 Setting::Select {
563 js_data_name: "preferred-dark-theme",
564 description: "Preferred dark theme",
565 default_value: "dark",
566 options: theme_names.clone(),
567 },
568 Setting::Select {
569 js_data_name: "preferred-light-theme",
570 description: "Preferred light theme",
571 default_value: "light",
572 options: theme_names,
573 },
574 ],
575 )
576 .into(),
577 (
578 "Auto-hide item declarations",
579 vec![
580 ("auto-hide-struct", "Auto-hide structs declaration", true),
581 ("auto-hide-enum", "Auto-hide enums declaration", false),
582 ("auto-hide-union", "Auto-hide unions declaration", true),
583 ("auto-hide-trait", "Auto-hide traits declaration", true),
584 ("auto-hide-macro", "Auto-hide macros declaration", false),
585 ],
586 )
587 .into(),
588 ("auto-hide-attributes", "Auto-hide item attributes.", true).into(),
589 ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(),
590 ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true)
591 .into(),
592 ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(),
593 ("go-to-only-result", "Directly go to item in search if there is only one result", false)
594 .into(),
595 ("line-numbers", "Show line numbers on code examples", false).into(),
596 ("disable-shortcuts", "Disable keyboard shortcuts", false).into(),
597 ];
598
599 Ok(format!(
600 "<h1 class=\"fqn\">\
601 <span class=\"in-band\">Rustdoc settings</span>\
602 </h1>\
603 <div class=\"settings\">{}</div>\
604 <script src=\"{}settings{}.js\"></script>",
605 settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(),
606 root_path,
607 suffix
608 ))
609 }
610
611 fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) {
612 if let Some(ref name) = item.name {
613 info!("Documenting {}", name);
614 }
615 document_item_info(w, cx, item, false, parent);
616 document_full(w, item, cx, "", false);
617 }
618
619 /// Render md_text as markdown.
620 fn render_markdown(
621 w: &mut Buffer,
622 cx: &Context<'_>,
623 md_text: &str,
624 links: Vec<RenderedLink>,
625 prefix: &str,
626 is_hidden: bool,
627 ) {
628 let mut ids = cx.id_map.borrow_mut();
629 write!(
630 w,
631 "<div class=\"docblock{}\">{}{}</div>",
632 if is_hidden { " hidden" } else { "" },
633 prefix,
634 Markdown(
635 md_text,
636 &links,
637 &mut ids,
638 cx.shared.codes,
639 cx.shared.edition,
640 &cx.shared.playground
641 )
642 .into_string()
643 )
644 }
645
646 /// Writes a documentation block containing only the first paragraph of the documentation. If the
647 /// docs are longer, a "Read more" link is appended to the end.
648 fn document_short(
649 w: &mut Buffer,
650 item: &clean::Item,
651 cx: &Context<'_>,
652 link: AssocItemLink<'_>,
653 prefix: &str,
654 is_hidden: bool,
655 parent: Option<&clean::Item>,
656 show_def_docs: bool,
657 ) {
658 document_item_info(w, cx, item, is_hidden, parent);
659 if !show_def_docs {
660 return;
661 }
662 if let Some(s) = item.doc_value() {
663 let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string();
664
665 if s.contains('\n') {
666 let link =
667 format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache()));
668
669 if let Some(idx) = summary_html.rfind("</p>") {
670 summary_html.insert_str(idx, &link);
671 } else {
672 summary_html.push_str(&link);
673 }
674 }
675
676 write!(
677 w,
678 "<div class='docblock{}'>{}{}</div>",
679 if is_hidden { " hidden" } else { "" },
680 prefix,
681 summary_html,
682 );
683 } else if !prefix.is_empty() {
684 write!(
685 w,
686 "<div class=\"docblock{}\">{}</div>",
687 if is_hidden { " hidden" } else { "" },
688 prefix
689 );
690 }
691 }
692
693 fn document_full(
694 w: &mut Buffer,
695 item: &clean::Item,
696 cx: &Context<'_>,
697 prefix: &str,
698 is_hidden: bool,
699 ) {
700 if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
701 debug!("Doc block: =====\n{}\n=====", s);
702 render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden);
703 } else if !prefix.is_empty() {
704 if is_hidden {
705 w.write_str("<div class=\"docblock hidden\">");
706 } else {
707 w.write_str("<div class=\"docblock\">");
708 }
709 w.write_str(prefix);
710 w.write_str("</div>");
711 }
712 }
713
714 /// Add extra information about an item such as:
715 ///
716 /// * Stability
717 /// * Deprecated
718 /// * Required features (through the `doc_cfg` feature)
719 fn document_item_info(
720 w: &mut Buffer,
721 cx: &Context<'_>,
722 item: &clean::Item,
723 is_hidden: bool,
724 parent: Option<&clean::Item>,
725 ) {
726 let item_infos = short_item_info(item, cx, parent);
727 if !item_infos.is_empty() {
728 if is_hidden {
729 w.write_str("<div class=\"item-info hidden\">");
730 } else {
731 w.write_str("<div class=\"item-info\">");
732 }
733 for info in item_infos {
734 w.write_str(&info);
735 }
736 w.write_str("</div>");
737 }
738 }
739
740 fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
741 let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) {
742 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
743 (cfg, _) => cfg.as_deref().cloned(),
744 };
745
746 debug!(
747 "Portability {:?} - {:?} = {:?}",
748 item.attrs.cfg,
749 parent.and_then(|p| p.attrs.cfg.as_ref()),
750 cfg
751 );
752
753 Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html()))
754 }
755
756 /// Render the stability, deprecation and portability information that is displayed at the top of
757 /// the item's documentation.
758 fn short_item_info(
759 item: &clean::Item,
760 cx: &Context<'_>,
761 parent: Option<&clean::Item>,
762 ) -> Vec<String> {
763 let mut extra_info = vec![];
764 let error_codes = cx.shared.codes;
765
766 if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) =
767 item.deprecation(cx.tcx())
768 {
769 // We display deprecation messages for #[deprecated] and #[rustc_deprecated]
770 // but only display the future-deprecation messages for #[rustc_deprecated].
771 let mut message = if let Some(since) = since {
772 let since = &since.as_str();
773 if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
774 if *since == "TBD" {
775 String::from("Deprecating in a future Rust version")
776 } else {
777 format!("Deprecating in {}", Escape(since))
778 }
779 } else {
780 format!("Deprecated since {}", Escape(since))
781 }
782 } else {
783 String::from("Deprecated")
784 };
785
786 if let Some(note) = note {
787 let note = note.as_str();
788 let mut ids = cx.id_map.borrow_mut();
789 let html = MarkdownHtml(
790 &note,
791 &mut ids,
792 error_codes,
793 cx.shared.edition,
794 &cx.shared.playground,
795 );
796 message.push_str(&format!(": {}", html.into_string()));
797 }
798 extra_info.push(format!(
799 "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>",
800 message,
801 ));
802 }
803
804 // Render unstable items. But don't render "rustc_private" crates (internal compiler crates).
805 // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere.
806 if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item
807 .stability(cx.tcx())
808 .as_ref()
809 .filter(|stab| stab.feature != sym::rustc_private)
810 .map(|stab| (stab.level, stab.feature))
811 {
812 let mut message =
813 "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned();
814
815 let mut feature = format!("<code>{}</code>", Escape(&feature.as_str()));
816 if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) {
817 feature.push_str(&format!(
818 "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>",
819 url = url,
820 issue = issue
821 ));
822 }
823
824 message.push_str(&format!(" ({})", feature));
825
826 if let Some(unstable_reason) = reason {
827 let mut ids = cx.id_map.borrow_mut();
828 message = format!(
829 "<details><summary>{}</summary>{}</details>",
830 message,
831 MarkdownHtml(
832 &unstable_reason.as_str(),
833 &mut ids,
834 error_codes,
835 cx.shared.edition,
836 &cx.shared.playground,
837 )
838 .into_string()
839 );
840 }
841
842 extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message));
843 }
844
845 if let Some(portability) = portability(item, parent) {
846 extra_info.push(portability);
847 }
848
849 extra_info
850 }
851
852 fn render_impls(
853 cx: &Context<'_>,
854 w: &mut Buffer,
855 traits: &[&&Impl],
856 containing_item: &clean::Item,
857 ) {
858 let mut impls = traits
859 .iter()
860 .map(|i| {
861 let did = i.trait_did_full(cx.cache()).unwrap();
862 let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
863 let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() };
864 render_impl(
865 &mut buffer,
866 cx,
867 i,
868 containing_item,
869 assoc_link,
870 RenderMode::Normal,
871 containing_item.stable_since(cx.tcx()).as_deref(),
872 containing_item.const_stable_since(cx.tcx()).as_deref(),
873 true,
874 None,
875 false,
876 true,
877 &[],
878 );
879 buffer.into_inner()
880 })
881 .collect::<Vec<_>>();
882 impls.sort();
883 w.write_str(&impls.join(""));
884 }
885
886 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String {
887 use crate::formats::item_type::ItemType::*;
888
889 let name = it.name.as_ref().unwrap();
890 let ty = match it.type_() {
891 Typedef | AssocType => AssocType,
892 s => s,
893 };
894
895 let anchor = format!("#{}.{}", ty, name);
896 match link {
897 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
898 AssocItemLink::Anchor(None) => anchor,
899 AssocItemLink::GotoSource(did, _) => {
900 href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
901 }
902 }
903 }
904
905 fn assoc_const(
906 w: &mut Buffer,
907 it: &clean::Item,
908 ty: &clean::Type,
909 _default: Option<&String>,
910 link: AssocItemLink<'_>,
911 extra: &str,
912 cx: &Context<'_>,
913 ) {
914 write!(
915 w,
916 "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}",
917 extra,
918 it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()),
919 naive_assoc_href(it, link, cx.cache()),
920 it.name.as_ref().unwrap(),
921 ty.print(cx.cache())
922 );
923 }
924
925 fn assoc_type(
926 w: &mut Buffer,
927 it: &clean::Item,
928 bounds: &[clean::GenericBound],
929 default: Option<&clean::Type>,
930 link: AssocItemLink<'_>,
931 extra: &str,
932 cache: &Cache,
933 ) {
934 write!(
935 w,
936 "{}type <a href=\"{}\" class=\"type\">{}</a>",
937 extra,
938 naive_assoc_href(it, link, cache),
939 it.name.as_ref().unwrap()
940 );
941 if !bounds.is_empty() {
942 write!(w, ": {}", print_generic_bounds(bounds, cache))
943 }
944 if let Some(default) = default {
945 write!(w, " = {}", default.print(cache))
946 }
947 }
948
949 fn render_stability_since_raw(
950 w: &mut Buffer,
951 ver: Option<&str>,
952 const_ver: Option<&str>,
953 containing_ver: Option<&str>,
954 containing_const_ver: Option<&str>,
955 ) {
956 let ver = ver.filter(|inner| !inner.is_empty());
957 let const_ver = const_ver.filter(|inner| !inner.is_empty());
958
959 match (ver, const_ver) {
960 (Some(v), Some(cv)) if const_ver != containing_const_ver => {
961 write!(
962 w,
963 "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>",
964 v, cv
965 );
966 }
967 (Some(v), _) if ver != containing_ver => {
968 write!(
969 w,
970 "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>",
971 v
972 );
973 }
974 _ => {}
975 }
976 }
977
978 fn render_assoc_item(
979 w: &mut Buffer,
980 item: &clean::Item,
981 link: AssocItemLink<'_>,
982 parent: ItemType,
983 cx: &Context<'_>,
984 ) {
985 fn method(
986 w: &mut Buffer,
987 meth: &clean::Item,
988 header: hir::FnHeader,
989 g: &clean::Generics,
990 d: &clean::FnDecl,
991 link: AssocItemLink<'_>,
992 parent: ItemType,
993 cx: &Context<'_>,
994 ) {
995 let name = meth.name.as_ref().unwrap();
996 let anchor = format!("#{}.{}", meth.type_(), name);
997 let href = match link {
998 AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
999 AssocItemLink::Anchor(None) => anchor,
1000 AssocItemLink::GotoSource(did, provided_methods) => {
1001 // We're creating a link from an impl-item to the corresponding
1002 // trait-item and need to map the anchored type accordingly.
1003 let ty = if provided_methods.contains(&name) {
1004 ItemType::Method
1005 } else {
1006 ItemType::TyMethod
1007 };
1008
1009 href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
1010 }
1011 };
1012 let mut header_len = format!(
1013 "{}{}{}{}{}{:#}fn {}{:#}",
1014 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
1015 header.constness.print_with_space(),
1016 header.asyncness.print_with_space(),
1017 header.unsafety.print_with_space(),
1018 print_default_space(meth.is_default()),
1019 print_abi_with_space(header.abi),
1020 name,
1021 g.print(cx.cache())
1022 )
1023 .len();
1024 let (indent, end_newline) = if parent == ItemType::Trait {
1025 header_len += 4;
1026 (4, false)
1027 } else {
1028 (0, true)
1029 };
1030 render_attributes(w, meth, false);
1031 write!(
1032 w,
1033 "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
1034 {generics}{decl}{spotlight}{where_clause}",
1035 if parent == ItemType::Trait { " " } else { "" },
1036 meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()),
1037 header.constness.print_with_space(),
1038 header.asyncness.print_with_space(),
1039 header.unsafety.print_with_space(),
1040 print_default_space(meth.is_default()),
1041 print_abi_with_space(header.abi),
1042 href = href,
1043 name = name,
1044 generics = g.print(cx.cache()),
1045 decl = Function { decl: d, header_len, indent, asyncness: header.asyncness }
1046 .print(cx.cache()),
1047 spotlight = spotlight_decl(&d, cx.cache()),
1048 where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache())
1049 )
1050 }
1051 match *item.kind {
1052 clean::StrippedItem(..) => {}
1053 clean::TyMethodItem(ref m) => {
1054 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1055 }
1056 clean::MethodItem(ref m, _) => {
1057 method(w, item, m.header, &m.generics, &m.decl, link, parent, cx)
1058 }
1059 clean::AssocConstItem(ref ty, ref default) => assoc_const(
1060 w,
1061 item,
1062 ty,
1063 default.as_ref(),
1064 link,
1065 if parent == ItemType::Trait { " " } else { "" },
1066 cx,
1067 ),
1068 clean::AssocTypeItem(ref bounds, ref default) => assoc_type(
1069 w,
1070 item,
1071 bounds,
1072 default.as_ref(),
1073 link,
1074 if parent == ItemType::Trait { " " } else { "" },
1075 cx.cache(),
1076 ),
1077 _ => panic!("render_assoc_item called on non-associated-item"),
1078 }
1079 }
1080
1081 const ALLOWED_ATTRIBUTES: &[Symbol] = &[
1082 sym::export_name,
1083 sym::lang,
1084 sym::link_section,
1085 sym::must_use,
1086 sym::no_mangle,
1087 sym::repr,
1088 sym::non_exhaustive,
1089 ];
1090
1091 // The `top` parameter is used when generating the item declaration to ensure it doesn't have a
1092 // left padding. For example:
1093 //
1094 // #[foo] <----- "top" attribute
1095 // struct Foo {
1096 // #[bar] <---- not "top" attribute
1097 // bar: usize,
1098 // }
1099 fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) {
1100 let attrs = it
1101 .attrs
1102 .other_attrs
1103 .iter()
1104 .filter_map(|attr| {
1105 if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
1106 Some(pprust::attribute_to_string(&attr))
1107 } else {
1108 None
1109 }
1110 })
1111 .join("\n");
1112
1113 if !attrs.is_empty() {
1114 write!(
1115 w,
1116 "<span class=\"docblock attributes{}\">{}</span>",
1117 if top { " top-attr" } else { "" },
1118 &attrs
1119 );
1120 }
1121 }
1122
1123 #[derive(Copy, Clone)]
1124 enum AssocItemLink<'a> {
1125 Anchor(Option<&'a str>),
1126 GotoSource(DefId, &'a FxHashSet<Symbol>),
1127 }
1128
1129 impl<'a> AssocItemLink<'a> {
1130 fn anchor(&self, id: &'a str) -> Self {
1131 match *self {
1132 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)),
1133 ref other => *other,
1134 }
1135 }
1136 }
1137
1138 fn render_assoc_items(
1139 w: &mut Buffer,
1140 cx: &Context<'_>,
1141 containing_item: &clean::Item,
1142 it: DefId,
1143 what: AssocItemRender<'_>,
1144 ) {
1145 info!("Documenting associated items of {:?}", containing_item.name);
1146 let v = match cx.cache.impls.get(&it) {
1147 Some(v) => v,
1148 None => return,
1149 };
1150 let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none());
1151 if !non_trait.is_empty() {
1152 let render_mode = match what {
1153 AssocItemRender::All => {
1154 w.write_str(
1155 "<h2 id=\"implementations\" class=\"small-section-header\">\
1156 Implementations<a href=\"#implementations\" class=\"anchor\"></a>\
1157 </h2>",
1158 );
1159 RenderMode::Normal
1160 }
1161 AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
1162 let id = cx.derive_id(small_url_encode(format!(
1163 "deref-methods-{:#}",
1164 type_.print(cx.cache())
1165 )));
1166 debug!("Adding {} to deref id map", type_.print(cx.cache()));
1167 cx.deref_id_map
1168 .borrow_mut()
1169 .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone());
1170 write!(
1171 w,
1172 "<h2 id=\"{id}\" class=\"small-section-header\">\
1173 Methods from {trait_}&lt;Target = {type_}&gt;\
1174 <a href=\"#{id}\" class=\"anchor\"></a>\
1175 </h2>",
1176 id = id,
1177 trait_ = trait_.print(cx.cache()),
1178 type_ = type_.print(cx.cache()),
1179 );
1180 RenderMode::ForDeref { mut_: deref_mut_ }
1181 }
1182 };
1183 for i in &non_trait {
1184 render_impl(
1185 w,
1186 cx,
1187 i,
1188 containing_item,
1189 AssocItemLink::Anchor(None),
1190 render_mode,
1191 containing_item.stable_since(cx.tcx()).as_deref(),
1192 containing_item.const_stable_since(cx.tcx()).as_deref(),
1193 true,
1194 None,
1195 false,
1196 true,
1197 &[],
1198 );
1199 }
1200 }
1201 if !traits.is_empty() {
1202 let deref_impl = traits
1203 .iter()
1204 .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did);
1205 if let Some(impl_) = deref_impl {
1206 let has_deref_mut = traits.iter().any(|t| {
1207 t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did
1208 });
1209 render_deref_methods(w, cx, impl_, containing_item, has_deref_mut);
1210 }
1211
1212 // If we were already one level into rendering deref methods, we don't want to render
1213 // anything after recursing into any further deref methods above.
1214 if let AssocItemRender::DerefFor { .. } = what {
1215 return;
1216 }
1217
1218 let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1219 traits.iter().partition(|t| t.inner_impl().synthetic);
1220 let (blanket_impl, concrete): (Vec<&&Impl>, _) =
1221 concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
1222
1223 let mut impls = Buffer::empty_from(&w);
1224 render_impls(cx, &mut impls, &concrete, containing_item);
1225 let impls = impls.into_inner();
1226 if !impls.is_empty() {
1227 write!(
1228 w,
1229 "<h2 id=\"trait-implementations\" class=\"small-section-header\">\
1230 Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\
1231 </h2>\
1232 <div id=\"trait-implementations-list\">{}</div>",
1233 impls
1234 );
1235 }
1236
1237 if !synthetic.is_empty() {
1238 w.write_str(
1239 "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\
1240 Auto Trait Implementations\
1241 <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\
1242 </h2>\
1243 <div id=\"synthetic-implementations-list\">",
1244 );
1245 render_impls(cx, w, &synthetic, containing_item);
1246 w.write_str("</div>");
1247 }
1248
1249 if !blanket_impl.is_empty() {
1250 w.write_str(
1251 "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\
1252 Blanket Implementations\
1253 <a href=\"#blanket-implementations\" class=\"anchor\"></a>\
1254 </h2>\
1255 <div id=\"blanket-implementations-list\">",
1256 );
1257 render_impls(cx, w, &blanket_impl, containing_item);
1258 w.write_str("</div>");
1259 }
1260 }
1261 }
1262
1263 fn render_deref_methods(
1264 w: &mut Buffer,
1265 cx: &Context<'_>,
1266 impl_: &Impl,
1267 container_item: &clean::Item,
1268 deref_mut: bool,
1269 ) {
1270 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1271 let (target, real_target) = impl_
1272 .inner_impl()
1273 .items
1274 .iter()
1275 .find_map(|item| match *item.kind {
1276 clean::TypedefItem(ref t, true) => Some(match *t {
1277 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1278 _ => (&t.type_, &t.type_),
1279 }),
1280 _ => None,
1281 })
1282 .expect("Expected associated type binding");
1283 debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target);
1284 let what =
1285 AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
1286 if let Some(did) = target.def_id_full(cx.cache()) {
1287 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1288 // `impl Deref<Target = S> for S`
1289 if did == type_did {
1290 // Avoid infinite cycles
1291 return;
1292 }
1293 }
1294 render_assoc_items(w, cx, container_item, did, what);
1295 } else {
1296 if let Some(prim) = target.primitive_type() {
1297 if let Some(&did) = cx.cache.primitive_locations.get(&prim) {
1298 render_assoc_items(w, cx, container_item, did, what);
1299 }
1300 }
1301 }
1302 }
1303
1304 fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool {
1305 let self_type_opt = match *item.kind {
1306 clean::MethodItem(ref method, _) => method.decl.self_type(),
1307 clean::TyMethodItem(ref method) => method.decl.self_type(),
1308 _ => None,
1309 };
1310
1311 if let Some(self_ty) = self_type_opt {
1312 let (by_mut_ref, by_box, by_value) = match self_ty {
1313 SelfTy::SelfBorrowed(_, mutability)
1314 | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
1315 (mutability == Mutability::Mut, false, false)
1316 }
1317 SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
1318 (false, Some(did) == cache.owned_box_did, false)
1319 }
1320 SelfTy::SelfValue => (false, false, true),
1321 _ => (false, false, false),
1322 };
1323
1324 (deref_mut_ || !by_mut_ref) && !by_box && !by_value
1325 } else {
1326 false
1327 }
1328 }
1329
1330 fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String {
1331 let mut out = Buffer::html();
1332 let mut trait_ = String::new();
1333
1334 if let Some(did) = decl.output.def_id_full(cache) {
1335 if let Some(impls) = cache.impls.get(&did) {
1336 for i in impls {
1337 let impl_ = i.inner_impl();
1338 if impl_.trait_.def_id().map_or(false, |d| {
1339 cache.traits.get(&d).map(|t| t.is_spotlight).unwrap_or(false)
1340 }) {
1341 if out.is_empty() {
1342 write!(
1343 &mut out,
1344 "<h3 class=\"notable\">Notable traits for {}</h3>\
1345 <code class=\"content\">",
1346 impl_.for_.print(cache)
1347 );
1348 trait_.push_str(&impl_.for_.print(cache).to_string());
1349 }
1350
1351 //use the "where" class here to make it small
1352 write!(
1353 &mut out,
1354 "<span class=\"where fmt-newline\">{}</span>",
1355 impl_.print(cache, false)
1356 );
1357 let t_did = impl_.trait_.def_id_full(cache).unwrap();
1358 for it in &impl_.items {
1359 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1360 out.push_str("<span class=\"where fmt-newline\"> ");
1361 assoc_type(
1362 &mut out,
1363 it,
1364 &[],
1365 Some(&tydef.type_),
1366 AssocItemLink::GotoSource(t_did, &FxHashSet::default()),
1367 "",
1368 cache,
1369 );
1370 out.push_str(";</span>");
1371 }
1372 }
1373 }
1374 }
1375 }
1376 }
1377
1378 if !out.is_empty() {
1379 out.insert_str(
1380 0,
1381 "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\
1382 <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">",
1383 );
1384 out.push_str("</code></span></div></span></span>");
1385 }
1386
1387 out.into_inner()
1388 }
1389
1390 fn render_impl(
1391 w: &mut Buffer,
1392 cx: &Context<'_>,
1393 i: &Impl,
1394 parent: &clean::Item,
1395 link: AssocItemLink<'_>,
1396 render_mode: RenderMode,
1397 outer_version: Option<&str>,
1398 outer_const_version: Option<&str>,
1399 show_def_docs: bool,
1400 use_absolute: Option<bool>,
1401 is_on_foreign_type: bool,
1402 show_default_items: bool,
1403 // This argument is used to reference same type with different paths to avoid duplication
1404 // in documentation pages for trait with automatic implementations like "Send" and "Sync".
1405 aliases: &[String],
1406 ) {
1407 let traits = &cx.cache.traits;
1408 let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]);
1409
1410 if render_mode == RenderMode::Normal {
1411 let id = cx.derive_id(match i.inner_impl().trait_ {
1412 Some(ref t) => {
1413 if is_on_foreign_type {
1414 get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache())
1415 } else {
1416 format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache()))))
1417 }
1418 }
1419 None => "impl".to_string(),
1420 });
1421 let aliases = if aliases.is_empty() {
1422 String::new()
1423 } else {
1424 format!(" aliases=\"{}\"", aliases.join(","))
1425 };
1426 if let Some(use_absolute) = use_absolute {
1427 write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
1428 write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute));
1429 if show_def_docs {
1430 for it in &i.inner_impl().items {
1431 if let clean::TypedefItem(ref tydef, _) = *it.kind {
1432 w.write_str("<span class=\"where fmt-newline\"> ");
1433 assoc_type(
1434 w,
1435 it,
1436 &[],
1437 Some(&tydef.type_),
1438 AssocItemLink::Anchor(None),
1439 "",
1440 cx.cache(),
1441 );
1442 w.write_str(";</span>");
1443 }
1444 }
1445 }
1446 w.write_str("</code>");
1447 } else {
1448 write!(
1449 w,
1450 "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
1451 id,
1452 aliases,
1453 i.inner_impl().print(cx.cache(), false)
1454 );
1455 }
1456 write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
1457 render_stability_since_raw(
1458 w,
1459 i.impl_item.stable_since(cx.tcx()).as_deref(),
1460 i.impl_item.const_stable_since(cx.tcx()).as_deref(),
1461 outer_version,
1462 outer_const_version,
1463 );
1464 write_srclink(cx, &i.impl_item, w);
1465 w.write_str("</h3>");
1466
1467 if trait_.is_some() {
1468 if let Some(portability) = portability(&i.impl_item, Some(parent)) {
1469 write!(w, "<div class=\"item-info\">{}</div>", portability);
1470 }
1471 }
1472
1473 if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
1474 let mut ids = cx.id_map.borrow_mut();
1475 write!(
1476 w,
1477 "<div class=\"docblock\">{}</div>",
1478 Markdown(
1479 &*dox,
1480 &i.impl_item.links(&cx.cache),
1481 &mut ids,
1482 cx.shared.codes,
1483 cx.shared.edition,
1484 &cx.shared.playground
1485 )
1486 .into_string()
1487 );
1488 }
1489 }
1490
1491 fn doc_impl_item(
1492 w: &mut Buffer,
1493 cx: &Context<'_>,
1494 item: &clean::Item,
1495 parent: &clean::Item,
1496 link: AssocItemLink<'_>,
1497 render_mode: RenderMode,
1498 is_default_item: bool,
1499 outer_version: Option<&str>,
1500 outer_const_version: Option<&str>,
1501 trait_: Option<&clean::Trait>,
1502 show_def_docs: bool,
1503 ) {
1504 let item_type = item.type_();
1505 let name = item.name.as_ref().unwrap();
1506
1507 let render_method_item = match render_mode {
1508 RenderMode::Normal => true,
1509 RenderMode::ForDeref { mut_: deref_mut_ } => {
1510 should_render_item(&item, deref_mut_, &cx.cache)
1511 }
1512 };
1513
1514 let (is_hidden, extra_class) =
1515 if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias())
1516 && !is_default_item
1517 {
1518 (false, "")
1519 } else {
1520 (true, " hidden")
1521 };
1522 match *item.kind {
1523 clean::MethodItem(..) | clean::TyMethodItem(_) => {
1524 // Only render when the method is not static or we allow static methods
1525 if render_method_item {
1526 let id = cx.derive_id(format!("{}.{}", item_type, name));
1527 write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class);
1528 w.write_str("<code>");
1529 render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx);
1530 w.write_str("</code>");
1531 render_stability_since_raw(
1532 w,
1533 item.stable_since(cx.tcx()).as_deref(),
1534 item.const_stable_since(cx.tcx()).as_deref(),
1535 outer_version,
1536 outer_const_version,
1537 );
1538 write_srclink(cx, item, w);
1539 w.write_str("</h4>");
1540 }
1541 }
1542 clean::TypedefItem(ref tydef, _) => {
1543 let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name));
1544 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1545 assoc_type(
1546 w,
1547 item,
1548 &Vec::new(),
1549 Some(&tydef.type_),
1550 link.anchor(&id),
1551 "",
1552 cx.cache(),
1553 );
1554 w.write_str("</code></h4>");
1555 }
1556 clean::AssocConstItem(ref ty, ref default) => {
1557 let id = cx.derive_id(format!("{}.{}", item_type, name));
1558 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1559 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx);
1560 w.write_str("</code>");
1561 render_stability_since_raw(
1562 w,
1563 item.stable_since(cx.tcx()).as_deref(),
1564 item.const_stable_since(cx.tcx()).as_deref(),
1565 outer_version,
1566 outer_const_version,
1567 );
1568 write_srclink(cx, item, w);
1569 w.write_str("</h4>");
1570 }
1571 clean::AssocTypeItem(ref bounds, ref default) => {
1572 let id = cx.derive_id(format!("{}.{}", item_type, name));
1573 write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class);
1574 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache());
1575 w.write_str("</code></h4>");
1576 }
1577 clean::StrippedItem(..) => return,
1578 _ => panic!("can't make docs for trait item with name {:?}", item.name),
1579 }
1580
1581 if render_method_item {
1582 if !is_default_item {
1583 if let Some(t) = trait_ {
1584 // The trait item may have been stripped so we might not
1585 // find any documentation or stability for it.
1586 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1587 // We need the stability of the item from the trait
1588 // because impls can't have a stability.
1589 if item.doc_value().is_some() {
1590 document_item_info(w, cx, it, is_hidden, Some(parent));
1591 document_full(w, item, cx, "", is_hidden);
1592 } else {
1593 // In case the item isn't documented,
1594 // provide short documentation from the trait.
1595 document_short(
1596 w,
1597 it,
1598 cx,
1599 link,
1600 "",
1601 is_hidden,
1602 Some(parent),
1603 show_def_docs,
1604 );
1605 }
1606 }
1607 } else {
1608 document_item_info(w, cx, item, is_hidden, Some(parent));
1609 if show_def_docs {
1610 document_full(w, item, cx, "", is_hidden);
1611 }
1612 }
1613 } else {
1614 document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs);
1615 }
1616 }
1617 }
1618
1619 w.write_str("<div class=\"impl-items\">");
1620 for trait_item in &i.inner_impl().items {
1621 doc_impl_item(
1622 w,
1623 cx,
1624 trait_item,
1625 if trait_.is_some() { &i.impl_item } else { parent },
1626 link,
1627 render_mode,
1628 false,
1629 outer_version,
1630 outer_const_version,
1631 trait_.map(|t| &t.trait_),
1632 show_def_docs,
1633 );
1634 }
1635
1636 fn render_default_items(
1637 w: &mut Buffer,
1638 cx: &Context<'_>,
1639 t: &clean::Trait,
1640 i: &clean::Impl,
1641 parent: &clean::Item,
1642 render_mode: RenderMode,
1643 outer_version: Option<&str>,
1644 outer_const_version: Option<&str>,
1645 show_def_docs: bool,
1646 ) {
1647 for trait_item in &t.items {
1648 let n = trait_item.name;
1649 if i.items.iter().any(|m| m.name == n) {
1650 continue;
1651 }
1652 let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap();
1653 let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
1654
1655 doc_impl_item(
1656 w,
1657 cx,
1658 trait_item,
1659 parent,
1660 assoc_link,
1661 render_mode,
1662 true,
1663 outer_version,
1664 outer_const_version,
1665 None,
1666 show_def_docs,
1667 );
1668 }
1669 }
1670
1671 // If we've implemented a trait, then also emit documentation for all
1672 // default items which weren't overridden in the implementation block.
1673 // We don't emit documentation for default items if they appear in the
1674 // Implementations on Foreign Types or Implementors sections.
1675 if show_default_items {
1676 if let Some(t) = trait_ {
1677 render_default_items(
1678 w,
1679 cx,
1680 &t.trait_,
1681 &i.inner_impl(),
1682 &i.impl_item,
1683 render_mode,
1684 outer_version,
1685 outer_const_version,
1686 show_def_docs,
1687 );
1688 }
1689 }
1690 w.write_str("</div>");
1691 }
1692
1693 fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
1694 let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 };
1695
1696 if it.is_struct()
1697 || it.is_trait()
1698 || it.is_primitive()
1699 || it.is_union()
1700 || it.is_enum()
1701 || it.is_mod()
1702 || it.is_typedef()
1703 {
1704 write!(
1705 buffer,
1706 "<p class=\"location\">{}{}</p>",
1707 match *it.kind {
1708 clean::StructItem(..) => "Struct ",
1709 clean::TraitItem(..) => "Trait ",
1710 clean::PrimitiveItem(..) => "Primitive Type ",
1711 clean::UnionItem(..) => "Union ",
1712 clean::EnumItem(..) => "Enum ",
1713 clean::TypedefItem(..) => "Type Definition ",
1714 clean::ForeignTypeItem => "Foreign Type ",
1715 clean::ModuleItem(..) =>
1716 if it.is_crate() {
1717 "Crate "
1718 } else {
1719 "Module "
1720 },
1721 _ => "",
1722 },
1723 it.name.as_ref().unwrap()
1724 );
1725 }
1726
1727 if it.is_crate() {
1728 if let Some(ref version) = cx.cache.crate_version {
1729 write!(
1730 buffer,
1731 "<div class=\"block version\">\
1732 <p>Version {}</p>\
1733 </div>",
1734 Escape(version)
1735 );
1736 }
1737 }
1738
1739 buffer.write_str("<div class=\"sidebar-elems\">");
1740 if it.is_crate() {
1741 write!(
1742 buffer,
1743 "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>",
1744 it.name.as_ref().expect("crates always have a name")
1745 );
1746 }
1747 match *it.kind {
1748 clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s),
1749 clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t),
1750 clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it),
1751 clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u),
1752 clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e),
1753 clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it),
1754 clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items),
1755 clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it),
1756 _ => (),
1757 }
1758
1759 // The sidebar is designed to display sibling functions, modules and
1760 // other miscellaneous information. since there are lots of sibling
1761 // items (and that causes quadratic growth in large modules),
1762 // we refactor common parts into a shared JavaScript file per module.
1763 // still, we don't move everything into JS because we want to preserve
1764 // as much HTML as possible in order to allow non-JS-enabled browsers
1765 // to navigate the documentation (though slightly inefficiently).
1766
1767 buffer.write_str("<p class=\"location\">");
1768 for (i, name) in cx.current.iter().take(parentlen).enumerate() {
1769 if i > 0 {
1770 buffer.write_str("::<wbr>");
1771 }
1772 write!(
1773 buffer,
1774 "<a href=\"{}index.html\">{}</a>",
1775 &cx.root_path()[..(cx.current.len() - i - 1) * 3],
1776 *name
1777 );
1778 }
1779 buffer.write_str("</p>");
1780
1781 // Sidebar refers to the enclosing module, not this module.
1782 let relpath = if it.is_mod() { "../" } else { "" };
1783 write!(
1784 buffer,
1785 "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\
1786 </div>",
1787 name = it.name.unwrap_or(kw::Empty),
1788 ty = it.type_(),
1789 path = relpath
1790 );
1791 if parentlen == 0 {
1792 // There is no sidebar-items.js beyond the crate root path
1793 // FIXME maybe dynamic crate loading can be merged here
1794 } else {
1795 write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath);
1796 }
1797 // Closes sidebar-elems div.
1798 buffer.write_str("</div>");
1799 }
1800
1801 fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
1802 if used_links.insert(url.clone()) {
1803 return url;
1804 }
1805 let mut add = 1;
1806 while !used_links.insert(format!("{}-{}", url, add)) {
1807 add += 1;
1808 }
1809 format!("{}-{}", url, add)
1810 }
1811
1812 fn get_methods(
1813 i: &clean::Impl,
1814 for_deref: bool,
1815 used_links: &mut FxHashSet<String>,
1816 deref_mut: bool,
1817 cache: &Cache,
1818 ) -> Vec<String> {
1819 i.items
1820 .iter()
1821 .filter_map(|item| match item.name {
1822 Some(ref name) if !name.is_empty() && item.is_method() => {
1823 if !for_deref || should_render_item(item, deref_mut, cache) {
1824 Some(format!(
1825 "<a href=\"#{}\">{}</a>",
1826 get_next_url(used_links, format!("method.{}", name)),
1827 name
1828 ))
1829 } else {
1830 None
1831 }
1832 }
1833 _ => None,
1834 })
1835 .collect::<Vec<_>>()
1836 }
1837
1838 // The point is to url encode any potential character from a type with genericity.
1839 fn small_url_encode(s: String) -> String {
1840 let mut st = String::new();
1841 let mut last_match = 0;
1842 for (idx, c) in s.char_indices() {
1843 let escaped = match c {
1844 '<' => "%3C",
1845 '>' => "%3E",
1846 ' ' => "%20",
1847 '?' => "%3F",
1848 '\'' => "%27",
1849 '&' => "%26",
1850 ',' => "%2C",
1851 ':' => "%3A",
1852 ';' => "%3B",
1853 '[' => "%5B",
1854 ']' => "%5D",
1855 '"' => "%22",
1856 _ => continue,
1857 };
1858
1859 st += &s[last_match..idx];
1860 st += escaped;
1861 // NOTE: we only expect single byte characters here - which is fine as long as we
1862 // only match single byte characters
1863 last_match = idx + 1;
1864 }
1865
1866 if last_match != 0 {
1867 st += &s[last_match..];
1868 st
1869 } else {
1870 s
1871 }
1872 }
1873
1874 fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) {
1875 if let Some(v) = cx.cache.impls.get(&it.def_id) {
1876 let mut used_links = FxHashSet::default();
1877
1878 {
1879 let used_links_bor = &mut used_links;
1880 let mut ret = v
1881 .iter()
1882 .filter(|i| i.inner_impl().trait_.is_none())
1883 .flat_map(move |i| {
1884 get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache)
1885 })
1886 .collect::<Vec<_>>();
1887 if !ret.is_empty() {
1888 // We want links' order to be reproducible so we don't use unstable sort.
1889 ret.sort();
1890
1891 out.push_str(
1892 "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\
1893 <div class=\"sidebar-links\">",
1894 );
1895 for line in ret {
1896 out.push_str(&line);
1897 }
1898 out.push_str("</div>");
1899 }
1900 }
1901
1902 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
1903 if let Some(impl_) = v
1904 .iter()
1905 .filter(|i| i.inner_impl().trait_.is_some())
1906 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did)
1907 {
1908 sidebar_deref_methods(cx, out, impl_, v);
1909 }
1910 let format_impls = |impls: Vec<&Impl>| {
1911 let mut links = FxHashSet::default();
1912
1913 let mut ret = impls
1914 .iter()
1915 .filter_map(|it| {
1916 if let Some(ref i) = it.inner_impl().trait_ {
1917 let i_display = format!("{:#}", i.print(cx.cache()));
1918 let out = Escape(&i_display);
1919 let encoded = small_url_encode(format!("{:#}", i.print(cx.cache())));
1920 let generated = format!(
1921 "<a href=\"#impl-{}\">{}{}</a>",
1922 encoded,
1923 if it.inner_impl().negative_polarity { "!" } else { "" },
1924 out
1925 );
1926 if links.insert(generated.clone()) { Some(generated) } else { None }
1927 } else {
1928 None
1929 }
1930 })
1931 .collect::<Vec<String>>();
1932 ret.sort();
1933 ret
1934 };
1935
1936 let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| {
1937 out.push_str("<div class=\"sidebar-links\">");
1938 for link in links {
1939 out.push_str(&link);
1940 }
1941 out.push_str("</div>");
1942 };
1943
1944 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
1945 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
1946 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
1947 .into_iter()
1948 .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
1949
1950 let concrete_format = format_impls(concrete);
1951 let synthetic_format = format_impls(synthetic);
1952 let blanket_format = format_impls(blanket_impl);
1953
1954 if !concrete_format.is_empty() {
1955 out.push_str(
1956 "<a class=\"sidebar-title\" href=\"#trait-implementations\">\
1957 Trait Implementations</a>",
1958 );
1959 write_sidebar_links(out, concrete_format);
1960 }
1961
1962 if !synthetic_format.is_empty() {
1963 out.push_str(
1964 "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\
1965 Auto Trait Implementations</a>",
1966 );
1967 write_sidebar_links(out, synthetic_format);
1968 }
1969
1970 if !blanket_format.is_empty() {
1971 out.push_str(
1972 "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\
1973 Blanket Implementations</a>",
1974 );
1975 write_sidebar_links(out, blanket_format);
1976 }
1977 }
1978 }
1979 }
1980
1981 fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) {
1982 let c = cx.cache();
1983
1984 debug!("found Deref: {:?}", impl_);
1985 if let Some((target, real_target)) =
1986 impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
1987 clean::TypedefItem(ref t, true) => Some(match *t {
1988 clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_),
1989 _ => (&t.type_, &t.type_),
1990 }),
1991 _ => None,
1992 })
1993 {
1994 debug!("found target, real_target: {:?} {:?}", target, real_target);
1995 if let Some(did) = target.def_id_full(cx.cache()) {
1996 if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) {
1997 // `impl Deref<Target = S> for S`
1998 if did == type_did {
1999 // Avoid infinite cycles
2000 return;
2001 }
2002 }
2003 }
2004 let deref_mut = v
2005 .iter()
2006 .filter(|i| i.inner_impl().trait_.is_some())
2007 .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did);
2008 let inner_impl = target
2009 .def_id_full(cx.cache())
2010 .or_else(|| {
2011 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
2012 })
2013 .and_then(|did| c.impls.get(&did));
2014 if let Some(impls) = inner_impl {
2015 debug!("found inner_impl: {:?}", impls);
2016 let mut used_links = FxHashSet::default();
2017 let mut ret = impls
2018 .iter()
2019 .filter(|i| i.inner_impl().trait_.is_none())
2020 .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c))
2021 .collect::<Vec<_>>();
2022 if !ret.is_empty() {
2023 let deref_id_map = cx.deref_id_map.borrow();
2024 let id = deref_id_map
2025 .get(&real_target.def_id_full(cx.cache()).unwrap())
2026 .expect("Deref section without derived id");
2027 write!(
2028 out,
2029 "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}&lt;Target={}&gt;</a>",
2030 id,
2031 Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))),
2032 Escape(&format!("{:#}", real_target.print(c))),
2033 );
2034 // We want links' order to be reproducible so we don't use unstable sort.
2035 ret.sort();
2036 out.push_str("<div class=\"sidebar-links\">");
2037 for link in ret {
2038 out.push_str(&link);
2039 }
2040 out.push_str("</div>");
2041 }
2042 }
2043
2044 // Recurse into any further impls that might exist for `target`
2045 if let Some(target_did) = target.def_id_full(cx.cache()) {
2046 if let Some(target_impls) = c.impls.get(&target_did) {
2047 if let Some(target_deref_impl) = target_impls
2048 .iter()
2049 .filter(|i| i.inner_impl().trait_.is_some())
2050 .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did)
2051 {
2052 sidebar_deref_methods(cx, out, target_deref_impl, target_impls);
2053 }
2054 }
2055 }
2056 }
2057 }
2058
2059 fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) {
2060 let mut sidebar = Buffer::new();
2061 let fields = get_struct_fields_name(&s.fields);
2062
2063 if !fields.is_empty() {
2064 if let CtorKind::Fictive = s.struct_type {
2065 sidebar.push_str(
2066 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2067 <div class=\"sidebar-links\">",
2068 );
2069
2070 for field in fields {
2071 sidebar.push_str(&field);
2072 }
2073
2074 sidebar.push_str("</div>");
2075 }
2076 }
2077
2078 sidebar_assoc_items(cx, &mut sidebar, it);
2079
2080 if !sidebar.is_empty() {
2081 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2082 }
2083 }
2084
2085 fn get_id_for_impl_on_foreign_type(
2086 for_: &clean::Type,
2087 trait_: &clean::Type,
2088 cache: &Cache,
2089 ) -> String {
2090 small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache)))
2091 }
2092
2093 fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> {
2094 match *item.kind {
2095 clean::ItemKind::ImplItem(ref i) => {
2096 if let Some(ref trait_) = i.trait_ {
2097 Some((
2098 format!("{:#}", i.for_.print(cache)),
2099 get_id_for_impl_on_foreign_type(&i.for_, trait_, cache),
2100 ))
2101 } else {
2102 None
2103 }
2104 }
2105 _ => None,
2106 }
2107 }
2108
2109 fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) {
2110 buf.write_str("<div class=\"block items\">");
2111
2112 fn print_sidebar_section(
2113 out: &mut Buffer,
2114 items: &[clean::Item],
2115 before: &str,
2116 filter: impl Fn(&clean::Item) -> bool,
2117 write: impl Fn(&mut Buffer, &Symbol),
2118 after: &str,
2119 ) {
2120 let mut items = items
2121 .iter()
2122 .filter_map(|m| match m.name {
2123 Some(ref name) if filter(m) => Some(name),
2124 _ => None,
2125 })
2126 .collect::<Vec<_>>();
2127
2128 if !items.is_empty() {
2129 items.sort();
2130 out.push_str(before);
2131 for item in items.into_iter() {
2132 write(out, item);
2133 }
2134 out.push_str(after);
2135 }
2136 }
2137
2138 print_sidebar_section(
2139 buf,
2140 &t.items,
2141 "<a class=\"sidebar-title\" href=\"#associated-types\">\
2142 Associated Types</a><div class=\"sidebar-links\">",
2143 |m| m.is_associated_type(),
2144 |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym),
2145 "</div>",
2146 );
2147
2148 print_sidebar_section(
2149 buf,
2150 &t.items,
2151 "<a class=\"sidebar-title\" href=\"#associated-const\">\
2152 Associated Constants</a><div class=\"sidebar-links\">",
2153 |m| m.is_associated_const(),
2154 |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym),
2155 "</div>",
2156 );
2157
2158 print_sidebar_section(
2159 buf,
2160 &t.items,
2161 "<a class=\"sidebar-title\" href=\"#required-methods\">\
2162 Required Methods</a><div class=\"sidebar-links\">",
2163 |m| m.is_ty_method(),
2164 |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym),
2165 "</div>",
2166 );
2167
2168 print_sidebar_section(
2169 buf,
2170 &t.items,
2171 "<a class=\"sidebar-title\" href=\"#provided-methods\">\
2172 Provided Methods</a><div class=\"sidebar-links\">",
2173 |m| m.is_method(),
2174 |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym),
2175 "</div>",
2176 );
2177
2178 if let Some(implementors) = cx.cache.implementors.get(&it.def_id) {
2179 let mut res = implementors
2180 .iter()
2181 .filter(|i| {
2182 i.inner_impl()
2183 .for_
2184 .def_id_full(cx.cache())
2185 .map_or(false, |d| !cx.cache.paths.contains_key(&d))
2186 })
2187 .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache()))
2188 .collect::<Vec<_>>();
2189
2190 if !res.is_empty() {
2191 res.sort();
2192 buf.push_str(
2193 "<a class=\"sidebar-title\" href=\"#foreign-impls\">\
2194 Implementations on Foreign Types</a>\
2195 <div class=\"sidebar-links\">",
2196 );
2197 for (name, id) in res.into_iter() {
2198 write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name));
2199 }
2200 buf.push_str("</div>");
2201 }
2202 }
2203
2204 sidebar_assoc_items(cx, buf, it);
2205
2206 buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
2207 if t.is_auto {
2208 buf.push_str(
2209 "<a class=\"sidebar-title\" \
2210 href=\"#synthetic-implementors\">Auto Implementors</a>",
2211 );
2212 }
2213
2214 buf.push_str("</div>")
2215 }
2216
2217 fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2218 let mut sidebar = Buffer::new();
2219 sidebar_assoc_items(cx, &mut sidebar, it);
2220
2221 if !sidebar.is_empty() {
2222 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2223 }
2224 }
2225
2226 fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2227 let mut sidebar = Buffer::new();
2228 sidebar_assoc_items(cx, &mut sidebar, it);
2229
2230 if !sidebar.is_empty() {
2231 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2232 }
2233 }
2234
2235 fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> {
2236 let mut fields = fields
2237 .iter()
2238 .filter(|f| matches!(*f.kind, clean::StructFieldItem(..)))
2239 .filter_map(|f| {
2240 f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name))
2241 })
2242 .collect::<Vec<_>>();
2243 fields.sort();
2244 fields
2245 }
2246
2247 fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) {
2248 let mut sidebar = Buffer::new();
2249 let fields = get_struct_fields_name(&u.fields);
2250
2251 if !fields.is_empty() {
2252 sidebar.push_str(
2253 "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
2254 <div class=\"sidebar-links\">",
2255 );
2256
2257 for field in fields {
2258 sidebar.push_str(&field);
2259 }
2260
2261 sidebar.push_str("</div>");
2262 }
2263
2264 sidebar_assoc_items(cx, &mut sidebar, it);
2265
2266 if !sidebar.is_empty() {
2267 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2268 }
2269 }
2270
2271 fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) {
2272 let mut sidebar = Buffer::new();
2273
2274 let mut variants = e
2275 .variants
2276 .iter()
2277 .filter_map(|v| match v.name {
2278 Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)),
2279 _ => None,
2280 })
2281 .collect::<Vec<_>>();
2282 if !variants.is_empty() {
2283 variants.sort_unstable();
2284 sidebar.push_str(&format!(
2285 "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
2286 <div class=\"sidebar-links\">{}</div>",
2287 variants.join(""),
2288 ));
2289 }
2290
2291 sidebar_assoc_items(cx, &mut sidebar, it);
2292
2293 if !sidebar.is_empty() {
2294 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2295 }
2296 }
2297
2298 fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) {
2299 match *ty {
2300 ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"),
2301 ItemType::Module => ("modules", "Modules"),
2302 ItemType::Struct => ("structs", "Structs"),
2303 ItemType::Union => ("unions", "Unions"),
2304 ItemType::Enum => ("enums", "Enums"),
2305 ItemType::Function => ("functions", "Functions"),
2306 ItemType::Typedef => ("types", "Type Definitions"),
2307 ItemType::Static => ("statics", "Statics"),
2308 ItemType::Constant => ("constants", "Constants"),
2309 ItemType::Trait => ("traits", "Traits"),
2310 ItemType::Impl => ("impls", "Implementations"),
2311 ItemType::TyMethod => ("tymethods", "Type Methods"),
2312 ItemType::Method => ("methods", "Methods"),
2313 ItemType::StructField => ("fields", "Struct Fields"),
2314 ItemType::Variant => ("variants", "Variants"),
2315 ItemType::Macro => ("macros", "Macros"),
2316 ItemType::Primitive => ("primitives", "Primitive Types"),
2317 ItemType::AssocType => ("associated-types", "Associated Types"),
2318 ItemType::AssocConst => ("associated-consts", "Associated Constants"),
2319 ItemType::ForeignType => ("foreign-types", "Foreign Types"),
2320 ItemType::Keyword => ("keywords", "Keywords"),
2321 ItemType::OpaqueTy => ("opaque-types", "Opaque Types"),
2322 ItemType::ProcAttribute => ("attributes", "Attribute Macros"),
2323 ItemType::ProcDerive => ("derives", "Derive Macros"),
2324 ItemType::TraitAlias => ("trait-aliases", "Trait aliases"),
2325 }
2326 }
2327
2328 fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) {
2329 let mut sidebar = String::new();
2330
2331 if items.iter().any(|it| {
2332 it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped())
2333 }) {
2334 sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>");
2335 }
2336
2337 // ordering taken from item_module, reorder, where it prioritized elements in a certain order
2338 // to print its headings
2339 for &myty in &[
2340 ItemType::Primitive,
2341 ItemType::Module,
2342 ItemType::Macro,
2343 ItemType::Struct,
2344 ItemType::Enum,
2345 ItemType::Constant,
2346 ItemType::Static,
2347 ItemType::Trait,
2348 ItemType::Function,
2349 ItemType::Typedef,
2350 ItemType::Union,
2351 ItemType::Impl,
2352 ItemType::TyMethod,
2353 ItemType::Method,
2354 ItemType::StructField,
2355 ItemType::Variant,
2356 ItemType::AssocType,
2357 ItemType::AssocConst,
2358 ItemType::ForeignType,
2359 ItemType::Keyword,
2360 ] {
2361 if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
2362 let (short, name) = item_ty_to_strs(&myty);
2363 sidebar.push_str(&format!(
2364 "<li><a href=\"#{id}\">{name}</a></li>",
2365 id = short,
2366 name = name
2367 ));
2368 }
2369 }
2370
2371 if !sidebar.is_empty() {
2372 write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar);
2373 }
2374 }
2375
2376 fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) {
2377 let mut sidebar = Buffer::new();
2378 sidebar_assoc_items(cx, &mut sidebar, it);
2379
2380 if !sidebar.is_empty() {
2381 write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner());
2382 }
2383 }
2384
2385 crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang";
2386
2387 /// Returns a list of all paths used in the type.
2388 /// This is used to help deduplicate imported impls
2389 /// for reexported types. If any of the contained
2390 /// types are re-exported, we don't use the corresponding
2391 /// entry from the js file, as inlining will have already
2392 /// picked up the impl
2393 fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
2394 let mut out = Vec::new();
2395 let mut visited = FxHashSet::default();
2396 let mut work = VecDeque::new();
2397
2398 work.push_back(first_ty);
2399
2400 while let Some(ty) = work.pop_front() {
2401 if !visited.insert(ty.clone()) {
2402 continue;
2403 }
2404
2405 match ty {
2406 clean::Type::ResolvedPath { did, .. } => {
2407 let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone());
2408 let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern);
2409
2410 if let Some(path) = fqp {
2411 out.push(path.join("::"));
2412 }
2413 }
2414 clean::Type::Tuple(tys) => {
2415 work.extend(tys.into_iter());
2416 }
2417 clean::Type::Slice(ty) => {
2418 work.push_back(*ty);
2419 }
2420 clean::Type::Array(ty, _) => {
2421 work.push_back(*ty);
2422 }
2423 clean::Type::RawPointer(_, ty) => {
2424 work.push_back(*ty);
2425 }
2426 clean::Type::BorrowedRef { type_, .. } => {
2427 work.push_back(*type_);
2428 }
2429 clean::Type::QPath { self_type, trait_, .. } => {
2430 work.push_back(*self_type);
2431 work.push_back(*trait_);
2432 }
2433 _ => {}
2434 }
2435 }
2436 out
2437 }