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