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