]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/print_item.rs
Make some clean::Trait fields computation on demand
[rust.git] / src / librustdoc / html / render / print_item.rs
1 use clean::AttributesExt;
2
3 use std::cmp::Ordering;
4 use std::fmt;
5 use std::rc::Rc;
6
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
8 use rustc_hir as hir;
9 use rustc_hir::def::CtorKind;
10 use rustc_hir::def_id::DefId;
11 use rustc_middle::middle::stability;
12 use rustc_middle::span_bug;
13 use rustc_middle::ty::layout::LayoutError;
14 use rustc_middle::ty::{Adt, TyCtxt};
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::{kw, sym, Symbol};
17 use rustc_target::abi::{Layout, Primitive, TagEncoding, Variants};
18
19 use super::{
20     collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_section,
21     notable_traits_decl, render_assoc_item, render_assoc_items, render_attributes_in_code,
22     render_attributes_in_pre, render_impl, render_stability_since_raw, write_srclink,
23     AssocItemLink, Context, ImplRenderingParameters,
24 };
25 use crate::clean;
26 use crate::config::ModuleSorting;
27 use crate::formats::item_type::ItemType;
28 use crate::formats::{AssocItemRender, Impl, RenderMode};
29 use crate::html::escape::Escape;
30 use crate::html::format::{
31     join_with_double_colon, print_abi_with_space, print_constness_with_space, print_where_clause,
32     Buffer, Ending, PrintWithSpace,
33 };
34 use crate::html::highlight;
35 use crate::html::layout::Page;
36 use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
37 use crate::html::url_parts_builder::UrlPartsBuilder;
38
39 use askama::Template;
40
41 const ITEM_TABLE_OPEN: &str = "<div class=\"item-table\">";
42 const ITEM_TABLE_CLOSE: &str = "</div>";
43 const ITEM_TABLE_ROW_OPEN: &str = "<div class=\"item-row\">";
44 const ITEM_TABLE_ROW_CLOSE: &str = "</div>";
45
46 // A component in a `use` path, like `string` in std::string::ToString
47 struct PathComponent {
48     path: String,
49     name: Symbol,
50 }
51
52 #[derive(Template)]
53 #[template(path = "print_item.html")]
54 struct ItemVars<'a> {
55     page: &'a Page<'a>,
56     static_root_path: &'a str,
57     typ: &'a str,
58     name: &'a str,
59     item_type: &'a str,
60     path_components: Vec<PathComponent>,
61     stability_since_raw: &'a str,
62     src_href: Option<&'a str>,
63 }
64
65 /// Calls `print_where_clause` and returns `true` if a `where` clause was generated.
66 fn print_where_clause_and_check<'a, 'tcx: 'a>(
67     buffer: &mut Buffer,
68     gens: &'a clean::Generics,
69     cx: &'a Context<'tcx>,
70 ) -> bool {
71     let len_before = buffer.len();
72     write!(buffer, "{}", print_where_clause(gens, cx, 0, Ending::Newline));
73     len_before != buffer.len()
74 }
75
76 pub(super) fn print_item(
77     cx: &mut Context<'_>,
78     item: &clean::Item,
79     buf: &mut Buffer,
80     page: &Page<'_>,
81 ) {
82     debug_assert!(!item.is_stripped());
83     let typ = match *item.kind {
84         clean::ModuleItem(_) => {
85             if item.is_crate() {
86                 "Crate "
87             } else {
88                 "Module "
89             }
90         }
91         clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
92         clean::TraitItem(..) => "Trait ",
93         clean::StructItem(..) => "Struct ",
94         clean::UnionItem(..) => "Union ",
95         clean::EnumItem(..) => "Enum ",
96         clean::TypedefItem(..) => "Type Definition ",
97         clean::MacroItem(..) => "Macro ",
98         clean::ProcMacroItem(ref mac) => match mac.kind {
99             MacroKind::Bang => "Macro ",
100             MacroKind::Attr => "Attribute Macro ",
101             MacroKind::Derive => "Derive Macro ",
102         },
103         clean::PrimitiveItem(..) => "Primitive Type ",
104         clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
105         clean::ConstantItem(..) => "Constant ",
106         clean::ForeignTypeItem => "Foreign Type ",
107         clean::KeywordItem(..) => "Keyword ",
108         clean::OpaqueTyItem(..) => "Opaque Type ",
109         clean::TraitAliasItem(..) => "Trait Alias ",
110         _ => {
111             // We don't generate pages for any other type.
112             unreachable!();
113         }
114     };
115     let mut stability_since_raw = Buffer::new();
116     render_stability_since_raw(
117         &mut stability_since_raw,
118         item.stable_since(cx.tcx()),
119         item.const_stability(cx.tcx()),
120         None,
121         None,
122     );
123     let stability_since_raw: String = stability_since_raw.into_inner();
124
125     // Write source tag
126     //
127     // When this item is part of a `crate use` in a downstream crate, the
128     // source link in the downstream documentation will actually come back to
129     // this page, and this link will be auto-clicked. The `id` attribute is
130     // used to find the link to auto-click.
131     let src_href =
132         if cx.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
133
134     let path_components = if item.is_primitive() || item.is_keyword() {
135         vec![]
136     } else {
137         let cur = &cx.current;
138         let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
139         cur.iter()
140             .enumerate()
141             .take(amt)
142             .map(|(i, component)| PathComponent {
143                 path: "../".repeat(cur.len() - i - 1),
144                 name: *component,
145             })
146             .collect()
147     };
148
149     let item_vars = ItemVars {
150         page,
151         static_root_path: page.get_static_root_path(),
152         typ,
153         name: item.name.as_ref().unwrap().as_str(),
154         item_type: &item.type_().to_string(),
155         path_components,
156         stability_since_raw: &stability_since_raw,
157         src_href: src_href.as_deref(),
158     };
159
160     item_vars.render_into(buf).unwrap();
161
162     match &*item.kind {
163         clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items),
164         clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => {
165             item_function(buf, cx, item, f)
166         }
167         clean::TraitItem(ref t) => item_trait(buf, cx, item, t),
168         clean::StructItem(ref s) => item_struct(buf, cx, item, s),
169         clean::UnionItem(ref s) => item_union(buf, cx, item, s),
170         clean::EnumItem(ref e) => item_enum(buf, cx, item, e),
171         clean::TypedefItem(ref t) => item_typedef(buf, cx, item, t),
172         clean::MacroItem(ref m) => item_macro(buf, cx, item, m),
173         clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m),
174         clean::PrimitiveItem(_) => item_primitive(buf, cx, item),
175         clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i),
176         clean::ConstantItem(ref c) => item_constant(buf, cx, item, c),
177         clean::ForeignTypeItem => item_foreign_type(buf, cx, item),
178         clean::KeywordItem(_) => item_keyword(buf, cx, item),
179         clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e),
180         clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta),
181         _ => {
182             // We don't generate pages for any other type.
183             unreachable!();
184         }
185     }
186 }
187
188 /// For large structs, enums, unions, etc, determine whether to hide their fields
189 fn should_hide_fields(n_fields: usize) -> bool {
190     n_fields > 12
191 }
192
193 fn toggle_open(w: &mut Buffer, text: impl fmt::Display) {
194     write!(
195         w,
196         "<details class=\"rustdoc-toggle type-contents-toggle\">\
197             <summary class=\"hideme\">\
198                 <span>Show {}</span>\
199             </summary>",
200         text
201     );
202 }
203
204 fn toggle_close(w: &mut Buffer) {
205     w.write_str("</details>");
206 }
207
208 fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: &[clean::Item]) {
209     document(w, cx, item, None, HeadingOffset::H2);
210
211     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>();
212
213     // the order of item types in the listing
214     fn reorder(ty: ItemType) -> u8 {
215         match ty {
216             ItemType::ExternCrate => 0,
217             ItemType::Import => 1,
218             ItemType::Primitive => 2,
219             ItemType::Module => 3,
220             ItemType::Macro => 4,
221             ItemType::Struct => 5,
222             ItemType::Enum => 6,
223             ItemType::Constant => 7,
224             ItemType::Static => 8,
225             ItemType::Trait => 9,
226             ItemType::Function => 10,
227             ItemType::Typedef => 12,
228             ItemType::Union => 13,
229             _ => 14 + ty as u8,
230         }
231     }
232
233     fn cmp(
234         i1: &clean::Item,
235         i2: &clean::Item,
236         idx1: usize,
237         idx2: usize,
238         tcx: TyCtxt<'_>,
239     ) -> Ordering {
240         let ty1 = i1.type_();
241         let ty2 = i2.type_();
242         if item_ty_to_section(ty1) != item_ty_to_section(ty2)
243             || (ty1 != ty2 && (ty1 == ItemType::ExternCrate || ty2 == ItemType::ExternCrate))
244         {
245             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2));
246         }
247         let s1 = i1.stability(tcx).as_ref().map(|s| s.level);
248         let s2 = i2.stability(tcx).as_ref().map(|s| s.level);
249         if let (Some(a), Some(b)) = (s1, s2) {
250             match (a.is_stable(), b.is_stable()) {
251                 (true, true) | (false, false) => {}
252                 (false, true) => return Ordering::Less,
253                 (true, false) => return Ordering::Greater,
254             }
255         }
256         let lhs = i1.name.unwrap_or(kw::Empty);
257         let rhs = i2.name.unwrap_or(kw::Empty);
258         compare_names(lhs.as_str(), rhs.as_str())
259     }
260
261     match cx.shared.module_sorting {
262         ModuleSorting::Alphabetical => {
263             indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx()));
264         }
265         ModuleSorting::DeclarationOrder => {}
266     }
267     // This call is to remove re-export duplicates in cases such as:
268     //
269     // ```
270     // pub(crate) mod foo {
271     //     pub(crate) mod bar {
272     //         pub(crate) trait Double { fn foo(); }
273     //     }
274     // }
275     //
276     // pub(crate) use foo::bar::*;
277     // pub(crate) use foo::*;
278     // ```
279     //
280     // `Double` will appear twice in the generated docs.
281     //
282     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
283     // can be identical even if the elements are different (mostly in imports).
284     // So in case this is an import, we keep everything by adding a "unique id"
285     // (which is the position in the vector).
286     indices.dedup_by_key(|i| {
287         (
288             items[*i].item_id,
289             if items[*i].name.is_some() { Some(full_path(cx, &items[*i])) } else { None },
290             items[*i].type_(),
291             if items[*i].is_import() { *i } else { 0 },
292         )
293     });
294
295     debug!("{:?}", indices);
296     let mut last_section = None;
297
298     for &idx in &indices {
299         let myitem = &items[idx];
300         if myitem.is_stripped() {
301             continue;
302         }
303
304         let my_section = item_ty_to_section(myitem.type_());
305         if Some(my_section) != last_section {
306             if last_section.is_some() {
307                 w.write_str(ITEM_TABLE_CLOSE);
308             }
309             last_section = Some(my_section);
310             write!(
311                 w,
312                 "<h2 id=\"{id}\" class=\"small-section-header\">\
313                     <a href=\"#{id}\">{name}</a>\
314                  </h2>\n{}",
315                 ITEM_TABLE_OPEN,
316                 id = cx.derive_id(my_section.id().to_owned()),
317                 name = my_section.name(),
318             );
319         }
320
321         match *myitem.kind {
322             clean::ExternCrateItem { ref src } => {
323                 use crate::html::format::anchor;
324
325                 w.write_str(ITEM_TABLE_ROW_OPEN);
326                 match *src {
327                     Some(src) => write!(
328                         w,
329                         "<div class=\"item-left\"><code>{}extern crate {} as {};",
330                         myitem.visibility.print_with_space(myitem.item_id, cx),
331                         anchor(myitem.item_id.expect_def_id(), src, cx),
332                         myitem.name.unwrap(),
333                     ),
334                     None => write!(
335                         w,
336                         "<div class=\"item-left\"><code>{}extern crate {};",
337                         myitem.visibility.print_with_space(myitem.item_id, cx),
338                         anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx),
339                     ),
340                 }
341                 w.write_str("</code></div>");
342                 w.write_str(ITEM_TABLE_ROW_CLOSE);
343             }
344
345             clean::ImportItem(ref import) => {
346                 let (stab, stab_tags) = if let Some(import_def_id) = import.source.did {
347                     let ast_attrs = cx.tcx().get_attrs_unchecked(import_def_id);
348                     let import_attrs = Box::new(clean::Attributes::from_ast(ast_attrs, None));
349
350                     // Just need an item with the correct def_id and attrs
351                     let import_item = clean::Item {
352                         item_id: import_def_id.into(),
353                         attrs: import_attrs,
354                         cfg: ast_attrs.cfg(cx.tcx(), &cx.cache().hidden_cfg),
355                         ..myitem.clone()
356                     };
357
358                     let stab = import_item.stability_class(cx.tcx());
359                     let stab_tags = Some(extra_info_tags(&import_item, item, cx.tcx()));
360                     (stab, stab_tags)
361                 } else {
362                     (None, None)
363                 };
364
365                 let add = if stab.is_some() { " " } else { "" };
366
367                 w.write_str(ITEM_TABLE_ROW_OPEN);
368                 let id = match import.kind {
369                     clean::ImportKind::Simple(s) => {
370                         format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s)))
371                     }
372                     clean::ImportKind::Glob => String::new(),
373                 };
374                 write!(
375                     w,
376                     "<div class=\"item-left {stab}{add}import-item\"{id}>\
377                          <code>{vis}{imp}</code>\
378                      </div>\
379                      <div class=\"item-right docblock-short\">{stab_tags}</div>",
380                     stab = stab.unwrap_or_default(),
381                     vis = myitem.visibility.print_with_space(myitem.item_id, cx),
382                     imp = import.print(cx),
383                     stab_tags = stab_tags.unwrap_or_default(),
384                 );
385                 w.write_str(ITEM_TABLE_ROW_CLOSE);
386             }
387
388             _ => {
389                 if myitem.name.is_none() {
390                     continue;
391                 }
392
393                 let unsafety_flag = match *myitem.kind {
394                     clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
395                         if myitem.fn_header(cx.tcx()).unwrap().unsafety
396                             == hir::Unsafety::Unsafe =>
397                     {
398                         "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>"
399                     }
400                     _ => "",
401                 };
402
403                 let stab = myitem.stability_class(cx.tcx());
404                 let add = if stab.is_some() { " " } else { "" };
405
406                 let visibility_emoji = match myitem.visibility {
407                     clean::Visibility::Restricted(_) => {
408                         "<span title=\"Restricted Visibility\">&nbsp;🔒</span> "
409                     }
410                     _ => "",
411                 };
412
413                 let doc_value = myitem.doc_value().unwrap_or_default();
414                 w.write_str(ITEM_TABLE_ROW_OPEN);
415                 write!(
416                     w,
417                     "<div class=\"item-left {stab}{add}module-item\">\
418                             <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
419                             {visibility_emoji}\
420                             {unsafety_flag}\
421                             {stab_tags}\
422                      </div>\
423                      <div class=\"item-right docblock-short\">{docs}</div>",
424                     name = myitem.name.unwrap(),
425                     visibility_emoji = visibility_emoji,
426                     stab_tags = extra_info_tags(myitem, item, cx.tcx()),
427                     docs = MarkdownSummaryLine(&doc_value, &myitem.links(cx)).into_string(),
428                     class = myitem.type_(),
429                     add = add,
430                     stab = stab.unwrap_or_default(),
431                     unsafety_flag = unsafety_flag,
432                     href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
433                     title = [full_path(cx, myitem), myitem.type_().to_string()]
434                         .iter()
435                         .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None })
436                         .collect::<Vec<_>>()
437                         .join(" "),
438                 );
439                 w.write_str(ITEM_TABLE_ROW_CLOSE);
440             }
441         }
442     }
443
444     if last_section.is_some() {
445         w.write_str(ITEM_TABLE_CLOSE);
446     }
447 }
448
449 /// Render the stability, deprecation and portability tags that are displayed in the item's summary
450 /// at the module level.
451 fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String {
452     let mut tags = String::new();
453
454     fn tag_html(class: &str, title: &str, contents: &str) -> String {
455         format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents)
456     }
457
458     // The trailing space after each tag is to space it properly against the rest of the docs.
459     if let Some(depr) = &item.deprecation(tcx) {
460         let mut message = "Deprecated";
461         if !stability::deprecation_in_effect(depr) {
462             message = "Deprecation planned";
463         }
464         tags += &tag_html("deprecated", "", message);
465     }
466
467     // The "rustc_private" crates are permanently unstable so it makes no sense
468     // to render "unstable" everywhere.
469     if item.stability(tcx).as_ref().map(|s| s.is_unstable() && s.feature != sym::rustc_private)
470         == Some(true)
471     {
472         tags += &tag_html("unstable", "", "Experimental");
473     }
474
475     let cfg = match (&item.cfg, parent.cfg.as_ref()) {
476         (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
477         (cfg, _) => cfg.as_deref().cloned(),
478     };
479
480     debug!("Portability {:?} - {:?} = {:?}", item.cfg, parent.cfg, cfg);
481     if let Some(ref cfg) = cfg {
482         tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html());
483     }
484
485     tags
486 }
487
488 fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &clean::Function) {
489     let header = it.fn_header(cx.tcx()).expect("printing a function which isn't a function");
490     let constness = print_constness_with_space(&header.constness, it.const_stability(cx.tcx()));
491     let unsafety = header.unsafety.print_with_space();
492     let abi = print_abi_with_space(header.abi).to_string();
493     let asyncness = header.asyncness.print_with_space();
494     let visibility = it.visibility.print_with_space(it.item_id, cx).to_string();
495     let name = it.name.unwrap();
496
497     let generics_len = format!("{:#}", f.generics.print(cx)).len();
498     let header_len = "fn ".len()
499         + visibility.len()
500         + constness.len()
501         + asyncness.len()
502         + unsafety.len()
503         + abi.len()
504         + name.as_str().len()
505         + generics_len;
506
507     wrap_into_docblock(w, |w| {
508         wrap_item(w, "fn", |w| {
509             render_attributes_in_pre(w, it, "");
510             w.reserve(header_len);
511             write!(
512                 w,
513                 "{vis}{constness}{asyncness}{unsafety}{abi}fn \
514                  {name}{generics}{decl}{notable_traits}{where_clause}",
515                 vis = visibility,
516                 constness = constness,
517                 asyncness = asyncness,
518                 unsafety = unsafety,
519                 abi = abi,
520                 name = name,
521                 generics = f.generics.print(cx),
522                 where_clause = print_where_clause(&f.generics, cx, 0, Ending::Newline),
523                 decl = f.decl.full_print(header_len, 0, header.asyncness, cx),
524                 notable_traits = notable_traits_decl(&f.decl, cx),
525             );
526         });
527     });
528     document(w, cx, it, None, HeadingOffset::H2)
529 }
530
531 fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Trait) {
532     let bounds = bounds(&t.bounds, false, cx);
533     let required_types = t.items.iter().filter(|m| m.is_ty_associated_type()).collect::<Vec<_>>();
534     let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
535     let required_consts = t.items.iter().filter(|m| m.is_ty_associated_const()).collect::<Vec<_>>();
536     let provided_consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
537     let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
538     let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
539     let count_types = required_types.len() + provided_types.len();
540     let count_consts = required_consts.len() + provided_consts.len();
541     let count_methods = required_methods.len() + provided_methods.len();
542
543     // Output the trait definition
544     wrap_into_docblock(w, |w| {
545         wrap_item(w, "trait", |w| {
546             render_attributes_in_pre(w, it, "");
547             write!(
548                 w,
549                 "{}{}{}trait {}{}{}",
550                 it.visibility.print_with_space(it.item_id, cx),
551                 t.unsafety(cx.tcx()).print_with_space(),
552                 if t.is_auto(cx.tcx()) { "auto " } else { "" },
553                 it.name.unwrap(),
554                 t.generics.print(cx),
555                 bounds
556             );
557
558             if !t.generics.where_predicates.is_empty() {
559                 write!(w, "{}", print_where_clause(&t.generics, cx, 0, Ending::Newline));
560             } else {
561                 w.write_str(" ");
562             }
563
564             if t.items.is_empty() {
565                 w.write_str("{ }");
566             } else {
567                 // FIXME: we should be using a derived_id for the Anchors here
568                 w.write_str("{\n");
569                 let mut toggle = false;
570
571                 // If there are too many associated types, hide _everything_
572                 if should_hide_fields(count_types) {
573                     toggle = true;
574                     toggle_open(
575                         w,
576                         format_args!(
577                             "{} associated items",
578                             count_types + count_consts + count_methods
579                         ),
580                     );
581                 }
582                 for types in [&required_types, &provided_types] {
583                     for t in types {
584                         render_assoc_item(
585                             w,
586                             t,
587                             AssocItemLink::Anchor(None),
588                             ItemType::Trait,
589                             cx,
590                             RenderMode::Normal,
591                         );
592                         w.write_str(";\n");
593                     }
594                 }
595                 // If there are too many associated constants, hide everything after them
596                 // We also do this if the types + consts is large because otherwise we could
597                 // render a bunch of types and _then_ a bunch of consts just because both were
598                 // _just_ under the limit
599                 if !toggle && should_hide_fields(count_types + count_consts) {
600                     toggle = true;
601                     toggle_open(
602                         w,
603                         format_args!(
604                             "{} associated constant{} and {} method{}",
605                             count_consts,
606                             pluralize(count_consts),
607                             count_methods,
608                             pluralize(count_methods),
609                         ),
610                     );
611                 }
612                 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
613                     w.write_str("\n");
614                 }
615                 for consts in [&required_consts, &provided_consts] {
616                     for c in consts {
617                         render_assoc_item(
618                             w,
619                             c,
620                             AssocItemLink::Anchor(None),
621                             ItemType::Trait,
622                             cx,
623                             RenderMode::Normal,
624                         );
625                         w.write_str(";\n");
626                     }
627                 }
628                 if !toggle && should_hide_fields(count_methods) {
629                     toggle = true;
630                     toggle_open(w, format_args!("{} methods", count_methods));
631                 }
632                 if count_consts != 0 && count_methods != 0 {
633                     w.write_str("\n");
634                 }
635                 for (pos, m) in required_methods.iter().enumerate() {
636                     render_assoc_item(
637                         w,
638                         m,
639                         AssocItemLink::Anchor(None),
640                         ItemType::Trait,
641                         cx,
642                         RenderMode::Normal,
643                     );
644                     w.write_str(";\n");
645
646                     if pos < required_methods.len() - 1 {
647                         w.write_str("<span class=\"item-spacer\"></span>");
648                     }
649                 }
650                 if !required_methods.is_empty() && !provided_methods.is_empty() {
651                     w.write_str("\n");
652                 }
653                 for (pos, m) in provided_methods.iter().enumerate() {
654                     render_assoc_item(
655                         w,
656                         m,
657                         AssocItemLink::Anchor(None),
658                         ItemType::Trait,
659                         cx,
660                         RenderMode::Normal,
661                     );
662                     match *m.kind {
663                         clean::MethodItem(ref inner, _)
664                             if !inner.generics.where_predicates.is_empty() =>
665                         {
666                             w.write_str(",\n    { ... }\n");
667                         }
668                         _ => {
669                             w.write_str(" { ... }\n");
670                         }
671                     }
672
673                     if pos < provided_methods.len() - 1 {
674                         w.write_str("<span class=\"item-spacer\"></span>");
675                     }
676                 }
677                 if toggle {
678                     toggle_close(w);
679                 }
680                 w.write_str("}");
681             }
682         });
683     });
684
685     // Trait documentation
686     document(w, cx, it, None, HeadingOffset::H2);
687
688     fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) {
689         write!(
690             w,
691             "<h2 id=\"{0}\" class=\"small-section-header\">\
692                 {1}<a href=\"#{0}\" class=\"anchor\"></a>\
693              </h2>{2}",
694             id, title, extra_content
695         )
696     }
697
698     fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
699         let name = m.name.unwrap();
700         info!("Documenting {} on {:?}", name, t.name);
701         let item_type = m.type_();
702         let id = cx.derive_id(format!("{}.{}", item_type, name));
703         let mut content = Buffer::empty_from(w);
704         document(&mut content, cx, m, Some(t), HeadingOffset::H5);
705         let toggled = !content.is_empty();
706         if toggled {
707             write!(w, "<details class=\"rustdoc-toggle\" open><summary>");
708         }
709         write!(w, "<div id=\"{}\" class=\"method has-srclink\">", id);
710         write!(w, "<div class=\"rightside\">");
711
712         let has_stability = render_stability_since(w, m, t, cx.tcx());
713         if has_stability {
714             w.write_str(" · ");
715         }
716         write_srclink(cx, m, w);
717         write!(w, "</div>");
718         write!(w, "<h4 class=\"code-header\">");
719         render_assoc_item(
720             w,
721             m,
722             AssocItemLink::Anchor(Some(&id)),
723             ItemType::Impl,
724             cx,
725             RenderMode::Normal,
726         );
727         w.write_str("</h4>");
728         w.write_str("</div>");
729         if toggled {
730             write!(w, "</summary>");
731             w.push_buffer(content);
732             write!(w, "</details>");
733         }
734     }
735
736     if !required_types.is_empty() {
737         write_small_section_header(
738             w,
739             "required-associated-types",
740             "Required Associated Types",
741             "<div class=\"methods\">",
742         );
743         for t in required_types {
744             trait_item(w, cx, t, it);
745         }
746         w.write_str("</div>");
747     }
748     if !provided_types.is_empty() {
749         write_small_section_header(
750             w,
751             "provided-associated-types",
752             "Provided Associated Types",
753             "<div class=\"methods\">",
754         );
755         for t in provided_types {
756             trait_item(w, cx, t, it);
757         }
758         w.write_str("</div>");
759     }
760
761     if !required_consts.is_empty() {
762         write_small_section_header(
763             w,
764             "required-associated-consts",
765             "Required Associated Constants",
766             "<div class=\"methods\">",
767         );
768         for t in required_consts {
769             trait_item(w, cx, t, it);
770         }
771         w.write_str("</div>");
772     }
773     if !provided_consts.is_empty() {
774         write_small_section_header(
775             w,
776             "provided-associated-consts",
777             "Provided Associated Constants",
778             "<div class=\"methods\">",
779         );
780         for t in provided_consts {
781             trait_item(w, cx, t, it);
782         }
783         w.write_str("</div>");
784     }
785
786     // Output the documentation for each function individually
787     if !required_methods.is_empty() {
788         write_small_section_header(
789             w,
790             "required-methods",
791             "Required Methods",
792             "<div class=\"methods\">",
793         );
794         for m in required_methods {
795             trait_item(w, cx, m, it);
796         }
797         w.write_str("</div>");
798     }
799     if !provided_methods.is_empty() {
800         write_small_section_header(
801             w,
802             "provided-methods",
803             "Provided Methods",
804             "<div class=\"methods\">",
805         );
806         for m in provided_methods {
807             trait_item(w, cx, m, it);
808         }
809         w.write_str("</div>");
810     }
811
812     // If there are methods directly on this trait object, render them here.
813     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All);
814
815     let cloned_shared = Rc::clone(&cx.shared);
816     let cache = &cloned_shared.cache;
817     let mut extern_crates = FxHashSet::default();
818     if let Some(implementors) = cache.implementors.get(&it.item_id.expect_def_id()) {
819         // The DefId is for the first Type found with that name. The bool is
820         // if any Types with the same name but different DefId have been found.
821         let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
822         for implementor in implementors {
823             if let Some(did) = implementor.inner_impl().for_.without_borrowed_ref().def_id(cache) &&
824                 !did.is_local() {
825                 extern_crates.insert(did.krate);
826             }
827             match implementor.inner_impl().for_.without_borrowed_ref() {
828                 clean::Type::Path { ref path } if !path.is_assoc_ty() => {
829                     let did = path.def_id();
830                     let &mut (prev_did, ref mut has_duplicates) =
831                         implementor_dups.entry(path.last()).or_insert((did, false));
832                     if prev_did != did {
833                         *has_duplicates = true;
834                     }
835                 }
836                 _ => {}
837             }
838         }
839
840         let (local, foreign) =
841             implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
842
843         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
844             local.iter().partition(|i| i.inner_impl().kind.is_auto());
845
846         synthetic.sort_by(|a, b| compare_impl(a, b, cx));
847         concrete.sort_by(|a, b| compare_impl(a, b, cx));
848
849         if !foreign.is_empty() {
850             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
851
852             for implementor in foreign {
853                 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
854                 let assoc_link =
855                     AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
856                 render_impl(
857                     w,
858                     cx,
859                     implementor,
860                     it,
861                     assoc_link,
862                     RenderMode::Normal,
863                     None,
864                     &[],
865                     ImplRenderingParameters {
866                         show_def_docs: false,
867                         show_default_items: false,
868                         show_non_assoc_items: true,
869                         toggle_open_by_default: false,
870                     },
871                 );
872             }
873         }
874
875         write_small_section_header(
876             w,
877             "implementors",
878             "Implementors",
879             "<div class=\"item-list\" id=\"implementors-list\">",
880         );
881         for implementor in concrete {
882             render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
883         }
884         w.write_str("</div>");
885
886         if t.is_auto(cx.tcx()) {
887             write_small_section_header(
888                 w,
889                 "synthetic-implementors",
890                 "Auto implementors",
891                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
892             );
893             for implementor in synthetic {
894                 render_implementor(
895                     cx,
896                     implementor,
897                     it,
898                     w,
899                     &implementor_dups,
900                     &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
901                 );
902             }
903             w.write_str("</div>");
904         }
905     } else {
906         // even without any implementations to write in, we still want the heading and list, so the
907         // implementors javascript file pulled in below has somewhere to write the impls into
908         write_small_section_header(
909             w,
910             "implementors",
911             "Implementors",
912             "<div class=\"item-list\" id=\"implementors-list\"></div>",
913         );
914
915         if t.is_auto(cx.tcx()) {
916             write_small_section_header(
917                 w,
918                 "synthetic-implementors",
919                 "Auto implementors",
920                 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
921             );
922         }
923     }
924
925     // Include implementors in crates that depend on the current crate.
926     //
927     // This is complicated by the way rustdoc is invoked, which is basically
928     // the same way rustc is invoked: it gets called, one at a time, for each
929     // crate. When building the rustdocs for the current crate, rustdoc can
930     // see crate metadata for its dependencies, but cannot see metadata for its
931     // dependents.
932     //
933     // To make this work, we generate a "hook" at this stage, and our
934     // dependents can "plug in" to it when they build. For simplicity's sake,
935     // it's [JSONP]: a JavaScript file with the data we need (and can parse),
936     // surrounded by a tiny wrapper that the Rust side ignores, but allows the
937     // JavaScript side to include without having to worry about Same Origin
938     // Policy. The code for *that* is in `write_shared.rs`.
939     //
940     // This is further complicated by `#[doc(inline)]`. We want all copies
941     // of an inlined trait to reference the same JS file, to address complex
942     // dependency graphs like this one (lower crates depend on higher crates):
943     //
944     // ```text
945     //  --------------------------------------------
946     //  |            crate A: trait Foo            |
947     //  --------------------------------------------
948     //      |                               |
949     //  --------------------------------    |
950     //  | crate B: impl A::Foo for Bar |    |
951     //  --------------------------------    |
952     //      |                               |
953     //  ---------------------------------------------
954     //  | crate C: #[doc(inline)] use A::Foo as Baz |
955     //  |          impl Baz for Quux                |
956     //  ---------------------------------------------
957     // ```
958     //
959     // Basically, we want `C::Baz` and `A::Foo` to show the same set of
960     // impls, which is easier if they both treat `/implementors/A/trait.Foo.js`
961     // as the Single Source of Truth.
962     //
963     // We also want the `impl Baz for Quux` to be written to
964     // `trait.Foo.js`. However, when we generate plain HTML for `C::Baz`,
965     // we're going to want to generate plain HTML for `impl Baz for Quux` too,
966     // because that'll load faster, and it's better for SEO. And we don't want
967     // the same impl to show up twice on the same page.
968     //
969     // To make this work, the implementors JS file has a structure kinda
970     // like this:
971     //
972     // ```js
973     // JSONP({
974     // "B": {"impl A::Foo for Bar"},
975     // "C": {"impl Baz for Quux"},
976     // });
977     // ```
978     //
979     // First of all, this means we can rebuild a crate, and it'll replace its own
980     // data if something changes. That is, `rustdoc` is idempotent. The other
981     // advantage is that we can list the crates that get included in the HTML,
982     // and ignore them when doing the JavaScript-based part of rendering.
983     // So C's HTML will have something like this:
984     //
985     // ```html
986     // <script type="text/javascript" src="/implementors/A/trait.Foo.js"
987     //     data-ignore-extern-crates="A,B" async></script>
988     // ```
989     //
990     // And, when the JS runs, anything in data-ignore-extern-crates is known
991     // to already be in the HTML, and will be ignored.
992     //
993     // [JSONP]: https://en.wikipedia.org/wiki/JSONP
994     let mut js_src_path: UrlPartsBuilder = std::iter::repeat("..")
995         .take(cx.current.len())
996         .chain(std::iter::once("implementors"))
997         .collect();
998     if let Some(did) = it.item_id.as_def_id() &&
999         let get_extern = { || cache.external_paths.get(&did).map(|s| s.0.clone()) } &&
1000         let Some(fqp) = cache.exact_paths.get(&did).cloned().or_else(get_extern) {
1001         js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1002         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1003     } else {
1004         js_src_path.extend(cx.current.iter().copied());
1005         js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1006     }
1007     let extern_crates = extern_crates
1008         .into_iter()
1009         .map(|cnum| cx.shared.tcx.crate_name(cnum).to_string())
1010         .collect::<Vec<_>>()
1011         .join(",");
1012     write!(
1013         w,
1014         "<script type=\"text/javascript\" src=\"{src}\" data-ignore-extern-crates=\"{extern_crates}\" async></script>",
1015         src = js_src_path.finish(),
1016     );
1017 }
1018
1019 fn item_trait_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
1020     wrap_into_docblock(w, |w| {
1021         wrap_item(w, "trait-alias", |w| {
1022             render_attributes_in_pre(w, it, "");
1023             write!(
1024                 w,
1025                 "trait {}{}{} = {};",
1026                 it.name.unwrap(),
1027                 t.generics.print(cx),
1028                 print_where_clause(&t.generics, cx, 0, Ending::Newline),
1029                 bounds(&t.bounds, true, cx)
1030             );
1031         });
1032     });
1033
1034     document(w, cx, it, None, HeadingOffset::H2);
1035
1036     // Render any items associated directly to this alias, as otherwise they
1037     // won't be visible anywhere in the docs. It would be nice to also show
1038     // associated items from the aliased type (see discussion in #32077), but
1039     // we need #14072 to make sense of the generics.
1040     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1041 }
1042
1043 fn item_opaque_ty(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
1044     wrap_into_docblock(w, |w| {
1045         wrap_item(w, "opaque", |w| {
1046             render_attributes_in_pre(w, it, "");
1047             write!(
1048                 w,
1049                 "type {}{}{where_clause} = impl {bounds};",
1050                 it.name.unwrap(),
1051                 t.generics.print(cx),
1052                 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1053                 bounds = bounds(&t.bounds, false, cx),
1054             );
1055         });
1056     });
1057
1058     document(w, cx, it, None, HeadingOffset::H2);
1059
1060     // Render any items associated directly to this alias, as otherwise they
1061     // won't be visible anywhere in the docs. It would be nice to also show
1062     // associated items from the aliased type (see discussion in #32077), but
1063     // we need #14072 to make sense of the generics.
1064     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1065 }
1066
1067 fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1068     fn write_content(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) {
1069         wrap_item(w, "typedef", |w| {
1070             render_attributes_in_pre(w, it, "");
1071             write!(w, "{}", it.visibility.print_with_space(it.item_id, cx));
1072             write!(
1073                 w,
1074                 "type {}{}{where_clause} = {type_};",
1075                 it.name.unwrap(),
1076                 t.generics.print(cx),
1077                 where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
1078                 type_ = t.type_.print(cx),
1079             );
1080         });
1081     }
1082
1083     wrap_into_docblock(w, |w| write_content(w, cx, it, t));
1084
1085     document(w, cx, it, None, HeadingOffset::H2);
1086
1087     let def_id = it.item_id.expect_def_id();
1088     // Render any items associated directly to this alias, as otherwise they
1089     // won't be visible anywhere in the docs. It would be nice to also show
1090     // associated items from the aliased type (see discussion in #32077), but
1091     // we need #14072 to make sense of the generics.
1092     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1093     document_type_layout(w, cx, def_id);
1094 }
1095
1096 fn item_union(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Union) {
1097     wrap_into_docblock(w, |w| {
1098         wrap_item(w, "union", |w| {
1099             render_attributes_in_pre(w, it, "");
1100             render_union(w, it, Some(&s.generics), &s.fields, "", cx);
1101         });
1102     });
1103
1104     document(w, cx, it, None, HeadingOffset::H2);
1105
1106     let mut fields = s
1107         .fields
1108         .iter()
1109         .filter_map(|f| match *f.kind {
1110             clean::StructFieldItem(ref ty) => Some((f, ty)),
1111             _ => None,
1112         })
1113         .peekable();
1114     if fields.peek().is_some() {
1115         write!(
1116             w,
1117             "<h2 id=\"fields\" class=\"fields small-section-header\">\
1118                    Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
1119         );
1120         for (field, ty) in fields {
1121             let name = field.name.expect("union field name");
1122             let id = format!("{}.{}", ItemType::StructField, name);
1123             write!(
1124                 w,
1125                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
1126                      <a href=\"#{id}\" class=\"anchor field\"></a>\
1127                      <code>{name}: {ty}</code>\
1128                  </span>",
1129                 id = id,
1130                 name = name,
1131                 shortty = ItemType::StructField,
1132                 ty = ty.print(cx),
1133             );
1134             if let Some(stability_class) = field.stability_class(cx.tcx()) {
1135                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
1136             }
1137             document(w, cx, field, Some(it), HeadingOffset::H3);
1138         }
1139     }
1140     let def_id = it.item_id.expect_def_id();
1141     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1142     document_type_layout(w, cx, def_id);
1143 }
1144
1145 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
1146     for (i, ty) in s.iter().enumerate() {
1147         if i > 0 {
1148             w.write_str(",&nbsp;");
1149         }
1150         match *ty.kind {
1151             clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1152             clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1153             _ => unreachable!(),
1154         }
1155     }
1156 }
1157
1158 fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::Enum) {
1159     let count_variants = e.variants().count();
1160     wrap_into_docblock(w, |w| {
1161         wrap_item(w, "enum", |w| {
1162             render_attributes_in_pre(w, it, "");
1163             write!(
1164                 w,
1165                 "{}enum {}{}",
1166                 it.visibility.print_with_space(it.item_id, cx),
1167                 it.name.unwrap(),
1168                 e.generics.print(cx),
1169             );
1170             if !print_where_clause_and_check(w, &e.generics, cx) {
1171                 // If there wasn't a `where` clause, we add a whitespace.
1172                 w.write_str(" ");
1173             }
1174
1175             let variants_stripped = e.has_stripped_entries();
1176             if count_variants == 0 && !variants_stripped {
1177                 w.write_str("{}");
1178             } else {
1179                 w.write_str("{\n");
1180                 let toggle = should_hide_fields(count_variants);
1181                 if toggle {
1182                     toggle_open(w, format_args!("{} variants", count_variants));
1183                 }
1184                 for v in e.variants() {
1185                     w.write_str("    ");
1186                     let name = v.name.unwrap();
1187                     match *v.kind {
1188                         clean::VariantItem(ref var) => match var {
1189                             clean::Variant::CLike => write!(w, "{}", name),
1190                             clean::Variant::Tuple(ref s) => {
1191                                 write!(w, "{}(", name);
1192                                 print_tuple_struct_fields(w, cx, s);
1193                                 w.write_str(")");
1194                             }
1195                             clean::Variant::Struct(ref s) => {
1196                                 render_struct(
1197                                     w,
1198                                     v,
1199                                     None,
1200                                     s.struct_type,
1201                                     &s.fields,
1202                                     "    ",
1203                                     false,
1204                                     cx,
1205                                 );
1206                             }
1207                         },
1208                         _ => unreachable!(),
1209                     }
1210                     w.write_str(",\n");
1211                 }
1212
1213                 if variants_stripped {
1214                     w.write_str("    // some variants omitted\n");
1215                 }
1216                 if toggle {
1217                     toggle_close(w);
1218                 }
1219                 w.write_str("}");
1220             }
1221         });
1222     });
1223
1224     document(w, cx, it, None, HeadingOffset::H2);
1225
1226     if count_variants != 0 {
1227         write!(
1228             w,
1229             "<h2 id=\"variants\" class=\"variants small-section-header\">\
1230                    Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1231             document_non_exhaustive_header(it)
1232         );
1233         document_non_exhaustive(w, it);
1234         for variant in e.variants() {
1235             let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1236             write!(
1237                 w,
1238                 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1239                     <a href=\"#{id}\" class=\"anchor field\"></a>\
1240                     <code>{name}",
1241                 id = id,
1242                 name = variant.name.unwrap()
1243             );
1244             if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1245                 w.write_str("(");
1246                 print_tuple_struct_fields(w, cx, s);
1247                 w.write_str(")");
1248             }
1249             w.write_str("</code>");
1250             render_stability_since(w, variant, it, cx.tcx());
1251             w.write_str("</h3>");
1252
1253             use crate::clean::Variant;
1254
1255             let heading_and_fields = match &*variant.kind {
1256                 clean::VariantItem(Variant::Struct(s)) => Some(("Fields", &s.fields)),
1257                 // Documentation on tuple variant fields is rare, so to reduce noise we only emit
1258                 // the section if at least one field is documented.
1259                 clean::VariantItem(Variant::Tuple(fields))
1260                     if fields.iter().any(|f| f.doc_value().is_some()) =>
1261                 {
1262                     Some(("Tuple Fields", fields))
1263                 }
1264                 _ => None,
1265             };
1266
1267             if let Some((heading, fields)) = heading_and_fields {
1268                 let variant_id =
1269                     cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1270                 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1271                 write!(w, "<h4>{heading}</h4>", heading = heading);
1272                 document_non_exhaustive(w, variant);
1273                 for field in fields {
1274                     match *field.kind {
1275                         clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1276                         clean::StructFieldItem(ref ty) => {
1277                             let id = cx.derive_id(format!(
1278                                 "variant.{}.field.{}",
1279                                 variant.name.unwrap(),
1280                                 field.name.unwrap()
1281                             ));
1282                             write!(
1283                                 w,
1284                                 "<div class=\"sub-variant-field\">\
1285                                  <span id=\"{id}\" class=\"variant small-section-header\">\
1286                                     <a href=\"#{id}\" class=\"anchor field\"></a>\
1287                                     <code>{f}:&nbsp;{t}</code>\
1288                                 </span>",
1289                                 id = id,
1290                                 f = field.name.unwrap(),
1291                                 t = ty.print(cx)
1292                             );
1293                             document(w, cx, field, Some(variant), HeadingOffset::H5);
1294                             write!(w, "</div>");
1295                         }
1296                         _ => unreachable!(),
1297                     }
1298                 }
1299                 w.write_str("</div>");
1300             }
1301
1302             document(w, cx, variant, Some(it), HeadingOffset::H4);
1303         }
1304     }
1305     let def_id = it.item_id.expect_def_id();
1306     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1307     document_type_layout(w, cx, def_id);
1308 }
1309
1310 fn item_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean::Macro) {
1311     wrap_into_docblock(w, |w| {
1312         highlight::render_with_highlighting(
1313             &t.source,
1314             w,
1315             Some("macro"),
1316             None,
1317             None,
1318             it.span(cx.tcx()).inner().edition(),
1319             None,
1320             None,
1321             None,
1322         );
1323     });
1324     document(w, cx, it, None, HeadingOffset::H2)
1325 }
1326
1327 fn item_proc_macro(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1328     wrap_into_docblock(w, |w| {
1329         let name = it.name.expect("proc-macros always have names");
1330         match m.kind {
1331             MacroKind::Bang => {
1332                 wrap_item(w, "macro", |w| {
1333                     write!(w, "{}!() {{ /* proc-macro */ }}", name);
1334                 });
1335             }
1336             MacroKind::Attr => {
1337                 wrap_item(w, "attr", |w| {
1338                     write!(w, "#[{}]", name);
1339                 });
1340             }
1341             MacroKind::Derive => {
1342                 wrap_item(w, "derive", |w| {
1343                     write!(w, "#[derive({})]", name);
1344                     if !m.helpers.is_empty() {
1345                         w.push_str("\n{\n");
1346                         w.push_str("    // Attributes available to this derive:\n");
1347                         for attr in &m.helpers {
1348                             writeln!(w, "    #[{}]", attr);
1349                         }
1350                         w.push_str("}\n");
1351                     }
1352                 });
1353             }
1354         }
1355     });
1356     document(w, cx, it, None, HeadingOffset::H2)
1357 }
1358
1359 fn item_primitive(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1360     document(w, cx, it, None, HeadingOffset::H2);
1361     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1362 }
1363
1364 fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
1365     wrap_into_docblock(w, |w| {
1366         wrap_item(w, "const", |w| {
1367             render_attributes_in_code(w, it);
1368
1369             write!(
1370                 w,
1371                 "{vis}const {name}: {typ}",
1372                 vis = it.visibility.print_with_space(it.item_id, cx),
1373                 name = it.name.unwrap(),
1374                 typ = c.type_.print(cx),
1375             );
1376
1377             // FIXME: The code below now prints
1378             //            ` = _; // 100i32`
1379             //        if the expression is
1380             //            `50 + 50`
1381             //        which looks just wrong.
1382             //        Should we print
1383             //            ` = 100i32;`
1384             //        instead?
1385
1386             let value = c.value(cx.tcx());
1387             let is_literal = c.is_literal(cx.tcx());
1388             let expr = c.expr(cx.tcx());
1389             if value.is_some() || is_literal {
1390                 write!(w, " = {expr};", expr = Escape(&expr));
1391             } else {
1392                 w.write_str(";");
1393             }
1394
1395             if !is_literal {
1396                 if let Some(value) = &value {
1397                     let value_lowercase = value.to_lowercase();
1398                     let expr_lowercase = expr.to_lowercase();
1399
1400                     if value_lowercase != expr_lowercase
1401                         && value_lowercase.trim_end_matches("i32") != expr_lowercase
1402                     {
1403                         write!(w, " // {value}", value = Escape(value));
1404                     }
1405                 }
1406             }
1407         });
1408     });
1409
1410     document(w, cx, it, None, HeadingOffset::H2)
1411 }
1412
1413 fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
1414     wrap_into_docblock(w, |w| {
1415         wrap_item(w, "struct", |w| {
1416             render_attributes_in_code(w, it);
1417             render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1418         });
1419     });
1420
1421     document(w, cx, it, None, HeadingOffset::H2);
1422
1423     let mut fields = s
1424         .fields
1425         .iter()
1426         .filter_map(|f| match *f.kind {
1427             clean::StructFieldItem(ref ty) => Some((f, ty)),
1428             _ => None,
1429         })
1430         .peekable();
1431     if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1432         if fields.peek().is_some() {
1433             write!(
1434                 w,
1435                 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1436                      {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1437                  </h2>",
1438                 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1439                 document_non_exhaustive_header(it)
1440             );
1441             document_non_exhaustive(w, it);
1442             for (index, (field, ty)) in fields.enumerate() {
1443                 let field_name =
1444                     field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
1445                 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1446                 write!(
1447                     w,
1448                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1449                          <a href=\"#{id}\" class=\"anchor field\"></a>\
1450                          <code>{name}: {ty}</code>\
1451                      </span>",
1452                     item_type = ItemType::StructField,
1453                     id = id,
1454                     name = field_name,
1455                     ty = ty.print(cx)
1456                 );
1457                 document(w, cx, field, Some(it), HeadingOffset::H3);
1458             }
1459         }
1460     }
1461     let def_id = it.item_id.expect_def_id();
1462     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1463     document_type_layout(w, cx, def_id);
1464 }
1465
1466 fn item_static(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
1467     wrap_into_docblock(w, |w| {
1468         wrap_item(w, "static", |w| {
1469             render_attributes_in_code(w, it);
1470             write!(
1471                 w,
1472                 "{vis}static {mutability}{name}: {typ}",
1473                 vis = it.visibility.print_with_space(it.item_id, cx),
1474                 mutability = s.mutability.print_with_space(),
1475                 name = it.name.unwrap(),
1476                 typ = s.type_.print(cx)
1477             );
1478         });
1479     });
1480     document(w, cx, it, None, HeadingOffset::H2)
1481 }
1482
1483 fn item_foreign_type(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1484     wrap_into_docblock(w, |w| {
1485         wrap_item(w, "foreigntype", |w| {
1486             w.write_str("extern {\n");
1487             render_attributes_in_code(w, it);
1488             write!(
1489                 w,
1490                 "    {}type {};\n}}",
1491                 it.visibility.print_with_space(it.item_id, cx),
1492                 it.name.unwrap(),
1493             );
1494         });
1495     });
1496
1497     document(w, cx, it, None, HeadingOffset::H2);
1498
1499     render_assoc_items(w, cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1500 }
1501
1502 fn item_keyword(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item) {
1503     document(w, cx, it, None, HeadingOffset::H2)
1504 }
1505
1506 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1507 pub(crate) fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1508     /// Takes a non-numeric and a numeric part from the given &str.
1509     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1510         let i = s.find(|c: char| c.is_ascii_digit());
1511         let (a, b) = s.split_at(i.unwrap_or(s.len()));
1512         let i = b.find(|c: char| !c.is_ascii_digit());
1513         let (b, c) = b.split_at(i.unwrap_or(b.len()));
1514         *s = c;
1515         (a, b)
1516     }
1517
1518     while !lhs.is_empty() || !rhs.is_empty() {
1519         let (la, lb) = take_parts(&mut lhs);
1520         let (ra, rb) = take_parts(&mut rhs);
1521         // First process the non-numeric part.
1522         match la.cmp(ra) {
1523             Ordering::Equal => (),
1524             x => return x,
1525         }
1526         // Then process the numeric part, if both sides have one (and they fit in a u64).
1527         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1528             match ln.cmp(&rn) {
1529                 Ordering::Equal => (),
1530                 x => return x,
1531             }
1532         }
1533         // Then process the numeric part again, but this time as strings.
1534         match lb.cmp(rb) {
1535             Ordering::Equal => (),
1536             x => return x,
1537         }
1538     }
1539
1540     Ordering::Equal
1541 }
1542
1543 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1544     let mut s = join_with_double_colon(&cx.current);
1545     s.push_str("::");
1546     s.push_str(item.name.unwrap().as_str());
1547     s
1548 }
1549
1550 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1551     match ty {
1552         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1553         _ => format!("{}.{}.html", ty, name),
1554     }
1555 }
1556
1557 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1558     let mut bounds = String::new();
1559     if !t_bounds.is_empty() {
1560         if !trait_alias {
1561             bounds.push_str(": ");
1562         }
1563         for (i, p) in t_bounds.iter().enumerate() {
1564             if i > 0 {
1565                 bounds.push_str(" + ");
1566             }
1567             bounds.push_str(&p.print(cx).to_string());
1568         }
1569     }
1570     bounds
1571 }
1572
1573 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1574 where
1575     F: FnOnce(&mut Buffer),
1576 {
1577     w.write_str("<div class=\"docblock item-decl\">");
1578     f(w);
1579     w.write_str("</div>")
1580 }
1581
1582 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1583 where
1584     F: FnOnce(&mut Buffer),
1585 {
1586     w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1587     f(w);
1588     w.write_str("</code></pre>");
1589 }
1590
1591 fn render_stability_since(
1592     w: &mut Buffer,
1593     item: &clean::Item,
1594     containing_item: &clean::Item,
1595     tcx: TyCtxt<'_>,
1596 ) -> bool {
1597     render_stability_since_raw(
1598         w,
1599         item.stable_since(tcx),
1600         item.const_stability(tcx),
1601         containing_item.stable_since(tcx),
1602         containing_item.const_stable_since(tcx),
1603     )
1604 }
1605
1606 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1607     let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1608     let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1609
1610     // lhs and rhs are formatted as HTML, which may be unnecessary
1611     compare_names(&lhss, &rhss)
1612 }
1613
1614 fn render_implementor(
1615     cx: &mut Context<'_>,
1616     implementor: &Impl,
1617     trait_: &clean::Item,
1618     w: &mut Buffer,
1619     implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1620     aliases: &[String],
1621 ) {
1622     // If there's already another implementor that has the same abridged name, use the
1623     // full path, for example in `std::iter::ExactSizeIterator`
1624     let use_absolute = match implementor.inner_impl().for_ {
1625         clean::Type::Path { ref path, .. }
1626         | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
1627             if !path.is_assoc_ty() =>
1628         {
1629             implementor_dups[&path.last()].1
1630         }
1631         _ => false,
1632     };
1633     render_impl(
1634         w,
1635         cx,
1636         implementor,
1637         trait_,
1638         AssocItemLink::Anchor(None),
1639         RenderMode::Normal,
1640         Some(use_absolute),
1641         aliases,
1642         ImplRenderingParameters {
1643             show_def_docs: false,
1644             show_default_items: false,
1645             show_non_assoc_items: false,
1646             toggle_open_by_default: false,
1647         },
1648     );
1649 }
1650
1651 fn render_union(
1652     w: &mut Buffer,
1653     it: &clean::Item,
1654     g: Option<&clean::Generics>,
1655     fields: &[clean::Item],
1656     tab: &str,
1657     cx: &Context<'_>,
1658 ) {
1659     write!(w, "{}union {}", it.visibility.print_with_space(it.item_id, cx), it.name.unwrap(),);
1660
1661     let where_displayed = g
1662         .map(|g| {
1663             write!(w, "{}", g.print(cx));
1664             print_where_clause_and_check(w, g, cx)
1665         })
1666         .unwrap_or(false);
1667
1668     // If there wasn't a `where` clause, we add a whitespace.
1669     if !where_displayed {
1670         w.write_str(" ");
1671     }
1672
1673     write!(w, "{{\n{}", tab);
1674     let count_fields =
1675         fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1676     let toggle = should_hide_fields(count_fields);
1677     if toggle {
1678         toggle_open(w, format_args!("{} fields", count_fields));
1679     }
1680
1681     for field in fields {
1682         if let clean::StructFieldItem(ref ty) = *field.kind {
1683             write!(
1684                 w,
1685                 "    {}{}: {},\n{}",
1686                 field.visibility.print_with_space(field.item_id, cx),
1687                 field.name.unwrap(),
1688                 ty.print(cx),
1689                 tab
1690             );
1691         }
1692     }
1693
1694     if it.has_stripped_entries().unwrap() {
1695         write!(w, "    /* private fields */\n{}", tab);
1696     }
1697     if toggle {
1698         toggle_close(w);
1699     }
1700     w.write_str("}");
1701 }
1702
1703 fn render_struct(
1704     w: &mut Buffer,
1705     it: &clean::Item,
1706     g: Option<&clean::Generics>,
1707     ty: CtorKind,
1708     fields: &[clean::Item],
1709     tab: &str,
1710     structhead: bool,
1711     cx: &Context<'_>,
1712 ) {
1713     write!(
1714         w,
1715         "{}{}{}",
1716         it.visibility.print_with_space(it.item_id, cx),
1717         if structhead { "struct " } else { "" },
1718         it.name.unwrap()
1719     );
1720     if let Some(g) = g {
1721         write!(w, "{}", g.print(cx))
1722     }
1723     match ty {
1724         CtorKind::Fictive => {
1725             let where_diplayed = g.map(|g| print_where_clause_and_check(w, g, cx)).unwrap_or(false);
1726
1727             // If there wasn't a `where` clause, we add a whitespace.
1728             if !where_diplayed {
1729                 w.write_str(" {");
1730             } else {
1731                 w.write_str("{");
1732             }
1733             let count_fields =
1734                 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1735             let has_visible_fields = count_fields > 0;
1736             let toggle = should_hide_fields(count_fields);
1737             if toggle {
1738                 toggle_open(w, format_args!("{} fields", count_fields));
1739             }
1740             for field in fields {
1741                 if let clean::StructFieldItem(ref ty) = *field.kind {
1742                     write!(
1743                         w,
1744                         "\n{}    {}{}: {},",
1745                         tab,
1746                         field.visibility.print_with_space(field.item_id, cx),
1747                         field.name.unwrap(),
1748                         ty.print(cx),
1749                     );
1750                 }
1751             }
1752
1753             if has_visible_fields {
1754                 if it.has_stripped_entries().unwrap() {
1755                     write!(w, "\n{}    /* private fields */", tab);
1756                 }
1757                 write!(w, "\n{}", tab);
1758             } else if it.has_stripped_entries().unwrap() {
1759                 write!(w, " /* private fields */ ");
1760             }
1761             if toggle {
1762                 toggle_close(w);
1763             }
1764             w.write_str("}");
1765         }
1766         CtorKind::Fn => {
1767             w.write_str("(");
1768             for (i, field) in fields.iter().enumerate() {
1769                 if i > 0 {
1770                     w.write_str(", ");
1771                 }
1772                 match *field.kind {
1773                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1774                     clean::StructFieldItem(ref ty) => {
1775                         write!(
1776                             w,
1777                             "{}{}",
1778                             field.visibility.print_with_space(field.item_id, cx),
1779                             ty.print(cx),
1780                         )
1781                     }
1782                     _ => unreachable!(),
1783                 }
1784             }
1785             w.write_str(")");
1786             if let Some(g) = g {
1787                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1788             }
1789             // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1790             if structhead {
1791                 w.write_str(";");
1792             }
1793         }
1794         CtorKind::Const => {
1795             // Needed for PhantomData.
1796             if let Some(g) = g {
1797                 write!(w, "{}", print_where_clause(g, cx, 0, Ending::NoNewline));
1798             }
1799             w.write_str(";");
1800         }
1801     }
1802 }
1803
1804 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1805     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1806 }
1807
1808 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1809     if item.is_non_exhaustive() {
1810         write!(
1811             w,
1812             "<details class=\"rustdoc-toggle non-exhaustive\">\
1813                  <summary class=\"hideme\"><span>{}</span></summary>\
1814                  <div class=\"docblock\">",
1815             {
1816                 if item.is_struct() {
1817                     "This struct is marked as non-exhaustive"
1818                 } else if item.is_enum() {
1819                     "This enum is marked as non-exhaustive"
1820                 } else if item.is_variant() {
1821                     "This variant is marked as non-exhaustive"
1822                 } else {
1823                     "This type is marked as non-exhaustive"
1824                 }
1825             }
1826         );
1827
1828         if item.is_struct() {
1829             w.write_str(
1830                 "Non-exhaustive structs could have additional fields added in future. \
1831                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1832                  using the traditional <code>Struct { .. }</code> syntax; cannot be \
1833                  matched against without a wildcard <code>..</code>; and \
1834                  struct update syntax will not work.",
1835             );
1836         } else if item.is_enum() {
1837             w.write_str(
1838                 "Non-exhaustive enums could have additional variants added in future. \
1839                  Therefore, when matching against variants of non-exhaustive enums, an \
1840                  extra wildcard arm must be added to account for any future variants.",
1841             );
1842         } else if item.is_variant() {
1843             w.write_str(
1844                 "Non-exhaustive enum variants could have additional fields added in future. \
1845                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1846                  crates and cannot be matched against.",
1847             );
1848         } else {
1849             w.write_str(
1850                 "This type will require a wildcard arm in any match statements or constructors.",
1851             );
1852         }
1853
1854         w.write_str("</div></details>");
1855     }
1856 }
1857
1858 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1859     fn write_size_of_layout(w: &mut Buffer, layout: Layout<'_>, tag_size: u64) {
1860         if layout.abi().is_unsized() {
1861             write!(w, "(unsized)");
1862         } else {
1863             let bytes = layout.size().bytes() - tag_size;
1864             write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1865         }
1866     }
1867
1868     if !cx.shared.show_type_layout {
1869         return;
1870     }
1871
1872     writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1873     writeln!(w, "<div class=\"docblock\">");
1874
1875     let tcx = cx.tcx();
1876     let param_env = tcx.param_env(ty_def_id);
1877     let ty = tcx.type_of(ty_def_id);
1878     match tcx.layout_of(param_env.and(ty)) {
1879         Ok(ty_layout) => {
1880             writeln!(
1881                 w,
1882                 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1883                  <strong>completely unstable</strong> and may even differ between compilations. \
1884                  The only exception is types with certain <code>repr(...)</code> attributes. \
1885                  Please see the Rust Reference’s \
1886                  <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1887                  chapter for details on type layout guarantees.</p></div>"
1888             );
1889             w.write_str("<p><strong>Size:</strong> ");
1890             write_size_of_layout(w, ty_layout.layout, 0);
1891             writeln!(w, "</p>");
1892             if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1893                 &ty_layout.layout.variants()
1894             {
1895                 if !variants.is_empty() {
1896                     w.write_str(
1897                         "<p><strong>Size for each variant:</strong></p>\
1898                             <ul>",
1899                     );
1900
1901                     let Adt(adt, _) = ty_layout.ty.kind() else {
1902                         span_bug!(tcx.def_span(ty_def_id), "not an adt")
1903                     };
1904
1905                     let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1906                         0
1907                     } else if let Primitive::Int(i, _) = tag.primitive() {
1908                         i.size().bytes()
1909                     } else {
1910                         span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1911                     };
1912
1913                     for (index, layout) in variants.iter_enumerated() {
1914                         let name = adt.variant(index).name;
1915                         write!(w, "<li><code>{name}</code>: ", name = name);
1916                         write_size_of_layout(w, *layout, tag_size);
1917                         writeln!(w, "</li>");
1918                     }
1919                     w.write_str("</ul>");
1920                 }
1921             }
1922         }
1923         // This kind of layout error can occur with valid code, e.g. if you try to
1924         // get the layout of a generic type such as `Vec<T>`.
1925         Err(LayoutError::Unknown(_)) => {
1926             writeln!(
1927                 w,
1928                 "<p><strong>Note:</strong> Unable to compute type layout, \
1929                  possibly due to this type having generic parameters. \
1930                  Layout can only be computed for concrete, fully-instantiated types.</p>"
1931             );
1932         }
1933         // This kind of error probably can't happen with valid code, but we don't
1934         // want to panic and prevent the docs from building, so we just let the
1935         // user know that we couldn't compute the layout.
1936         Err(LayoutError::SizeOverflow(_)) => {
1937             writeln!(
1938                 w,
1939                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1940                  the type was too big.</p>"
1941             );
1942         }
1943         Err(LayoutError::NormalizationFailure(_, _)) => {
1944             writeln!(
1945                 w,
1946                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1947                 the type failed to be normalized.</p>"
1948             )
1949         }
1950     }
1951
1952     writeln!(w, "</div>");
1953 }
1954
1955 fn pluralize(count: usize) -> &'static str {
1956     if count > 1 { "s" } else { "" }
1957 }