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