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