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