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