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