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