]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/print_item.rs
Auto merge of #90491 - Mark-Simulacrum:push-pred-faster, r=matthewjasper
[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::ResolvedPath { ref path, did, .. }
731                 | clean::BorrowedRef {
732                     type_: box clean::ResolvedPath { ref path, did, .. }, ..
733                 } if !path.is_assoc_ty() => {
734                     let &mut (prev_did, ref mut has_duplicates) =
735                         implementor_dups.entry(path.last()).or_insert((did, false));
736                     if prev_did != did {
737                         *has_duplicates = true;
738                     }
739                 }
740                 _ => {}
741             }
742         }
743
744         let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| {
745             i.inner_impl().for_.def_id(cache).map_or(true, |d| cache.paths.contains_key(&d))
746         });
747
748         let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
749             local.iter().partition(|i| i.inner_impl().kind.is_auto());
750
751         synthetic.sort_by(|a, b| compare_impl(a, b, cx));
752         concrete.sort_by(|a, b| compare_impl(a, b, cx));
753
754         if !foreign.is_empty() {
755             write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", "");
756
757             for implementor in foreign {
758                 let provided_methods = implementor.inner_impl().provided_trait_methods(cx.tcx());
759                 let assoc_link =
760                     AssocItemLink::GotoSource(implementor.impl_item.def_id, &provided_methods);
761                 render_impl(
762                     w,
763                     cx,
764                     implementor,
765                     it,
766                     assoc_link,
767                     RenderMode::Normal,
768                     None,
769                     &[],
770                     ImplRenderingParameters {
771                         show_def_docs: false,
772                         is_on_foreign_type: true,
773                         show_default_items: false,
774                         show_non_assoc_items: true,
775                         toggle_open_by_default: false,
776                     },
777                 );
778             }
779         }
780
781         write_small_section_header(
782             w,
783             "implementors",
784             "Implementors",
785             "<div class=\"item-list\" id=\"implementors-list\">",
786         );
787         for implementor in concrete {
788             render_implementor(cx, implementor, it, w, &implementor_dups, &[]);
789         }
790         w.write_str("</div>");
791
792         if t.is_auto {
793             write_small_section_header(
794                 w,
795                 "synthetic-implementors",
796                 "Auto implementors",
797                 "<div class=\"item-list\" id=\"synthetic-implementors-list\">",
798             );
799             for implementor in synthetic {
800                 render_implementor(
801                     cx,
802                     implementor,
803                     it,
804                     w,
805                     &implementor_dups,
806                     &collect_paths_for_type(implementor.inner_impl().for_.clone(), cache),
807                 );
808             }
809             w.write_str("</div>");
810         }
811     } else {
812         // even without any implementations to write in, we still want the heading and list, so the
813         // implementors javascript file pulled in below has somewhere to write the impls into
814         write_small_section_header(
815             w,
816             "implementors",
817             "Implementors",
818             "<div class=\"item-list\" id=\"implementors-list\"></div>",
819         );
820
821         if t.is_auto {
822             write_small_section_header(
823                 w,
824                 "synthetic-implementors",
825                 "Auto implementors",
826                 "<div class=\"item-list\" id=\"synthetic-implementors-list\"></div>",
827             );
828         }
829     }
830
831     write!(
832         w,
833         "<script type=\"text/javascript\" \
834                  src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\
835          </script>",
836         root_path = vec![".."; cx.current.len()].join("/"),
837         path = if it.def_id.is_local() {
838             cx.current.join("/")
839         } else {
840             let (ref path, _) = cache.external_paths[&it.def_id.expect_def_id()];
841             path[..path.len() - 1].join("/")
842         },
843         ty = it.type_(),
844         name = *it.name.as_ref().unwrap()
845     );
846 }
847
848 fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) {
849     wrap_into_docblock(w, |w| {
850         wrap_item(w, "trait-alias", |w| {
851             render_attributes_in_pre(w, it, "");
852             write!(
853                 w,
854                 "trait {}{}{} = {};",
855                 it.name.as_ref().unwrap(),
856                 t.generics.print(cx),
857                 print_where_clause(&t.generics, cx, 0, true),
858                 bounds(&t.bounds, true, cx)
859             );
860         });
861     });
862
863     document(w, cx, it, None, HeadingOffset::H2);
864
865     // Render any items associated directly to this alias, as otherwise they
866     // won't be visible anywhere in the docs. It would be nice to also show
867     // associated items from the aliased type (see discussion in #32077), but
868     // we need #14072 to make sense of the generics.
869     render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
870 }
871
872 fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) {
873     wrap_into_docblock(w, |w| {
874         wrap_item(w, "opaque", |w| {
875             render_attributes_in_pre(w, it, "");
876             write!(
877                 w,
878                 "type {}{}{where_clause} = impl {bounds};",
879                 it.name.as_ref().unwrap(),
880                 t.generics.print(cx),
881                 where_clause = print_where_clause(&t.generics, cx, 0, true),
882                 bounds = bounds(&t.bounds, false, cx),
883             );
884         });
885     });
886
887     document(w, cx, it, None, HeadingOffset::H2);
888
889     // Render any items associated directly to this alias, as otherwise they
890     // won't be visible anywhere in the docs. It would be nice to also show
891     // associated items from the aliased type (see discussion in #32077), but
892     // we need #14072 to make sense of the generics.
893     render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
894 }
895
896 fn item_typedef(
897     w: &mut Buffer,
898     cx: &Context<'_>,
899     it: &clean::Item,
900     t: &clean::Typedef,
901     is_associated: bool,
902 ) {
903     fn write_content(
904         w: &mut Buffer,
905         cx: &Context<'_>,
906         it: &clean::Item,
907         t: &clean::Typedef,
908         is_associated: bool,
909     ) {
910         wrap_item(w, "typedef", |w| {
911             render_attributes_in_pre(w, it, "");
912             if !is_associated {
913                 write!(w, "{}", it.visibility.print_with_space(it.def_id, cx));
914             }
915             write!(
916                 w,
917                 "type {}{}{where_clause} = {type_};",
918                 it.name.as_ref().unwrap(),
919                 t.generics.print(cx),
920                 where_clause = print_where_clause(&t.generics, cx, 0, true),
921                 type_ = t.type_.print(cx),
922             );
923         });
924     }
925
926     // If this is an associated typedef, we don't want to wrap it into a docblock.
927     if is_associated {
928         write_content(w, cx, it, t, is_associated);
929     } else {
930         wrap_into_docblock(w, |w| {
931             write_content(w, cx, it, t, is_associated);
932         });
933     }
934
935     document(w, cx, it, None, HeadingOffset::H2);
936
937     let def_id = it.def_id.expect_def_id();
938     // Render any items associated directly to this alias, as otherwise they
939     // won't be visible anywhere in the docs. It would be nice to also show
940     // associated items from the aliased type (see discussion in #32077), but
941     // we need #14072 to make sense of the generics.
942     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
943 }
944
945 fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
946     wrap_into_docblock(w, |w| {
947         wrap_item(w, "union", |w| {
948             render_attributes_in_pre(w, it, "");
949             render_union(w, it, Some(&s.generics), &s.fields, "", cx);
950         });
951     });
952
953     document(w, cx, it, None, HeadingOffset::H2);
954
955     let mut fields = s
956         .fields
957         .iter()
958         .filter_map(|f| match *f.kind {
959             clean::StructFieldItem(ref ty) => Some((f, ty)),
960             _ => None,
961         })
962         .peekable();
963     if fields.peek().is_some() {
964         write!(
965             w,
966             "<h2 id=\"fields\" class=\"fields small-section-header\">\
967                    Fields<a href=\"#fields\" class=\"anchor\"></a></h2>"
968         );
969         for (field, ty) in fields {
970             let name = field.name.as_ref().expect("union field name");
971             let id = format!("{}.{}", ItemType::StructField, name);
972             write!(
973                 w,
974                 "<span id=\"{id}\" class=\"{shortty} small-section-header\">\
975                      <a href=\"#{id}\" class=\"anchor field\"></a>\
976                      <code>{name}: {ty}</code>\
977                  </span>",
978                 id = id,
979                 name = name,
980                 shortty = ItemType::StructField,
981                 ty = ty.print(cx),
982             );
983             if let Some(stability_class) = field.stability_class(cx.tcx()) {
984                 write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class);
985             }
986             document(w, cx, field, Some(it), HeadingOffset::H3);
987         }
988     }
989     let def_id = it.def_id.expect_def_id();
990     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
991     document_type_layout(w, cx, def_id);
992 }
993
994 fn print_tuple_struct_fields(w: &mut Buffer, cx: &Context<'_>, s: &[clean::Item]) {
995     for (i, ty) in s.iter().enumerate() {
996         if i > 0 {
997             w.write_str(",&nbsp;");
998         }
999         match *ty.kind {
1000             clean::StrippedItem(box clean::StructFieldItem(_)) => w.write_str("_"),
1001             clean::StructFieldItem(ref ty) => write!(w, "{}", ty.print(cx)),
1002             _ => unreachable!(),
1003         }
1004     }
1005 }
1006
1007 fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
1008     wrap_into_docblock(w, |w| {
1009         wrap_item(w, "enum", |w| {
1010             render_attributes_in_pre(w, it, "");
1011             write!(
1012                 w,
1013                 "{}enum {}{}{}",
1014                 it.visibility.print_with_space(it.def_id, cx),
1015                 it.name.as_ref().unwrap(),
1016                 e.generics.print(cx),
1017                 print_where_clause(&e.generics, cx, 0, true),
1018             );
1019             if e.variants.is_empty() && !e.variants_stripped {
1020                 w.write_str(" {}");
1021             } else {
1022                 w.write_str(" {\n");
1023                 let count_variants = e.variants.len();
1024                 let toggle = should_hide_fields(count_variants);
1025                 if toggle {
1026                     toggle_open(w, format_args!("{} variants", count_variants));
1027                 }
1028                 for v in &e.variants {
1029                     w.write_str("    ");
1030                     let name = v.name.as_ref().unwrap();
1031                     match *v.kind {
1032                         clean::VariantItem(ref var) => match var {
1033                             clean::Variant::CLike => write!(w, "{}", name),
1034                             clean::Variant::Tuple(ref s) => {
1035                                 write!(w, "{}(", name);
1036                                 print_tuple_struct_fields(w, cx, s);
1037                                 w.write_str(")");
1038                             }
1039                             clean::Variant::Struct(ref s) => {
1040                                 render_struct(
1041                                     w,
1042                                     v,
1043                                     None,
1044                                     s.struct_type,
1045                                     &s.fields,
1046                                     "    ",
1047                                     false,
1048                                     cx,
1049                                 );
1050                             }
1051                         },
1052                         _ => unreachable!(),
1053                     }
1054                     w.write_str(",\n");
1055                 }
1056
1057                 if e.variants_stripped {
1058                     w.write_str("    // some variants omitted\n");
1059                 }
1060                 if toggle {
1061                     toggle_close(w);
1062                 }
1063                 w.write_str("}");
1064             }
1065         });
1066     });
1067
1068     document(w, cx, it, None, HeadingOffset::H2);
1069
1070     if !e.variants.is_empty() {
1071         write!(
1072             w,
1073             "<h2 id=\"variants\" class=\"variants small-section-header\">\
1074                    Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>",
1075             document_non_exhaustive_header(it)
1076         );
1077         document_non_exhaustive(w, it);
1078         for variant in &e.variants {
1079             let id =
1080                 cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap()));
1081             write!(
1082                 w,
1083                 "<h3 id=\"{id}\" class=\"variant small-section-header\">\
1084                     <a href=\"#{id}\" class=\"anchor field\"></a>\
1085                     <code>{name}",
1086                 id = id,
1087                 name = variant.name.as_ref().unwrap()
1088             );
1089             if let clean::VariantItem(clean::Variant::Tuple(ref s)) = *variant.kind {
1090                 w.write_str("(");
1091                 print_tuple_struct_fields(w, cx, s);
1092                 w.write_str(")");
1093             }
1094             w.write_str("</code>");
1095             render_stability_since(w, variant, it, cx.tcx());
1096             w.write_str("</h3>");
1097
1098             use crate::clean::Variant;
1099             if let Some((extra, fields)) = match *variant.kind {
1100                 clean::VariantItem(Variant::Struct(ref s)) => Some(("", &s.fields)),
1101                 clean::VariantItem(Variant::Tuple(ref fields)) => Some(("Tuple ", fields)),
1102                 _ => None,
1103             } {
1104                 let variant_id = cx.derive_id(format!(
1105                     "{}.{}.fields",
1106                     ItemType::Variant,
1107                     variant.name.as_ref().unwrap()
1108                 ));
1109                 write!(w, "<div class=\"sub-variant\" id=\"{id}\">", id = variant_id);
1110                 write!(w, "<h4>{extra}Fields</h4>", extra = extra,);
1111                 document_non_exhaustive(w, variant);
1112                 for field in fields {
1113                     match *field.kind {
1114                         clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1115                         clean::StructFieldItem(ref ty) => {
1116                             let id = cx.derive_id(format!(
1117                                 "variant.{}.field.{}",
1118                                 variant.name.as_ref().unwrap(),
1119                                 field.name.as_ref().unwrap()
1120                             ));
1121                             write!(
1122                                 w,
1123                                 "<div class=\"sub-variant-field\">\
1124                                  <span id=\"{id}\" class=\"variant small-section-header\">\
1125                                     <a href=\"#{id}\" class=\"anchor field\"></a>\
1126                                     <code>{f}:&nbsp;{t}</code>\
1127                                 </span>",
1128                                 id = id,
1129                                 f = field.name.as_ref().unwrap(),
1130                                 t = ty.print(cx)
1131                             );
1132                             document(w, cx, field, Some(variant), HeadingOffset::H5);
1133                             write!(w, "</div>");
1134                         }
1135                         _ => unreachable!(),
1136                     }
1137                 }
1138                 w.write_str("</div>");
1139             }
1140
1141             document(w, cx, variant, Some(it), HeadingOffset::H4);
1142         }
1143     }
1144     let def_id = it.def_id.expect_def_id();
1145     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1146     document_type_layout(w, cx, def_id);
1147 }
1148
1149 fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
1150     wrap_into_docblock(w, |w| {
1151         highlight::render_with_highlighting(
1152             &t.source,
1153             w,
1154             Some("macro"),
1155             None,
1156             None,
1157             it.span(cx.tcx()).inner().edition(),
1158             None,
1159             None,
1160             None,
1161         );
1162     });
1163     document(w, cx, it, None, HeadingOffset::H2)
1164 }
1165
1166 fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) {
1167     wrap_into_docblock(w, |w| {
1168         let name = it.name.as_ref().expect("proc-macros always have names");
1169         match m.kind {
1170             MacroKind::Bang => {
1171                 wrap_item(w, "macro", |w| {
1172                     write!(w, "{}!() {{ /* proc-macro */ }}", name);
1173                 });
1174             }
1175             MacroKind::Attr => {
1176                 wrap_item(w, "attr", |w| {
1177                     write!(w, "#[{}]", name);
1178                 });
1179             }
1180             MacroKind::Derive => {
1181                 wrap_item(w, "derive", |w| {
1182                     write!(w, "#[derive({})]", name);
1183                     if !m.helpers.is_empty() {
1184                         w.push_str("\n{\n");
1185                         w.push_str("    // Attributes available to this derive:\n");
1186                         for attr in &m.helpers {
1187                             writeln!(w, "    #[{}]", attr);
1188                         }
1189                         w.push_str("}\n");
1190                     }
1191                 });
1192             }
1193         }
1194     });
1195     document(w, cx, it, None, HeadingOffset::H2)
1196 }
1197
1198 fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1199     document(w, cx, it, None, HeadingOffset::H2);
1200     render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1201 }
1202
1203 fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) {
1204     wrap_into_docblock(w, |w| {
1205         wrap_item(w, "const", |w| {
1206             render_attributes_in_code(w, it);
1207
1208             write!(
1209                 w,
1210                 "{vis}const {name}: {typ}",
1211                 vis = it.visibility.print_with_space(it.def_id, cx),
1212                 name = it.name.as_ref().unwrap(),
1213                 typ = c.type_.print(cx),
1214             );
1215
1216             let value = c.value(cx.tcx());
1217             let is_literal = c.is_literal(cx.tcx());
1218             let expr = c.expr(cx.tcx());
1219             if value.is_some() || is_literal {
1220                 write!(w, " = {expr};", expr = Escape(&expr));
1221             } else {
1222                 w.write_str(";");
1223             }
1224
1225             if !is_literal {
1226                 if let Some(value) = &value {
1227                     let value_lowercase = value.to_lowercase();
1228                     let expr_lowercase = expr.to_lowercase();
1229
1230                     if value_lowercase != expr_lowercase
1231                         && value_lowercase.trim_end_matches("i32") != expr_lowercase
1232                     {
1233                         write!(w, " // {value}", value = Escape(value));
1234                     }
1235                 }
1236             }
1237         });
1238     });
1239
1240     document(w, cx, it, None, HeadingOffset::H2)
1241 }
1242
1243 fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) {
1244     wrap_into_docblock(w, |w| {
1245         wrap_item(w, "struct", |w| {
1246             render_attributes_in_code(w, it);
1247             render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx);
1248         });
1249     });
1250
1251     document(w, cx, it, None, HeadingOffset::H2);
1252
1253     let mut fields = s
1254         .fields
1255         .iter()
1256         .filter_map(|f| match *f.kind {
1257             clean::StructFieldItem(ref ty) => Some((f, ty)),
1258             _ => None,
1259         })
1260         .peekable();
1261     if let CtorKind::Fictive | CtorKind::Fn = s.struct_type {
1262         if fields.peek().is_some() {
1263             write!(
1264                 w,
1265                 "<h2 id=\"fields\" class=\"fields small-section-header\">\
1266                      {}{}<a href=\"#fields\" class=\"anchor\"></a>\
1267                  </h2>",
1268                 if let CtorKind::Fictive = s.struct_type { "Fields" } else { "Tuple Fields" },
1269                 document_non_exhaustive_header(it)
1270             );
1271             document_non_exhaustive(w, it);
1272             for (index, (field, ty)) in fields.enumerate() {
1273                 let field_name =
1274                     field.name.map_or_else(|| index.to_string(), |sym| (*sym.as_str()).to_string());
1275                 let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name));
1276                 write!(
1277                     w,
1278                     "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
1279                          <a href=\"#{id}\" class=\"anchor field\"></a>\
1280                          <code>{name}: {ty}</code>\
1281                      </span>",
1282                     item_type = ItemType::StructField,
1283                     id = id,
1284                     name = field_name,
1285                     ty = ty.print(cx)
1286                 );
1287                 document(w, cx, field, Some(it), HeadingOffset::H3);
1288             }
1289         }
1290     }
1291     let def_id = it.def_id.expect_def_id();
1292     render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
1293     document_type_layout(w, cx, def_id);
1294 }
1295
1296 fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
1297     wrap_into_docblock(w, |w| {
1298         wrap_item(w, "static", |w| {
1299             render_attributes_in_code(w, it);
1300             write!(
1301                 w,
1302                 "{vis}static {mutability}{name}: {typ}",
1303                 vis = it.visibility.print_with_space(it.def_id, cx),
1304                 mutability = s.mutability.print_with_space(),
1305                 name = it.name.as_ref().unwrap(),
1306                 typ = s.type_.print(cx)
1307             );
1308         });
1309     });
1310     document(w, cx, it, None, HeadingOffset::H2)
1311 }
1312
1313 fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1314     wrap_into_docblock(w, |w| {
1315         wrap_item(w, "foreigntype", |w| {
1316             w.write_str("extern {\n");
1317             render_attributes_in_code(w, it);
1318             write!(
1319                 w,
1320                 "    {}type {};\n}}",
1321                 it.visibility.print_with_space(it.def_id, cx),
1322                 it.name.as_ref().unwrap(),
1323             );
1324         });
1325     });
1326
1327     document(w, cx, it, None, HeadingOffset::H2);
1328
1329     render_assoc_items(w, cx, it, it.def_id.expect_def_id(), AssocItemRender::All)
1330 }
1331
1332 fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) {
1333     document(w, cx, it, None, HeadingOffset::H2)
1334 }
1335
1336 /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order).
1337 crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering {
1338     /// Takes a non-numeric and a numeric part from the given &str.
1339     fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) {
1340         let i = s.find(|c: char| c.is_ascii_digit());
1341         let (a, b) = s.split_at(i.unwrap_or(s.len()));
1342         let i = b.find(|c: char| !c.is_ascii_digit());
1343         let (b, c) = b.split_at(i.unwrap_or(b.len()));
1344         *s = c;
1345         (a, b)
1346     }
1347
1348     while !lhs.is_empty() || !rhs.is_empty() {
1349         let (la, lb) = take_parts(&mut lhs);
1350         let (ra, rb) = take_parts(&mut rhs);
1351         // First process the non-numeric part.
1352         match la.cmp(ra) {
1353             Ordering::Equal => (),
1354             x => return x,
1355         }
1356         // Then process the numeric part, if both sides have one (and they fit in a u64).
1357         if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) {
1358             match ln.cmp(&rn) {
1359                 Ordering::Equal => (),
1360                 x => return x,
1361             }
1362         }
1363         // Then process the numeric part again, but this time as strings.
1364         match lb.cmp(rb) {
1365             Ordering::Equal => (),
1366             x => return x,
1367         }
1368     }
1369
1370     Ordering::Equal
1371 }
1372
1373 pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
1374     let mut s = cx.current.join("::");
1375     s.push_str("::");
1376     s.push_str(&item.name.unwrap().as_str());
1377     s
1378 }
1379
1380 pub(super) fn item_path(ty: ItemType, name: &str) -> String {
1381     match ty {
1382         ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
1383         _ => format!("{}.{}.html", ty, name),
1384     }
1385 }
1386
1387 fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> String {
1388     let mut bounds = String::new();
1389     if !t_bounds.is_empty() {
1390         if !trait_alias {
1391             bounds.push_str(": ");
1392         }
1393         for (i, p) in t_bounds.iter().enumerate() {
1394             if i > 0 {
1395                 bounds.push_str(" + ");
1396             }
1397             bounds.push_str(&p.print(cx).to_string());
1398         }
1399     }
1400     bounds
1401 }
1402
1403 fn wrap_into_docblock<F>(w: &mut Buffer, f: F)
1404 where
1405     F: FnOnce(&mut Buffer),
1406 {
1407     w.write_str("<div class=\"docblock item-decl\">");
1408     f(w);
1409     w.write_str("</div>")
1410 }
1411
1412 fn wrap_item<F>(w: &mut Buffer, item_name: &str, f: F)
1413 where
1414     F: FnOnce(&mut Buffer),
1415 {
1416     w.write_fmt(format_args!("<pre class=\"rust {}\"><code>", item_name));
1417     f(w);
1418     w.write_str("</code></pre>");
1419 }
1420
1421 fn render_stability_since(
1422     w: &mut Buffer,
1423     item: &clean::Item,
1424     containing_item: &clean::Item,
1425     tcx: TyCtxt<'_>,
1426 ) {
1427     render_stability_since_raw(
1428         w,
1429         item.stable_since(tcx).as_deref(),
1430         item.const_stability(tcx),
1431         containing_item.stable_since(tcx).as_deref(),
1432         containing_item.const_stable_since(tcx).as_deref(),
1433     )
1434 }
1435
1436 fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cx: &Context<'_>) -> Ordering {
1437     let lhss = format!("{}", lhs.inner_impl().print(false, cx));
1438     let rhss = format!("{}", rhs.inner_impl().print(false, cx));
1439
1440     // lhs and rhs are formatted as HTML, which may be unnecessary
1441     compare_names(&lhss, &rhss)
1442 }
1443
1444 fn render_implementor(
1445     cx: &Context<'_>,
1446     implementor: &Impl,
1447     trait_: &clean::Item,
1448     w: &mut Buffer,
1449     implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
1450     aliases: &[String],
1451 ) {
1452     // If there's already another implementor that has the same abridged name, use the
1453     // full path, for example in `std::iter::ExactSizeIterator`
1454     let use_absolute = match implementor.inner_impl().for_ {
1455         clean::ResolvedPath { ref path, .. }
1456         | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, .. }, .. }
1457             if !path.is_assoc_ty() =>
1458         {
1459             implementor_dups[&path.last()].1
1460         }
1461         _ => false,
1462     };
1463     render_impl(
1464         w,
1465         cx,
1466         implementor,
1467         trait_,
1468         AssocItemLink::Anchor(None),
1469         RenderMode::Normal,
1470         Some(use_absolute),
1471         aliases,
1472         ImplRenderingParameters {
1473             show_def_docs: false,
1474             is_on_foreign_type: false,
1475             show_default_items: false,
1476             show_non_assoc_items: false,
1477             toggle_open_by_default: false,
1478         },
1479     );
1480 }
1481
1482 fn render_union(
1483     w: &mut Buffer,
1484     it: &clean::Item,
1485     g: Option<&clean::Generics>,
1486     fields: &[clean::Item],
1487     tab: &str,
1488     cx: &Context<'_>,
1489 ) {
1490     write!(
1491         w,
1492         "{}union {}",
1493         it.visibility.print_with_space(it.def_id, cx),
1494         it.name.as_ref().unwrap()
1495     );
1496     if let Some(g) = g {
1497         write!(w, "{}", g.print(cx));
1498         write!(w, "{}", print_where_clause(g, cx, 0, true));
1499     }
1500
1501     write!(w, " {{\n{}", tab);
1502     let count_fields =
1503         fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1504     let toggle = should_hide_fields(count_fields);
1505     if toggle {
1506         toggle_open(w, format_args!("{} fields", count_fields));
1507     }
1508
1509     for field in fields {
1510         if let clean::StructFieldItem(ref ty) = *field.kind {
1511             write!(
1512                 w,
1513                 "    {}{}: {},\n{}",
1514                 field.visibility.print_with_space(field.def_id, cx),
1515                 field.name.as_ref().unwrap(),
1516                 ty.print(cx),
1517                 tab
1518             );
1519         }
1520     }
1521
1522     if it.has_stripped_fields().unwrap() {
1523         write!(w, "    // some fields omitted\n{}", tab);
1524     }
1525     if toggle {
1526         toggle_close(w);
1527     }
1528     w.write_str("}");
1529 }
1530
1531 fn render_struct(
1532     w: &mut Buffer,
1533     it: &clean::Item,
1534     g: Option<&clean::Generics>,
1535     ty: CtorKind,
1536     fields: &[clean::Item],
1537     tab: &str,
1538     structhead: bool,
1539     cx: &Context<'_>,
1540 ) {
1541     write!(
1542         w,
1543         "{}{}{}",
1544         it.visibility.print_with_space(it.def_id, cx),
1545         if structhead { "struct " } else { "" },
1546         it.name.as_ref().unwrap()
1547     );
1548     if let Some(g) = g {
1549         write!(w, "{}", g.print(cx))
1550     }
1551     match ty {
1552         CtorKind::Fictive => {
1553             if let Some(g) = g {
1554                 write!(w, "{}", print_where_clause(g, cx, 0, true),)
1555             }
1556             w.write_str(" {");
1557             let count_fields =
1558                 fields.iter().filter(|f| matches!(*f.kind, clean::StructFieldItem(..))).count();
1559             let has_visible_fields = count_fields > 0;
1560             let toggle = should_hide_fields(count_fields);
1561             if toggle {
1562                 toggle_open(w, format_args!("{} fields", count_fields));
1563             }
1564             for field in fields {
1565                 if let clean::StructFieldItem(ref ty) = *field.kind {
1566                     write!(
1567                         w,
1568                         "\n{}    {}{}: {},",
1569                         tab,
1570                         field.visibility.print_with_space(field.def_id, cx),
1571                         field.name.as_ref().unwrap(),
1572                         ty.print(cx),
1573                     );
1574                 }
1575             }
1576
1577             if has_visible_fields {
1578                 if it.has_stripped_fields().unwrap() {
1579                     write!(w, "\n{}    // some fields omitted", tab);
1580                 }
1581                 write!(w, "\n{}", tab);
1582             } else if it.has_stripped_fields().unwrap() {
1583                 // If there are no visible fields we can just display
1584                 // `{ /* fields omitted */ }` to save space.
1585                 write!(w, " /* fields omitted */ ");
1586             }
1587             if toggle {
1588                 toggle_close(w);
1589             }
1590             w.write_str("}");
1591         }
1592         CtorKind::Fn => {
1593             w.write_str("(");
1594             for (i, field) in fields.iter().enumerate() {
1595                 if i > 0 {
1596                     w.write_str(", ");
1597                 }
1598                 match *field.kind {
1599                     clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"),
1600                     clean::StructFieldItem(ref ty) => {
1601                         write!(
1602                             w,
1603                             "{}{}",
1604                             field.visibility.print_with_space(field.def_id, cx),
1605                             ty.print(cx),
1606                         )
1607                     }
1608                     _ => unreachable!(),
1609                 }
1610             }
1611             w.write_str(")");
1612             if let Some(g) = g {
1613                 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1614             }
1615             // We only want a ";" when we are displaying a tuple struct, not a variant tuple struct.
1616             if structhead {
1617                 w.write_str(";");
1618             }
1619         }
1620         CtorKind::Const => {
1621             // Needed for PhantomData.
1622             if let Some(g) = g {
1623                 write!(w, "{}", print_where_clause(g, cx, 0, false),)
1624             }
1625             w.write_str(";");
1626         }
1627     }
1628 }
1629
1630 fn document_non_exhaustive_header(item: &clean::Item) -> &str {
1631     if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
1632 }
1633
1634 fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
1635     if item.is_non_exhaustive() {
1636         write!(
1637             w,
1638             "<details class=\"rustdoc-toggle non-exhaustive\">\
1639                  <summary class=\"hideme\"><span>{}</span></summary>\
1640                  <div class=\"docblock\">",
1641             {
1642                 if item.is_struct() {
1643                     "This struct is marked as non-exhaustive"
1644                 } else if item.is_enum() {
1645                     "This enum is marked as non-exhaustive"
1646                 } else if item.is_variant() {
1647                     "This variant is marked as non-exhaustive"
1648                 } else {
1649                     "This type is marked as non-exhaustive"
1650                 }
1651             }
1652         );
1653
1654         if item.is_struct() {
1655             w.write_str(
1656                 "Non-exhaustive structs could have additional fields added in future. \
1657                  Therefore, non-exhaustive structs cannot be constructed in external crates \
1658                  using the traditional <code>Struct { .. }</code> syntax; cannot be \
1659                  matched against without a wildcard <code>..</code>; and \
1660                  struct update syntax will not work.",
1661             );
1662         } else if item.is_enum() {
1663             w.write_str(
1664                 "Non-exhaustive enums could have additional variants added in future. \
1665                  Therefore, when matching against variants of non-exhaustive enums, an \
1666                  extra wildcard arm must be added to account for any future variants.",
1667             );
1668         } else if item.is_variant() {
1669             w.write_str(
1670                 "Non-exhaustive enum variants could have additional fields added in future. \
1671                  Therefore, non-exhaustive enum variants cannot be constructed in external \
1672                  crates and cannot be matched against.",
1673             );
1674         } else {
1675             w.write_str(
1676                 "This type will require a wildcard arm in any match statements or constructors.",
1677             );
1678         }
1679
1680         w.write_str("</div></details>");
1681     }
1682 }
1683
1684 fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
1685     fn write_size_of_layout(w: &mut Buffer, layout: &Layout, tag_size: u64) {
1686         if layout.abi.is_unsized() {
1687             write!(w, "(unsized)");
1688         } else {
1689             let bytes = layout.size.bytes() - tag_size;
1690             write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },);
1691         }
1692     }
1693
1694     if !cx.shared.show_type_layout {
1695         return;
1696     }
1697
1698     writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
1699     writeln!(w, "<div class=\"docblock\">");
1700
1701     let tcx = cx.tcx();
1702     let param_env = tcx.param_env(ty_def_id);
1703     let ty = tcx.type_of(ty_def_id);
1704     match tcx.layout_of(param_env.and(ty)) {
1705         Ok(ty_layout) => {
1706             writeln!(
1707                 w,
1708                 "<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
1709                  <strong>completely unstable</strong> and may even differ between compilations. \
1710                  The only exception is types with certain <code>repr(...)</code> attributes. \
1711                  Please see the Rust Reference’s \
1712                  <a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
1713                  chapter for details on type layout guarantees.</p></div>"
1714             );
1715             w.write_str("<p><strong>Size:</strong> ");
1716             write_size_of_layout(w, ty_layout.layout, 0);
1717             writeln!(w, "</p>");
1718             if let Variants::Multiple { variants, tag, tag_encoding, .. } =
1719                 &ty_layout.layout.variants
1720             {
1721                 if !variants.is_empty() {
1722                     w.write_str(
1723                         "<p><strong>Size for each variant:</strong></p>\
1724                             <ul>",
1725                     );
1726
1727                     let adt = if let Adt(adt, _) = ty_layout.ty.kind() {
1728                         adt
1729                     } else {
1730                         span_bug!(tcx.def_span(ty_def_id), "not an adt")
1731                     };
1732
1733                     let tag_size = if let TagEncoding::Niche { .. } = tag_encoding {
1734                         0
1735                     } else if let Primitive::Int(i, _) = tag.value {
1736                         i.size().bytes()
1737                     } else {
1738                         span_bug!(tcx.def_span(ty_def_id), "tag is neither niche nor int")
1739                     };
1740
1741                     for (index, layout) in variants.iter_enumerated() {
1742                         let ident = adt.variants[index].ident;
1743                         write!(w, "<li><code>{name}</code>: ", name = ident);
1744                         write_size_of_layout(w, layout, tag_size);
1745                         writeln!(w, "</li>");
1746                     }
1747                     w.write_str("</ul>");
1748                 }
1749             }
1750         }
1751         // This kind of layout error can occur with valid code, e.g. if you try to
1752         // get the layout of a generic type such as `Vec<T>`.
1753         Err(LayoutError::Unknown(_)) => {
1754             writeln!(
1755                 w,
1756                 "<p><strong>Note:</strong> Unable to compute type layout, \
1757                  possibly due to this type having generic parameters. \
1758                  Layout can only be computed for concrete, fully-instantiated types.</p>"
1759             );
1760         }
1761         // This kind of error probably can't happen with valid code, but we don't
1762         // want to panic and prevent the docs from building, so we just let the
1763         // user know that we couldn't compute the layout.
1764         Err(LayoutError::SizeOverflow(_)) => {
1765             writeln!(
1766                 w,
1767                 "<p><strong>Note:</strong> Encountered an error during type layout; \
1768                  the type was too big.</p>"
1769             );
1770         }
1771     }
1772
1773     writeln!(w, "</div>");
1774 }
1775
1776 fn pluralize(count: usize) -> &'static str {
1777     if count > 1 { "s" } else { "" }
1778 }