1use std::cmp::Ordering;
2use std::fmt::{self, Display, Write as _};
3use std::iter;
4
5use askama::Template;
6use rustc_abi::VariantIdx;
7use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
8use rustc_hir as hir;
9use rustc_hir::def::CtorKind;
10use rustc_hir::def_id::DefId;
11use rustc_index::IndexVec;
12use rustc_middle::ty::{self, TyCtxt};
13use rustc_span::hygiene::MacroKind;
14use rustc_span::symbol::{Symbol, sym};
15use tracing::{debug, info};
16
17use super::type_layout::document_type_layout;
18use super::{
19 AssocItemLink, AssocItemRender, Context, ImplRenderingParameters, RenderMode,
20 collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
21 item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
22 render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
23 render_impl, render_rightside, render_stability_since_raw,
24 render_stability_since_raw_with_extra, write_section_heading,
25};
26use crate::clean;
27use crate::config::ModuleSorting;
28use crate::display::{Joined as _, MaybeDisplay as _};
29use crate::formats::Impl;
30use crate::formats::item_type::ItemType;
31use crate::html::escape::{Escape, EscapeBodyTextWithWbr};
32use crate::html::format::{
33 Ending, PrintWithSpace, join_with_double_colon, print_abi_with_space,
34 print_constness_with_space, print_where_clause, visibility_print_with_space,
35};
36use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
37use crate::html::render::{document_full, document_item_info};
38use crate::html::url_parts_builder::UrlPartsBuilder;
39
40macro_rules! item_template {
59 (
60 $(#[$meta:meta])*
61 struct $name:ident<'a, 'cx> {
62 cx: &'a Context<'cx>,
63 it: &'a clean::Item,
64 $($field_name:ident: $field_ty:ty),*,
65 },
66 methods = [$($methods:tt),* $(,)?]
67 ) => {
68 #[derive(Template)]
69 $(#[$meta])*
70 struct $name<'a, 'cx> {
71 cx: &'a Context<'cx>,
72 it: &'a clean::Item,
73 $($field_name: $field_ty),*
74 }
75
76 impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for $name<'a, 'cx> {
77 fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>) {
78 (&self.it, &self.cx)
79 }
80 }
81
82 impl<'a, 'cx: 'a> $name<'a, 'cx> {
83 item_template_methods!($($methods)*);
84 }
85 };
86}
87
88macro_rules! item_template_methods {
92 () => {};
93 (document $($rest:tt)*) => {
94 fn document(&self) -> impl fmt::Display {
95 let (item, cx) = self.item_and_cx();
96 document(cx, item, None, HeadingOffset::H2)
97 }
98 item_template_methods!($($rest)*);
99 };
100 (document_type_layout $($rest:tt)*) => {
101 fn document_type_layout(&self) -> impl fmt::Display {
102 let (item, cx) = self.item_and_cx();
103 let def_id = item.item_id.expect_def_id();
104 document_type_layout(cx, def_id)
105 }
106 item_template_methods!($($rest)*);
107 };
108 (render_attributes_in_pre $($rest:tt)*) => {
109 fn render_attributes_in_pre(&self) -> impl fmt::Display {
110 let (item, cx) = self.item_and_cx();
111 render_attributes_in_pre(item, "", cx)
112 }
113 item_template_methods!($($rest)*);
114 };
115 (render_assoc_items $($rest:tt)*) => {
116 fn render_assoc_items(&self) -> impl fmt::Display {
117 let (item, cx) = self.item_and_cx();
118 let def_id = item.item_id.expect_def_id();
119 render_assoc_items(cx, item, def_id, AssocItemRender::All)
120 }
121 item_template_methods!($($rest)*);
122 };
123 ($method:ident $($rest:tt)*) => {
124 compile_error!(concat!("unknown method: ", stringify!($method)));
125 };
126 ($token:tt $($rest:tt)*) => {
127 compile_error!(concat!("unexpected token: ", stringify!($token)));
128 };
129}
130
131const ITEM_TABLE_OPEN: &str = "<dl class=\"item-table\">";
132const REEXPORTS_TABLE_OPEN: &str = "<dl class=\"item-table reexports\">";
133const ITEM_TABLE_CLOSE: &str = "</dl>";
134
135struct PathComponent {
137 path: String,
138 name: Symbol,
139}
140
141#[derive(Template)]
142#[template(path = "print_item.html")]
143struct ItemVars<'a> {
144 typ: &'a str,
145 name: &'a str,
146 item_type: &'a str,
147 path_components: Vec<PathComponent>,
148 stability_since_raw: &'a str,
149 src_href: Option<&'a str>,
150}
151
152pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item) -> impl fmt::Display {
153 debug_assert!(!item.is_stripped());
154
155 fmt::from_fn(|buf| {
156 let typ = match item.kind {
157 clean::ModuleItem(_) => {
158 if item.is_crate() {
159 "Crate "
160 } else {
161 "Module "
162 }
163 }
164 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
165 clean::TraitItem(..) => "Trait ",
166 clean::StructItem(..) => "Struct ",
167 clean::UnionItem(..) => "Union ",
168 clean::EnumItem(..) => "Enum ",
169 clean::TypeAliasItem(..) => "Type Alias ",
170 clean::MacroItem(..) => "Macro ",
171 clean::ProcMacroItem(ref mac) => match mac.kind {
172 MacroKind::Bang => "Macro ",
173 MacroKind::Attr => "Attribute Macro ",
174 MacroKind::Derive => "Derive Macro ",
175 },
176 clean::PrimitiveItem(..) => "Primitive Type ",
177 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
178 clean::ConstantItem(..) => "Constant ",
179 clean::ForeignTypeItem => "Foreign Type ",
180 clean::KeywordItem => "Keyword ",
181 clean::TraitAliasItem(..) => "Trait Alias ",
182 _ => {
183 unreachable!();
185 }
186 };
187 let stability_since_raw =
188 render_stability_since_raw(item.stable_since(cx.tcx()), item.const_stability(cx.tcx()))
189 .maybe_display()
190 .to_string();
191
192 let src_href =
199 if cx.info.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
200
201 let path_components = if item.is_primitive() || item.is_keyword() {
202 vec![]
203 } else {
204 let cur = &cx.current;
205 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
206 cur.iter()
207 .enumerate()
208 .take(amt)
209 .map(|(i, component)| PathComponent {
210 path: "../".repeat(cur.len() - i - 1),
211 name: *component,
212 })
213 .collect()
214 };
215
216 let item_vars = ItemVars {
217 typ,
218 name: item.name.as_ref().unwrap().as_str(),
219 item_type: &item.type_().to_string(),
220 path_components,
221 stability_since_raw: &stability_since_raw,
222 src_href: src_href.as_deref(),
223 };
224
225 item_vars.render_into(buf).unwrap();
226
227 match &item.kind {
228 clean::ModuleItem(m) => {
229 write!(buf, "{}", item_module(cx, item, &m.items))
230 }
231 clean::FunctionItem(f) | clean::ForeignFunctionItem(f, _) => {
232 write!(buf, "{}", item_function(cx, item, f))
233 }
234 clean::TraitItem(t) => write!(buf, "{}", item_trait(cx, item, t)),
235 clean::StructItem(s) => {
236 write!(buf, "{}", item_struct(cx, item, s))
237 }
238 clean::UnionItem(s) => write!(buf, "{}", item_union(cx, item, s)),
239 clean::EnumItem(e) => write!(buf, "{}", item_enum(cx, item, e)),
240 clean::TypeAliasItem(t) => {
241 write!(buf, "{}", item_type_alias(cx, item, t))
242 }
243 clean::MacroItem(m) => write!(buf, "{}", item_macro(cx, item, m)),
244 clean::ProcMacroItem(m) => {
245 write!(buf, "{}", item_proc_macro(cx, item, m))
246 }
247 clean::PrimitiveItem(_) => write!(buf, "{}", item_primitive(cx, item)),
248 clean::StaticItem(i) => {
249 write!(buf, "{}", item_static(cx, item, i, None))
250 }
251 clean::ForeignStaticItem(i, safety) => {
252 write!(buf, "{}", item_static(cx, item, i, Some(*safety)))
253 }
254 clean::ConstantItem(ci) => {
255 write!(buf, "{}", item_constant(cx, item, &ci.generics, &ci.type_, &ci.kind))
256 }
257 clean::ForeignTypeItem => {
258 write!(buf, "{}", item_foreign_type(cx, item))
259 }
260 clean::KeywordItem => write!(buf, "{}", item_keyword(cx, item)),
261 clean::TraitAliasItem(ta) => {
262 write!(buf, "{}", item_trait_alias(cx, item, ta))
263 }
264 _ => {
265 unreachable!();
267 }
268 }?;
269
270 let mut types_with_notable_traits = cx.types_with_notable_traits.borrow_mut();
272 if !types_with_notable_traits.is_empty() {
273 write!(
274 buf,
275 r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
276 notable_traits_json(types_with_notable_traits.iter(), cx),
277 )?;
278 types_with_notable_traits.clear();
279 }
280 Ok(())
281 })
282}
283
284fn should_hide_fields(n_fields: usize) -> bool {
286 n_fields > 12
287}
288
289fn toggle_open(mut w: impl fmt::Write, text: impl Display) {
290 write!(
291 w,
292 "<details class=\"toggle type-contents-toggle\">\
293 <summary class=\"hideme\">\
294 <span>Show {text}</span>\
295 </summary>",
296 )
297 .unwrap();
298}
299
300fn toggle_close(mut w: impl fmt::Write) {
301 w.write_str("</details>").unwrap();
302}
303
304trait ItemTemplate<'a, 'cx: 'a>: askama::Template + Display {
305 fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>);
306}
307
308fn item_module(cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) -> impl fmt::Display {
309 fmt::from_fn(|w| {
310 write!(w, "{}", document(cx, item, None, HeadingOffset::H2))?;
311
312 let mut not_stripped_items =
313 items.iter().filter(|i| !i.is_stripped()).enumerate().collect::<Vec<_>>();
314
315 fn reorder(ty: ItemType) -> u8 {
317 match ty {
318 ItemType::ExternCrate => 0,
319 ItemType::Import => 1,
320 ItemType::Primitive => 2,
321 ItemType::Module => 3,
322 ItemType::Macro => 4,
323 ItemType::Struct => 5,
324 ItemType::Enum => 6,
325 ItemType::Constant => 7,
326 ItemType::Static => 8,
327 ItemType::Trait => 9,
328 ItemType::Function => 10,
329 ItemType::TypeAlias => 12,
330 ItemType::Union => 13,
331 _ => 14 + ty as u8,
332 }
333 }
334
335 fn cmp(i1: &clean::Item, i2: &clean::Item, tcx: TyCtxt<'_>) -> Ordering {
336 let rty1 = reorder(i1.type_());
337 let rty2 = reorder(i2.type_());
338 if rty1 != rty2 {
339 return rty1.cmp(&rty2);
340 }
341 let is_stable1 =
342 i1.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
343 let is_stable2 =
344 i2.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
345 if is_stable1 != is_stable2 {
346 return is_stable2.cmp(&is_stable1);
349 }
350 match (i1.name, i2.name) {
351 (Some(name1), Some(name2)) => compare_names(name1.as_str(), name2.as_str()),
352 (Some(_), None) => Ordering::Greater,
353 (None, Some(_)) => Ordering::Less,
354 (None, None) => Ordering::Equal,
355 }
356 }
357
358 let tcx = cx.tcx();
359
360 match cx.shared.module_sorting {
361 ModuleSorting::Alphabetical => {
362 not_stripped_items.sort_by(|(_, i1), (_, i2)| cmp(i1, i2, tcx));
363 }
364 ModuleSorting::DeclarationOrder => {}
365 }
366 not_stripped_items.dedup_by_key(|(idx, i)| {
386 (
387 i.item_id,
388 if i.name.is_some() { Some(full_path(cx, i)) } else { None },
389 i.type_(),
390 if i.is_import() { *idx } else { 0 },
391 )
392 });
393
394 debug!("{not_stripped_items:?}");
395 let mut last_section = None;
396
397 for (_, myitem) in ¬_stripped_items {
398 let my_section = item_ty_to_section(myitem.type_());
399 if Some(my_section) != last_section {
400 if last_section.is_some() {
401 w.write_str(ITEM_TABLE_CLOSE)?;
402 }
403 last_section = Some(my_section);
404 let section_id = my_section.id();
405 let tag =
406 if section_id == "reexports" { REEXPORTS_TABLE_OPEN } else { ITEM_TABLE_OPEN };
407 write!(
408 w,
409 "{}",
410 write_section_heading(my_section.name(), &cx.derive_id(section_id), None, tag)
411 )?;
412 }
413
414 match myitem.kind {
415 clean::ExternCrateItem { ref src } => {
416 use crate::html::format::anchor;
417
418 match *src {
419 Some(src) => {
420 write!(
421 w,
422 "<dt><code>{}extern crate {} as {};",
423 visibility_print_with_space(myitem, cx),
424 anchor(myitem.item_id.expect_def_id(), src, cx),
425 EscapeBodyTextWithWbr(myitem.name.unwrap().as_str())
426 )?;
427 }
428 None => {
429 write!(
430 w,
431 "<dt><code>{}extern crate {};",
432 visibility_print_with_space(myitem, cx),
433 anchor(myitem.item_id.expect_def_id(), myitem.name.unwrap(), cx)
434 )?;
435 }
436 }
437 w.write_str("</code></dt>")?;
438 }
439
440 clean::ImportItem(ref import) => {
441 let stab_tags = import.source.did.map_or_else(String::new, |import_def_id| {
442 extra_info_tags(tcx, myitem, item, Some(import_def_id)).to_string()
443 });
444
445 let id = match import.kind {
446 clean::ImportKind::Simple(s) => {
447 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
448 }
449 clean::ImportKind::Glob => String::new(),
450 };
451 write!(
452 w,
453 "<dt{id}>\
454 <code>{vis}{imp}</code>{stab_tags}\
455 </dt>",
456 vis = visibility_print_with_space(myitem, cx),
457 imp = import.print(cx)
458 )?;
459 }
460
461 _ => {
462 if myitem.name.is_none() {
463 continue;
464 }
465
466 let unsafety_flag = match myitem.kind {
467 clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
468 if myitem.fn_header(tcx).unwrap().is_unsafe() =>
469 {
470 "<sup title=\"unsafe function\">âš </sup>"
471 }
472 clean::ForeignStaticItem(_, hir::Safety::Unsafe) => {
473 "<sup title=\"unsafe static\">âš </sup>"
474 }
475 _ => "",
476 };
477
478 let visibility_and_hidden = match myitem.visibility(tcx) {
479 Some(ty::Visibility::Restricted(_)) => {
480 if myitem.is_doc_hidden() {
481 "<span title=\"Restricted Visibility\"> 🔒</span><span title=\"Hidden item\">👻</span> "
483 } else {
484 "<span title=\"Restricted Visibility\"> 🔒</span> "
485 }
486 }
487 _ if myitem.is_doc_hidden() => {
488 "<span title=\"Hidden item\"> 👻</span> "
489 }
490 _ => "",
491 };
492
493 let docs =
494 MarkdownSummaryLine(&myitem.doc_value(), &myitem.links(cx)).into_string();
495 let (docs_before, docs_after) =
496 if docs.is_empty() { ("", "") } else { ("<dd>", "</dd>") };
497 write!(
498 w,
499 "<dt>\
500 <a class=\"{class}\" href=\"{href}\" title=\"{title}\">{name}</a>\
501 {visibility_and_hidden}\
502 {unsafety_flag}\
503 {stab_tags}\
504 </dt>\
505 {docs_before}{docs}{docs_after}",
506 name = EscapeBodyTextWithWbr(myitem.name.unwrap().as_str()),
507 visibility_and_hidden = visibility_and_hidden,
508 stab_tags = extra_info_tags(tcx, myitem, item, None),
509 class = myitem.type_(),
510 unsafety_flag = unsafety_flag,
511 href = item_path(myitem.type_(), myitem.name.unwrap().as_str()),
512 title = format_args!("{} {}", myitem.type_(), full_path(cx, myitem)),
513 )?;
514 }
515 }
516 }
517
518 if last_section.is_some() {
519 w.write_str(ITEM_TABLE_CLOSE)?;
520 }
521 Ok(())
522 })
523}
524
525fn extra_info_tags(
528 tcx: TyCtxt<'_>,
529 item: &clean::Item,
530 parent: &clean::Item,
531 import_def_id: Option<DefId>,
532) -> impl Display {
533 fmt::from_fn(move |f| {
534 fn tag_html(class: &str, title: &str, contents: &str) -> impl Display {
535 fmt::from_fn(move |f| {
536 write!(
537 f,
538 r#"<wbr><span class="stab {class}" title="{title}">{contents}</span>"#,
539 title = Escape(title),
540 )
541 })
542 }
543
544 let deprecation = import_def_id
546 .map_or_else(|| item.deprecation(tcx), |import_did| tcx.lookup_deprecation(import_did));
547 if let Some(depr) = deprecation {
548 let message = if depr.is_in_effect() { "Deprecated" } else { "Deprecation planned" };
549 write!(f, "{}", tag_html("deprecated", "", message))?;
550 }
551
552 let stability = import_def_id
555 .map_or_else(|| item.stability(tcx), |import_did| tcx.lookup_stability(import_did));
556 if stability.is_some_and(|s| s.is_unstable() && s.feature != sym::rustc_private) {
557 write!(f, "{}", tag_html("unstable", "", "Experimental"))?;
558 }
559
560 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
561 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
562 (cfg, _) => cfg.as_deref().cloned(),
563 };
564
565 debug!(
566 "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
567 name = item.name,
568 cfg = item.cfg,
569 parent_cfg = parent.cfg
570 );
571 if let Some(ref cfg) = cfg {
572 write!(
573 f,
574 "{}",
575 tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html())
576 )
577 } else {
578 Ok(())
579 }
580 })
581}
582
583fn item_function(cx: &Context<'_>, it: &clean::Item, f: &clean::Function) -> impl fmt::Display {
584 fmt::from_fn(|w| {
585 let tcx = cx.tcx();
586 let header = it.fn_header(tcx).expect("printing a function which isn't a function");
587 debug!(
588 "item_function/const: {:?} {:?} {:?} {:?}",
589 it.name,
590 &header.constness,
591 it.stable_since(tcx),
592 it.const_stability(tcx),
593 );
594 let constness = print_constness_with_space(
595 &header.constness,
596 it.stable_since(tcx),
597 it.const_stability(tcx),
598 );
599 let safety = header.safety.print_with_space();
600 let abi = print_abi_with_space(header.abi).to_string();
601 let asyncness = header.asyncness.print_with_space();
602 let visibility = visibility_print_with_space(it, cx).to_string();
603 let name = it.name.unwrap();
604
605 let generics_len = format!("{:#}", f.generics.print(cx)).len();
606 let header_len = "fn ".len()
607 + visibility.len()
608 + constness.len()
609 + asyncness.len()
610 + safety.len()
611 + abi.len()
612 + name.as_str().len()
613 + generics_len;
614
615 let notable_traits = notable_traits_button(&f.decl.output, cx).maybe_display();
616
617 wrap_item(w, |w| {
618 write!(
619 w,
620 "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \
621 {name}{generics}{decl}{notable_traits}{where_clause}",
622 attrs = render_attributes_in_pre(it, "", cx),
623 vis = visibility,
624 constness = constness,
625 asyncness = asyncness,
626 safety = safety,
627 abi = abi,
628 name = name,
629 generics = f.generics.print(cx),
630 where_clause =
631 print_where_clause(&f.generics, cx, 0, Ending::Newline).maybe_display(),
632 decl = f.decl.full_print(header_len, 0, cx),
633 )
634 })?;
635 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
636 })
637}
638
639fn item_trait(cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) -> impl fmt::Display {
640 fmt::from_fn(|w| {
641 let tcx = cx.tcx();
642 let bounds = bounds(&t.bounds, false, cx);
643 let required_types =
644 t.items.iter().filter(|m| m.is_required_associated_type()).collect::<Vec<_>>();
645 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
646 let required_consts =
647 t.items.iter().filter(|m| m.is_required_associated_const()).collect::<Vec<_>>();
648 let provided_consts =
649 t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
650 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
651 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
652 let count_types = required_types.len() + provided_types.len();
653 let count_consts = required_consts.len() + provided_consts.len();
654 let count_methods = required_methods.len() + provided_methods.len();
655 let must_implement_one_of_functions = tcx.trait_def(t.def_id).must_implement_one_of.clone();
656
657 wrap_item(w, |mut w| {
659 write!(
660 w,
661 "{attrs}{vis}{safety}{is_auto}trait {name}{generics}{bounds}",
662 attrs = render_attributes_in_pre(it, "", cx),
663 vis = visibility_print_with_space(it, cx),
664 safety = t.safety(tcx).print_with_space(),
665 is_auto = if t.is_auto(tcx) { "auto " } else { "" },
666 name = it.name.unwrap(),
667 generics = t.generics.print(cx),
668 )?;
669
670 if !t.generics.where_predicates.is_empty() {
671 write!(
672 w,
673 "{}",
674 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display()
675 )?;
676 } else {
677 w.write_char(' ')?;
678 }
679
680 if t.items.is_empty() {
681 w.write_str("{ }")
682 } else {
683 w.write_str("{\n")?;
685 let mut toggle = false;
686
687 if should_hide_fields(count_types) {
689 toggle = true;
690 toggle_open(
691 &mut w,
692 format_args!(
693 "{} associated items",
694 count_types + count_consts + count_methods
695 ),
696 );
697 }
698 for types in [&required_types, &provided_types] {
699 for t in types {
700 writeln!(
701 w,
702 "{};",
703 render_assoc_item(
704 t,
705 AssocItemLink::Anchor(None),
706 ItemType::Trait,
707 cx,
708 RenderMode::Normal,
709 )
710 )?;
711 }
712 }
713 if !toggle && should_hide_fields(count_types + count_consts) {
718 toggle = true;
719 toggle_open(
720 &mut w,
721 format_args!(
722 "{count_consts} associated constant{plural_const} and \
723 {count_methods} method{plural_method}",
724 plural_const = pluralize(count_consts),
725 plural_method = pluralize(count_methods),
726 ),
727 );
728 }
729 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
730 w.write_str("\n")?;
731 }
732 for consts in [&required_consts, &provided_consts] {
733 for c in consts {
734 writeln!(
735 w,
736 "{};",
737 render_assoc_item(
738 c,
739 AssocItemLink::Anchor(None),
740 ItemType::Trait,
741 cx,
742 RenderMode::Normal,
743 )
744 )?;
745 }
746 }
747 if !toggle && should_hide_fields(count_methods) {
748 toggle = true;
749 toggle_open(&mut w, format_args!("{count_methods} methods"));
750 }
751 if count_consts != 0 && count_methods != 0 {
752 w.write_str("\n")?;
753 }
754
755 if !required_methods.is_empty() {
756 writeln!(w, " // Required method{}", pluralize(required_methods.len()))?;
757 }
758 for (pos, m) in required_methods.iter().enumerate() {
759 writeln!(
760 w,
761 "{};",
762 render_assoc_item(
763 m,
764 AssocItemLink::Anchor(None),
765 ItemType::Trait,
766 cx,
767 RenderMode::Normal,
768 )
769 )?;
770
771 if pos < required_methods.len() - 1 {
772 w.write_str("<span class=\"item-spacer\"></span>")?;
773 }
774 }
775 if !required_methods.is_empty() && !provided_methods.is_empty() {
776 w.write_str("\n")?;
777 }
778
779 if !provided_methods.is_empty() {
780 writeln!(w, " // Provided method{}", pluralize(provided_methods.len()))?;
781 }
782 for (pos, m) in provided_methods.iter().enumerate() {
783 writeln!(
784 w,
785 "{} {{ ... }}",
786 render_assoc_item(
787 m,
788 AssocItemLink::Anchor(None),
789 ItemType::Trait,
790 cx,
791 RenderMode::Normal,
792 )
793 )?;
794
795 if pos < provided_methods.len() - 1 {
796 w.write_str("<span class=\"item-spacer\"></span>")?;
797 }
798 }
799 if toggle {
800 toggle_close(&mut w);
801 }
802 w.write_str("}")
803 }
804 })?;
805
806 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
808
809 fn trait_item(cx: &Context<'_>, m: &clean::Item, t: &clean::Item) -> impl fmt::Display {
810 fmt::from_fn(|w| {
811 let name = m.name.unwrap();
812 info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
813 let item_type = m.type_();
814 let id = cx.derive_id(format!("{item_type}.{name}"));
815
816 let content = document_full(m, cx, HeadingOffset::H5).to_string();
817
818 let toggled = !content.is_empty();
819 if toggled {
820 let method_toggle_class =
821 if item_type.is_method() { " method-toggle" } else { "" };
822 write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>")?;
823 }
824 write!(
825 w,
826 "<section id=\"{id}\" class=\"method\">\
827 {}\
828 <h4 class=\"code-header\">{}</h4></section>",
829 render_rightside(cx, m, RenderMode::Normal),
830 render_assoc_item(
831 m,
832 AssocItemLink::Anchor(Some(&id)),
833 ItemType::Impl,
834 cx,
835 RenderMode::Normal,
836 )
837 )?;
838 document_item_info(cx, m, Some(t)).render_into(w).unwrap();
839 if toggled {
840 write!(w, "</summary>{content}</details>")?;
841 }
842 Ok(())
843 })
844 }
845
846 if !required_consts.is_empty() {
847 write!(
848 w,
849 "{}",
850 write_section_heading(
851 "Required Associated Constants",
852 "required-associated-consts",
853 None,
854 "<div class=\"methods\">",
855 )
856 )?;
857 for t in required_consts {
858 write!(w, "{}", trait_item(cx, t, it))?;
859 }
860 w.write_str("</div>")?;
861 }
862 if !provided_consts.is_empty() {
863 write!(
864 w,
865 "{}",
866 write_section_heading(
867 "Provided Associated Constants",
868 "provided-associated-consts",
869 None,
870 "<div class=\"methods\">",
871 )
872 )?;
873 for t in provided_consts {
874 write!(w, "{}", trait_item(cx, t, it))?;
875 }
876 w.write_str("</div>")?;
877 }
878
879 if !required_types.is_empty() {
880 write!(
881 w,
882 "{}",
883 write_section_heading(
884 "Required Associated Types",
885 "required-associated-types",
886 None,
887 "<div class=\"methods\">",
888 )
889 )?;
890 for t in required_types {
891 write!(w, "{}", trait_item(cx, t, it))?;
892 }
893 w.write_str("</div>")?;
894 }
895 if !provided_types.is_empty() {
896 write!(
897 w,
898 "{}",
899 write_section_heading(
900 "Provided Associated Types",
901 "provided-associated-types",
902 None,
903 "<div class=\"methods\">",
904 )
905 )?;
906 for t in provided_types {
907 write!(w, "{}", trait_item(cx, t, it))?;
908 }
909 w.write_str("</div>")?;
910 }
911
912 if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
914 write!(
915 w,
916 "{}",
917 write_section_heading(
918 "Required Methods",
919 "required-methods",
920 None,
921 "<div class=\"methods\">",
922 )
923 )?;
924
925 if let Some(list) = must_implement_one_of_functions.as_deref() {
926 write!(
927 w,
928 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
929 fmt::from_fn(|f| list.iter().joined("`, `", f)),
930 )?;
931 }
932
933 for m in required_methods {
934 write!(w, "{}", trait_item(cx, m, it))?;
935 }
936 w.write_str("</div>")?;
937 }
938 if !provided_methods.is_empty() {
939 write!(
940 w,
941 "{}",
942 write_section_heading(
943 "Provided Methods",
944 "provided-methods",
945 None,
946 "<div class=\"methods\">",
947 )
948 )?;
949 for m in provided_methods {
950 write!(w, "{}", trait_item(cx, m, it))?;
951 }
952 w.write_str("</div>")?;
953 }
954
955 write!(
957 w,
958 "{}",
959 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
960 )?;
961
962 let mut extern_crates = FxIndexSet::default();
963
964 if !t.is_dyn_compatible(cx.tcx()) {
965 write!(
966 w,
967 "{}",
968 write_section_heading(
969 "Dyn Compatibility",
970 "dyn-compatibility",
971 None,
972 format!(
973 "<div class=\"dyn-compatibility-info\"><p>This trait is <b>not</b> \
974 <a href=\"{base}/reference/items/traits.html#dyn-compatibility\">dyn compatible</a>.</p>\
975 <p><i>In older versions of Rust, dyn compatibility was called \"object safety\", \
976 so this trait is not object safe.</i></p></div>",
977 base = crate::clean::utils::DOC_RUST_LANG_ORG_VERSION
978 ),
979 ),
980 )?;
981 }
982
983 if let Some(implementors) = cx.shared.cache.implementors.get(&it.item_id.expect_def_id()) {
984 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
987 for implementor in implementors {
988 if let Some(did) =
989 implementor.inner_impl().for_.without_borrowed_ref().def_id(&cx.shared.cache)
990 && !did.is_local()
991 {
992 extern_crates.insert(did.krate);
993 }
994 match implementor.inner_impl().for_.without_borrowed_ref() {
995 clean::Type::Path { path } if !path.is_assoc_ty() => {
996 let did = path.def_id();
997 let &mut (prev_did, ref mut has_duplicates) =
998 implementor_dups.entry(path.last()).or_insert((did, false));
999 if prev_did != did {
1000 *has_duplicates = true;
1001 }
1002 }
1003 _ => {}
1004 }
1005 }
1006
1007 let (local, mut foreign) =
1008 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
1009
1010 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1011 local.iter().partition(|i| i.inner_impl().kind.is_auto());
1012
1013 synthetic.sort_by_cached_key(|i| ImplString::new(i, cx));
1014 concrete.sort_by_cached_key(|i| ImplString::new(i, cx));
1015 foreign.sort_by_cached_key(|i| ImplString::new(i, cx));
1016
1017 if !foreign.is_empty() {
1018 write!(
1019 w,
1020 "{}",
1021 write_section_heading(
1022 "Implementations on Foreign Types",
1023 "foreign-impls",
1024 None,
1025 ""
1026 )
1027 )?;
1028
1029 for implementor in foreign {
1030 let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
1031 let assoc_link =
1032 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
1033 write!(
1034 w,
1035 "{}",
1036 render_impl(
1037 cx,
1038 implementor,
1039 it,
1040 assoc_link,
1041 RenderMode::Normal,
1042 None,
1043 &[],
1044 ImplRenderingParameters {
1045 show_def_docs: false,
1046 show_default_items: false,
1047 show_non_assoc_items: true,
1048 toggle_open_by_default: false,
1049 },
1050 )
1051 )?;
1052 }
1053 }
1054
1055 write!(
1056 w,
1057 "{}",
1058 write_section_heading(
1059 "Implementors",
1060 "implementors",
1061 None,
1062 "<div id=\"implementors-list\">",
1063 )
1064 )?;
1065 for implementor in concrete {
1066 write!(w, "{}", render_implementor(cx, implementor, it, &implementor_dups, &[]))?;
1067 }
1068 w.write_str("</div>")?;
1069
1070 if t.is_auto(tcx) {
1071 write!(
1072 w,
1073 "{}",
1074 write_section_heading(
1075 "Auto implementors",
1076 "synthetic-implementors",
1077 None,
1078 "<div id=\"synthetic-implementors-list\">",
1079 )
1080 )?;
1081 for implementor in synthetic {
1082 write!(
1083 w,
1084 "{}",
1085 render_implementor(
1086 cx,
1087 implementor,
1088 it,
1089 &implementor_dups,
1090 &collect_paths_for_type(
1091 implementor.inner_impl().for_.clone(),
1092 &cx.shared.cache,
1093 ),
1094 )
1095 )?;
1096 }
1097 w.write_str("</div>")?;
1098 }
1099 } else {
1100 write!(
1103 w,
1104 "{}",
1105 write_section_heading(
1106 "Implementors",
1107 "implementors",
1108 None,
1109 "<div id=\"implementors-list\"></div>",
1110 )
1111 )?;
1112
1113 if t.is_auto(tcx) {
1114 write!(
1115 w,
1116 "{}",
1117 write_section_heading(
1118 "Auto implementors",
1119 "synthetic-implementors",
1120 None,
1121 "<div id=\"synthetic-implementors-list\"></div>",
1122 )
1123 )?;
1124 }
1125 }
1126
1127 let mut js_src_path: UrlPartsBuilder =
1199 iter::repeat_n("..", cx.current.len()).chain(iter::once("trait.impl")).collect();
1200 if let Some(did) = it.item_id.as_def_id()
1201 && let get_extern = { || cx.shared.cache.external_paths.get(&did).map(|s| &s.0) }
1202 && let Some(fqp) = cx.shared.cache.exact_paths.get(&did).or_else(get_extern)
1203 {
1204 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1205 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1206 } else {
1207 js_src_path.extend(cx.current.iter().copied());
1208 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1209 }
1210 let extern_crates = fmt::from_fn(|f| {
1211 if !extern_crates.is_empty() {
1212 f.write_str(" data-ignore-extern-crates=\"")?;
1213 extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
1214 f.write_str("\"")?;
1215 }
1216 Ok(())
1217 });
1218 write!(
1219 w,
1220 "<script src=\"{src}\"{extern_crates} async></script>",
1221 src = js_src_path.finish()
1222 )
1223 })
1224}
1225
1226fn item_trait_alias(
1227 cx: &Context<'_>,
1228 it: &clean::Item,
1229 t: &clean::TraitAlias,
1230) -> impl fmt::Display {
1231 fmt::from_fn(|w| {
1232 wrap_item(w, |w| {
1233 write!(
1234 w,
1235 "{attrs}trait {name}{generics} = {bounds}{where_clause};",
1236 attrs = render_attributes_in_pre(it, "", cx),
1237 name = it.name.unwrap(),
1238 generics = t.generics.print(cx),
1239 bounds = bounds(&t.bounds, true, cx),
1240 where_clause =
1241 print_where_clause(&t.generics, cx, 0, Ending::NoNewline).maybe_display(),
1242 )
1243 })?;
1244
1245 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1246 write!(
1251 w,
1252 "{}",
1253 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1254 )
1255 })
1256}
1257
1258fn item_type_alias(cx: &Context<'_>, it: &clean::Item, t: &clean::TypeAlias) -> impl fmt::Display {
1259 fmt::from_fn(|w| {
1260 wrap_item(w, |w| {
1261 write!(
1262 w,
1263 "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
1264 attrs = render_attributes_in_pre(it, "", cx),
1265 vis = visibility_print_with_space(it, cx),
1266 name = it.name.unwrap(),
1267 generics = t.generics.print(cx),
1268 where_clause =
1269 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display(),
1270 type_ = t.type_.print(cx),
1271 )
1272 })?;
1273
1274 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1275
1276 if let Some(inner_type) = &t.inner_type {
1277 write!(w, "{}", write_section_heading("Aliased Type", "aliased-type", None, ""),)?;
1278
1279 match inner_type {
1280 clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive } => {
1281 let variants_iter = || variants.iter().filter(|i| !i.is_stripped());
1282 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1283 let enum_def_id = ty.ty_adt_def().unwrap().did();
1284
1285 wrap_item(w, |w| {
1286 let variants_len = variants.len();
1287 let variants_count = variants_iter().count();
1288 let has_stripped_entries = variants_len != variants_count;
1289
1290 write!(
1291 w,
1292 "enum {}{}{}",
1293 it.name.unwrap(),
1294 t.generics.print(cx),
1295 render_enum_fields(
1296 cx,
1297 Some(&t.generics),
1298 variants,
1299 variants_count,
1300 has_stripped_entries,
1301 *is_non_exhaustive,
1302 enum_def_id,
1303 )
1304 )
1305 })?;
1306 write!(w, "{}", item_variants(cx, it, variants, enum_def_id))?;
1307 }
1308 clean::TypeAliasInnerType::Union { fields } => {
1309 wrap_item(w, |w| {
1310 let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
1311 let has_stripped_fields = fields.len() != fields_count;
1312
1313 write!(
1314 w,
1315 "union {}{}{}",
1316 it.name.unwrap(),
1317 t.generics.print(cx),
1318 render_struct_fields(
1319 Some(&t.generics),
1320 None,
1321 fields,
1322 "",
1323 true,
1324 has_stripped_fields,
1325 cx,
1326 ),
1327 )
1328 })?;
1329 write!(w, "{}", item_fields(cx, it, fields, None))?;
1330 }
1331 clean::TypeAliasInnerType::Struct { ctor_kind, fields } => {
1332 wrap_item(w, |w| {
1333 let fields_count = fields.iter().filter(|i| !i.is_stripped()).count();
1334 let has_stripped_fields = fields.len() != fields_count;
1335
1336 write!(
1337 w,
1338 "struct {}{}{}",
1339 it.name.unwrap(),
1340 t.generics.print(cx),
1341 render_struct_fields(
1342 Some(&t.generics),
1343 *ctor_kind,
1344 fields,
1345 "",
1346 true,
1347 has_stripped_fields,
1348 cx,
1349 ),
1350 )
1351 })?;
1352 write!(w, "{}", item_fields(cx, it, fields, None))?;
1353 }
1354 }
1355 }
1356
1357 let def_id = it.item_id.expect_def_id();
1358 write!(
1363 w,
1364 "{}{}",
1365 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1366 document_type_layout(cx, def_id)
1367 )?;
1368
1369 let cache = &cx.shared.cache;
1442 if let Some(target_did) = t.type_.def_id(cache)
1443 && let get_extern = { || cache.external_paths.get(&target_did) }
1444 && let Some(&(ref target_fqp, target_type)) =
1445 cache.paths.get(&target_did).or_else(get_extern)
1446 && target_type.is_adt() && let Some(self_did) = it.item_id.as_def_id()
1448 && let get_local = { || cache.paths.get(&self_did).map(|(p, _)| p) }
1449 && let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local)
1450 {
1451 let mut js_src_path: UrlPartsBuilder =
1452 iter::repeat_n("..", cx.current.len()).chain(iter::once("type.impl")).collect();
1453 js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
1454 js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
1455 let self_path = fmt::from_fn(|f| self_fqp.iter().joined("::", f));
1456 write!(
1457 w,
1458 "<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
1459 src = js_src_path.finish(),
1460 )?;
1461 }
1462 Ok(())
1463 })
1464}
1465
1466fn item_union(cx: &Context<'_>, it: &clean::Item, s: &clean::Union) -> impl fmt::Display {
1467 item_template!(
1468 #[template(path = "item_union.html")]
1469 struct ItemUnion<'a, 'cx> {
1470 cx: &'a Context<'cx>,
1471 it: &'a clean::Item,
1472 s: &'a clean::Union,
1473 },
1474 methods = [document, document_type_layout, render_attributes_in_pre, render_assoc_items]
1475 );
1476
1477 impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
1478 fn render_union(&self) -> impl Display {
1479 render_union(self.it, Some(&self.s.generics), &self.s.fields, self.cx)
1480 }
1481
1482 fn document_field(&self, field: &'a clean::Item) -> impl Display {
1483 document(self.cx, field, Some(self.it), HeadingOffset::H3)
1484 }
1485
1486 fn stability_field(&self, field: &clean::Item) -> Option<String> {
1487 field.stability_class(self.cx.tcx())
1488 }
1489
1490 fn print_ty(&self, ty: &'a clean::Type) -> impl Display {
1491 ty.print(self.cx)
1492 }
1493
1494 fn fields_iter(
1495 &self,
1496 ) -> iter::Peekable<impl Iterator<Item = (&'a clean::Item, &'a clean::Type)>> {
1497 self.s
1498 .fields
1499 .iter()
1500 .filter_map(|f| match f.kind {
1501 clean::StructFieldItem(ref ty) => Some((f, ty)),
1502 _ => None,
1503 })
1504 .peekable()
1505 }
1506 }
1507
1508 fmt::from_fn(|w| {
1509 ItemUnion { cx, it, s }.render_into(w).unwrap();
1510 Ok(())
1511 })
1512}
1513
1514fn print_tuple_struct_fields(cx: &Context<'_>, s: &[clean::Item]) -> impl Display {
1515 fmt::from_fn(|f| {
1516 if !s.is_empty()
1517 && s.iter().all(|field| {
1518 matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
1519 })
1520 {
1521 return f.write_str("<span class=\"comment\">/* private fields */</span>");
1522 }
1523
1524 s.iter()
1525 .map(|ty| {
1526 fmt::from_fn(|f| match ty.kind {
1527 clean::StrippedItem(box clean::StructFieldItem(_)) => f.write_str("_"),
1528 clean::StructFieldItem(ref ty) => write!(f, "{}", ty.print(cx)),
1529 _ => unreachable!(),
1530 })
1531 })
1532 .joined(", ", f)
1533 })
1534}
1535
1536fn item_enum(cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) -> impl fmt::Display {
1537 fmt::from_fn(|w| {
1538 let count_variants = e.variants().count();
1539 wrap_item(w, |w| {
1540 render_attributes_in_code(w, it, cx);
1541 write!(
1542 w,
1543 "{}enum {}{}{}",
1544 visibility_print_with_space(it, cx),
1545 it.name.unwrap(),
1546 e.generics.print(cx),
1547 render_enum_fields(
1548 cx,
1549 Some(&e.generics),
1550 &e.variants,
1551 count_variants,
1552 e.has_stripped_entries(),
1553 it.is_non_exhaustive(),
1554 it.def_id().unwrap(),
1555 ),
1556 )
1557 })?;
1558
1559 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1560
1561 if count_variants != 0 {
1562 write!(w, "{}", item_variants(cx, it, &e.variants, it.def_id().unwrap()))?;
1563 }
1564 let def_id = it.item_id.expect_def_id();
1565 write!(
1566 w,
1567 "{}{}",
1568 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1569 document_type_layout(cx, def_id)
1570 )
1571 })
1572}
1573
1574fn should_show_enum_discriminant(
1578 cx: &Context<'_>,
1579 enum_def_id: DefId,
1580 variants: &IndexVec<VariantIdx, clean::Item>,
1581) -> bool {
1582 let mut has_variants_with_value = false;
1583 for variant in variants {
1584 if let clean::VariantItem(ref var) = variant.kind
1585 && matches!(var.kind, clean::VariantKind::CLike)
1586 {
1587 has_variants_with_value |= var.discriminant.is_some();
1588 } else {
1589 return false;
1590 }
1591 }
1592 if has_variants_with_value {
1593 return true;
1594 }
1595 let repr = cx.tcx().adt_def(enum_def_id).repr();
1596 repr.c() || repr.int.is_some()
1597}
1598
1599fn display_c_like_variant(
1600 cx: &Context<'_>,
1601 item: &clean::Item,
1602 variant: &clean::Variant,
1603 index: VariantIdx,
1604 should_show_enum_discriminant: bool,
1605 enum_def_id: DefId,
1606) -> impl fmt::Display {
1607 fmt::from_fn(move |w| {
1608 let name = item.name.unwrap();
1609 if let Some(ref value) = variant.discriminant {
1610 write!(w, "{} = {}", name.as_str(), value.value(cx.tcx(), true))?;
1611 } else if should_show_enum_discriminant {
1612 let adt_def = cx.tcx().adt_def(enum_def_id);
1613 let discr = adt_def.discriminant_for_variant(cx.tcx(), index);
1614 if discr.ty.is_signed() {
1615 write!(w, "{} = {}", name.as_str(), discr.val as i128)?;
1616 } else {
1617 write!(w, "{} = {}", name.as_str(), discr.val)?;
1618 }
1619 } else {
1620 write!(w, "{name}")?;
1621 }
1622 Ok(())
1623 })
1624}
1625
1626fn render_enum_fields(
1627 cx: &Context<'_>,
1628 g: Option<&clean::Generics>,
1629 variants: &IndexVec<VariantIdx, clean::Item>,
1630 count_variants: usize,
1631 has_stripped_entries: bool,
1632 is_non_exhaustive: bool,
1633 enum_def_id: DefId,
1634) -> impl fmt::Display {
1635 fmt::from_fn(move |w| {
1636 let should_show_enum_discriminant =
1637 should_show_enum_discriminant(cx, enum_def_id, variants);
1638 if let Some(generics) = g
1639 && let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline)
1640 {
1641 write!(w, "{where_clause}")?;
1642 } else {
1643 w.write_char(' ')?;
1645 }
1646
1647 let variants_stripped = has_stripped_entries;
1648 if count_variants == 0 && !variants_stripped {
1649 w.write_str("{}")
1650 } else {
1651 w.write_str("{\n")?;
1652 let toggle = should_hide_fields(count_variants);
1653 if toggle {
1654 toggle_open(&mut *w, format_args!("{count_variants} variants"));
1655 }
1656 const TAB: &str = " ";
1657 for (index, v) in variants.iter_enumerated() {
1658 if v.is_stripped() {
1659 continue;
1660 }
1661 w.write_str(TAB)?;
1662 match v.kind {
1663 clean::VariantItem(ref var) => match var.kind {
1664 clean::VariantKind::CLike => {
1665 write!(
1666 w,
1667 "{}",
1668 display_c_like_variant(
1669 cx,
1670 v,
1671 var,
1672 index,
1673 should_show_enum_discriminant,
1674 enum_def_id,
1675 )
1676 )?;
1677 }
1678 clean::VariantKind::Tuple(ref s) => {
1679 write!(w, "{}({})", v.name.unwrap(), print_tuple_struct_fields(cx, s))?;
1680 }
1681 clean::VariantKind::Struct(ref s) => {
1682 write!(
1683 w,
1684 "{}",
1685 render_struct(v, None, None, &s.fields, TAB, false, cx)
1686 )?;
1687 }
1688 },
1689 _ => unreachable!(),
1690 }
1691 w.write_str(",\n")?;
1692 }
1693
1694 if variants_stripped && !is_non_exhaustive {
1695 w.write_str(" <span class=\"comment\">// some variants omitted</span>\n")?;
1696 }
1697 if toggle {
1698 toggle_close(&mut *w);
1699 }
1700 w.write_str("}")
1701 }
1702 })
1703}
1704
1705fn item_variants(
1706 cx: &Context<'_>,
1707 it: &clean::Item,
1708 variants: &IndexVec<VariantIdx, clean::Item>,
1709 enum_def_id: DefId,
1710) -> impl fmt::Display {
1711 fmt::from_fn(move |w| {
1712 let tcx = cx.tcx();
1713 write!(
1714 w,
1715 "{}",
1716 write_section_heading(
1717 &format!("Variants{}", document_non_exhaustive_header(it)),
1718 "variants",
1719 Some("variants"),
1720 format!("{}<div class=\"variants\">", document_non_exhaustive(it)),
1721 ),
1722 )?;
1723
1724 let should_show_enum_discriminant =
1725 should_show_enum_discriminant(cx, enum_def_id, variants);
1726 for (index, variant) in variants.iter_enumerated() {
1727 if variant.is_stripped() {
1728 continue;
1729 }
1730 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1731 write!(
1732 w,
1733 "<section id=\"{id}\" class=\"variant\">\
1734 <a href=\"#{id}\" class=\"anchor\">§</a>\
1735 {}\
1736 <h3 class=\"code-header\">",
1737 render_stability_since_raw_with_extra(
1738 variant.stable_since(tcx),
1739 variant.const_stability(tcx),
1740 " rightside",
1741 )
1742 .maybe_display()
1743 )?;
1744 if let clean::VariantItem(ref var) = variant.kind
1745 && let clean::VariantKind::CLike = var.kind
1746 {
1747 write!(
1748 w,
1749 "{}",
1750 display_c_like_variant(
1751 cx,
1752 variant,
1753 var,
1754 index,
1755 should_show_enum_discriminant,
1756 enum_def_id,
1757 )
1758 )?;
1759 } else {
1760 w.write_str(variant.name.unwrap().as_str())?;
1761 }
1762
1763 let clean::VariantItem(variant_data) = &variant.kind else { unreachable!() };
1764
1765 if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
1766 write!(w, "({})", print_tuple_struct_fields(cx, s))?;
1767 }
1768 w.write_str("</h3></section>")?;
1769
1770 write!(w, "{}", document(cx, variant, Some(it), HeadingOffset::H4))?;
1771
1772 let heading_and_fields = match &variant_data.kind {
1773 clean::VariantKind::Struct(s) => {
1774 if s.fields.iter().any(|f| !f.is_doc_hidden()) {
1776 Some(("Fields", &s.fields))
1777 } else {
1778 None
1779 }
1780 }
1781 clean::VariantKind::Tuple(fields) => {
1782 if fields.iter().any(|f| !f.doc_value().is_empty()) {
1785 Some(("Tuple Fields", fields))
1786 } else {
1787 None
1788 }
1789 }
1790 clean::VariantKind::CLike => None,
1791 };
1792
1793 if let Some((heading, fields)) = heading_and_fields {
1794 let variant_id =
1795 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1796 write!(
1797 w,
1798 "<div class=\"sub-variant\" id=\"{variant_id}\">\
1799 <h4>{heading}</h4>\
1800 {}",
1801 document_non_exhaustive(variant)
1802 )?;
1803 for field in fields {
1804 match field.kind {
1805 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1806 clean::StructFieldItem(ref ty) => {
1807 let id = cx.derive_id(format!(
1808 "variant.{}.field.{}",
1809 variant.name.unwrap(),
1810 field.name.unwrap()
1811 ));
1812 write!(
1813 w,
1814 "<div class=\"sub-variant-field\">\
1815 <span id=\"{id}\" class=\"section-header\">\
1816 <a href=\"#{id}\" class=\"anchor field\">§</a>\
1817 <code>{f}: {t}</code>\
1818 </span>\
1819 {doc}\
1820 </div>",
1821 f = field.name.unwrap(),
1822 t = ty.print(cx),
1823 doc = document(cx, field, Some(variant), HeadingOffset::H5),
1824 )?;
1825 }
1826 _ => unreachable!(),
1827 }
1828 }
1829 w.write_str("</div>")?;
1830 }
1831 }
1832 w.write_str("</div>")
1833 })
1834}
1835
1836fn item_macro(cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) -> impl fmt::Display {
1837 fmt::from_fn(|w| {
1838 wrap_item(w, |w| {
1839 if !t.macro_rules {
1841 write!(w, "{}", visibility_print_with_space(it, cx))?;
1842 }
1843 write!(w, "{}", Escape(&t.source))
1844 })?;
1845 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
1846 })
1847}
1848
1849fn item_proc_macro(cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) -> impl fmt::Display {
1850 fmt::from_fn(|w| {
1851 wrap_item(w, |w| {
1852 let name = it.name.expect("proc-macros always have names");
1853 match m.kind {
1854 MacroKind::Bang => {
1855 write!(w, "{name}!() {{ <span class=\"comment\">/* proc-macro */</span> }}")?;
1856 }
1857 MacroKind::Attr => {
1858 write!(w, "#[{name}]")?;
1859 }
1860 MacroKind::Derive => {
1861 write!(w, "#[derive({name})]")?;
1862 if !m.helpers.is_empty() {
1863 w.write_str(
1864 "\n{\n \
1865 <span class=\"comment\">// Attributes available to this derive:</span>\n",
1866 )?;
1867 for attr in &m.helpers {
1868 writeln!(w, " #[{attr}]")?;
1869 }
1870 w.write_str("}\n")?;
1871 }
1872 }
1873 }
1874 fmt::Result::Ok(())
1875 })?;
1876 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
1877 })
1878}
1879
1880fn item_primitive(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
1881 fmt::from_fn(|w| {
1882 let def_id = it.item_id.expect_def_id();
1883 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1884 if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
1885 write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All))?;
1886 } else {
1887 let (concrete, synthetic, blanket_impl) =
1890 get_filtered_impls_for_reference(&cx.shared, it);
1891
1892 render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
1893 }
1894 Ok(())
1895 })
1896}
1897
1898fn item_constant(
1899 cx: &Context<'_>,
1900 it: &clean::Item,
1901 generics: &clean::Generics,
1902 ty: &clean::Type,
1903 c: &clean::ConstantKind,
1904) -> impl fmt::Display {
1905 fmt::from_fn(|w| {
1906 wrap_item(w, |w| {
1907 let tcx = cx.tcx();
1908 render_attributes_in_code(w, it, cx);
1909
1910 write!(
1911 w,
1912 "{vis}const {name}{generics}: {typ}{where_clause}",
1913 vis = visibility_print_with_space(it, cx),
1914 name = it.name.unwrap(),
1915 generics = generics.print(cx),
1916 typ = ty.print(cx),
1917 where_clause =
1918 print_where_clause(generics, cx, 0, Ending::NoNewline).maybe_display(),
1919 )?;
1920
1921 let value = c.value(tcx);
1931 let is_literal = c.is_literal(tcx);
1932 let expr = c.expr(tcx);
1933 if value.is_some() || is_literal {
1934 write!(w, " = {expr};", expr = Escape(&expr))?;
1935 } else {
1936 w.write_str(";")?;
1937 }
1938
1939 if !is_literal {
1940 if let Some(value) = &value {
1941 let value_lowercase = value.to_lowercase();
1942 let expr_lowercase = expr.to_lowercase();
1943
1944 if value_lowercase != expr_lowercase
1945 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1946 {
1947 write!(w, " // {value}", value = Escape(value))?;
1948 }
1949 }
1950 }
1951 Ok::<(), fmt::Error>(())
1952 })?;
1953
1954 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
1955 })
1956}
1957
1958fn item_struct(cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) -> impl fmt::Display {
1959 fmt::from_fn(|w| {
1960 wrap_item(w, |w| {
1961 render_attributes_in_code(w, it, cx);
1962 write!(
1963 w,
1964 "{}",
1965 render_struct(it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx)
1966 )
1967 })?;
1968
1969 let def_id = it.item_id.expect_def_id();
1970
1971 write!(
1972 w,
1973 "{}{}{}{}",
1974 document(cx, it, None, HeadingOffset::H2),
1975 item_fields(cx, it, &s.fields, s.ctor_kind),
1976 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1977 document_type_layout(cx, def_id),
1978 )
1979 })
1980}
1981
1982fn item_fields(
1983 cx: &Context<'_>,
1984 it: &clean::Item,
1985 fields: &[clean::Item],
1986 ctor_kind: Option<CtorKind>,
1987) -> impl fmt::Display {
1988 fmt::from_fn(move |w| {
1989 let mut fields = fields
1990 .iter()
1991 .filter_map(|f| match f.kind {
1992 clean::StructFieldItem(ref ty) => Some((f, ty)),
1993 _ => None,
1994 })
1995 .peekable();
1996 if let None | Some(CtorKind::Fn) = ctor_kind {
1997 if fields.peek().is_some() {
1998 let title = format!(
1999 "{}{}",
2000 if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
2001 document_non_exhaustive_header(it),
2002 );
2003 write!(
2004 w,
2005 "{}",
2006 write_section_heading(
2007 &title,
2008 "fields",
2009 Some("fields"),
2010 document_non_exhaustive(it)
2011 )
2012 )?;
2013 for (index, (field, ty)) in fields.enumerate() {
2014 let field_name = field
2015 .name
2016 .map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
2017 let id =
2018 cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField));
2019 write!(
2020 w,
2021 "<span id=\"{id}\" class=\"{item_type} section-header\">\
2022 <a href=\"#{id}\" class=\"anchor field\">§</a>\
2023 <code>{field_name}: {ty}</code>\
2024 </span>\
2025 {doc}",
2026 item_type = ItemType::StructField,
2027 ty = ty.print(cx),
2028 doc = document(cx, field, Some(it), HeadingOffset::H3),
2029 )?;
2030 }
2031 }
2032 }
2033 Ok(())
2034 })
2035}
2036
2037fn item_static(
2038 cx: &Context<'_>,
2039 it: &clean::Item,
2040 s: &clean::Static,
2041 safety: Option<hir::Safety>,
2042) -> impl fmt::Display {
2043 fmt::from_fn(move |w| {
2044 wrap_item(w, |w| {
2045 render_attributes_in_code(w, it, cx);
2046 write!(
2047 w,
2048 "{vis}{safe}static {mutability}{name}: {typ}",
2049 vis = visibility_print_with_space(it, cx),
2050 safe = safety.map(|safe| safe.prefix_str()).unwrap_or(""),
2051 mutability = s.mutability.print_with_space(),
2052 name = it.name.unwrap(),
2053 typ = s.type_.print(cx)
2054 )
2055 })?;
2056
2057 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
2058 })
2059}
2060
2061fn item_foreign_type(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
2062 fmt::from_fn(|w| {
2063 wrap_item(w, |w| {
2064 w.write_str("extern {\n")?;
2065 render_attributes_in_code(w, it, cx);
2066 write!(w, " {}type {};\n}}", visibility_print_with_space(it, cx), it.name.unwrap(),)
2067 })?;
2068
2069 write!(
2070 w,
2071 "{}{}",
2072 document(cx, it, None, HeadingOffset::H2),
2073 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
2074 )
2075 })
2076}
2077
2078fn item_keyword(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
2079 document(cx, it, None, HeadingOffset::H2)
2080}
2081
2082pub(crate) fn compare_names(left: &str, right: &str) -> Ordering {
2088 let mut left = left.chars().peekable();
2089 let mut right = right.chars().peekable();
2090
2091 loop {
2092 let (l, r) = match (left.next(), right.next()) {
2094 (None, None) => return Ordering::Equal,
2096 (None, Some(_)) => return Ordering::Less,
2098 (Some(_), None) => return Ordering::Greater,
2099 (Some(l), Some(r)) => (l, r),
2100 };
2101 let next_ordering = match (l.to_digit(10), r.to_digit(10)) {
2102 (None, None) => Ord::cmp(&l, &r),
2104 (None, Some(_)) => Ordering::Greater,
2107 (Some(_), None) => Ordering::Less,
2108 (Some(l), Some(r)) => {
2110 if l == 0 || r == 0 {
2111 let ordering = Ord::cmp(&l, &r);
2113 if ordering != Ordering::Equal {
2114 return ordering;
2115 }
2116 loop {
2117 let (l, r) = match (left.peek(), right.peek()) {
2119 (None, None) => return Ordering::Equal,
2121 (None, Some(_)) => return Ordering::Less,
2123 (Some(_), None) => return Ordering::Greater,
2124 (Some(l), Some(r)) => (l, r),
2125 };
2126 match (l.to_digit(10), r.to_digit(10)) {
2128 (None, None) => break Ordering::Equal,
2130 (None, Some(_)) => return Ordering::Less,
2132 (Some(_), None) => return Ordering::Greater,
2133 (Some(l), Some(r)) => {
2135 left.next();
2136 right.next();
2137 let ordering = Ord::cmp(&l, &r);
2138 if ordering != Ordering::Equal {
2139 return ordering;
2140 }
2141 }
2142 }
2143 }
2144 } else {
2145 let mut same_length_ordering = Ord::cmp(&l, &r);
2147 loop {
2148 let (l, r) = match (left.peek(), right.peek()) {
2150 (None, None) => return same_length_ordering,
2152 (None, Some(_)) => return Ordering::Less,
2154 (Some(_), None) => return Ordering::Greater,
2155 (Some(l), Some(r)) => (l, r),
2156 };
2157 match (l.to_digit(10), r.to_digit(10)) {
2159 (None, None) => break same_length_ordering,
2161 (None, Some(_)) => return Ordering::Less,
2163 (Some(_), None) => return Ordering::Greater,
2164 (Some(l), Some(r)) => {
2166 left.next();
2167 right.next();
2168 same_length_ordering = same_length_ordering.then(Ord::cmp(&l, &r));
2169 }
2170 }
2171 }
2172 }
2173 }
2174 };
2175 if next_ordering != Ordering::Equal {
2176 return next_ordering;
2177 }
2178 }
2179}
2180
2181pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
2182 let mut s = join_with_double_colon(&cx.current);
2183 s.push_str("::");
2184 s.push_str(item.name.unwrap().as_str());
2185 s
2186}
2187
2188pub(super) fn item_path(ty: ItemType, name: &str) -> impl Display {
2189 fmt::from_fn(move |f| match ty {
2190 ItemType::Module => write!(f, "{}index.html", ensure_trailing_slash(name)),
2191 _ => write!(f, "{ty}.{name}.html"),
2192 })
2193}
2194
2195fn bounds(bounds: &[clean::GenericBound], trait_alias: bool, cx: &Context<'_>) -> impl Display {
2196 (!bounds.is_empty())
2197 .then_some(fmt::from_fn(move |f| {
2198 let has_lots_of_bounds = bounds.len() > 2;
2199 let inter_str = if has_lots_of_bounds { "\n + " } else { " + " };
2200 if !trait_alias {
2201 if has_lots_of_bounds {
2202 f.write_str(":\n ")?;
2203 } else {
2204 f.write_str(": ")?;
2205 }
2206 }
2207
2208 bounds.iter().map(|p| p.print(cx)).joined(inter_str, f)
2209 }))
2210 .maybe_display()
2211}
2212
2213fn wrap_item<W, F, T>(w: &mut W, f: F) -> T
2214where
2215 W: fmt::Write,
2216 F: FnOnce(&mut W) -> T,
2217{
2218 write!(w, r#"<pre class="rust item-decl"><code>"#).unwrap();
2219 let res = f(w);
2220 write!(w, "</code></pre>").unwrap();
2221 res
2222}
2223
2224#[derive(PartialEq, Eq)]
2225struct ImplString(String);
2226
2227impl ImplString {
2228 fn new(i: &Impl, cx: &Context<'_>) -> ImplString {
2229 ImplString(format!("{}", i.inner_impl().print(false, cx)))
2230 }
2231}
2232
2233impl PartialOrd for ImplString {
2234 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2235 Some(Ord::cmp(self, other))
2236 }
2237}
2238
2239impl Ord for ImplString {
2240 fn cmp(&self, other: &Self) -> Ordering {
2241 compare_names(&self.0, &other.0)
2242 }
2243}
2244
2245fn render_implementor(
2246 cx: &Context<'_>,
2247 implementor: &Impl,
2248 trait_: &clean::Item,
2249 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2250 aliases: &[String],
2251) -> impl fmt::Display {
2252 let use_absolute = match implementor.inner_impl().for_ {
2255 clean::Type::Path { ref path, .. }
2256 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
2257 if !path.is_assoc_ty() =>
2258 {
2259 implementor_dups[&path.last()].1
2260 }
2261 _ => false,
2262 };
2263 render_impl(
2264 cx,
2265 implementor,
2266 trait_,
2267 AssocItemLink::Anchor(None),
2268 RenderMode::Normal,
2269 Some(use_absolute),
2270 aliases,
2271 ImplRenderingParameters {
2272 show_def_docs: false,
2273 show_default_items: false,
2274 show_non_assoc_items: false,
2275 toggle_open_by_default: false,
2276 },
2277 )
2278}
2279
2280fn render_union(
2281 it: &clean::Item,
2282 g: Option<&clean::Generics>,
2283 fields: &[clean::Item],
2284 cx: &Context<'_>,
2285) -> impl Display {
2286 fmt::from_fn(move |mut f| {
2287 write!(f, "{}union {}", visibility_print_with_space(it, cx), it.name.unwrap(),)?;
2288
2289 let where_displayed = if let Some(generics) = g {
2290 write!(f, "{}", generics.print(cx))?;
2291 if let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline) {
2292 write!(f, "{where_clause}")?;
2293 true
2294 } else {
2295 false
2296 }
2297 } else {
2298 false
2299 };
2300
2301 if !where_displayed {
2303 f.write_str(" ")?;
2304 }
2305
2306 writeln!(f, "{{")?;
2307 let count_fields =
2308 fields.iter().filter(|field| matches!(field.kind, clean::StructFieldItem(..))).count();
2309 let toggle = should_hide_fields(count_fields);
2310 if toggle {
2311 toggle_open(&mut f, format_args!("{count_fields} fields"));
2312 }
2313
2314 for field in fields {
2315 if let clean::StructFieldItem(ref ty) = field.kind {
2316 writeln!(
2317 f,
2318 " {}{}: {},",
2319 visibility_print_with_space(field, cx),
2320 field.name.unwrap(),
2321 ty.print(cx)
2322 )?;
2323 }
2324 }
2325
2326 if it.has_stripped_entries().unwrap() {
2327 writeln!(f, " <span class=\"comment\">/* private fields */</span>")?;
2328 }
2329 if toggle {
2330 toggle_close(&mut f);
2331 }
2332 f.write_str("}").unwrap();
2333 Ok(())
2334 })
2335}
2336
2337fn render_struct(
2338 it: &clean::Item,
2339 g: Option<&clean::Generics>,
2340 ty: Option<CtorKind>,
2341 fields: &[clean::Item],
2342 tab: &str,
2343 structhead: bool,
2344 cx: &Context<'_>,
2345) -> impl fmt::Display {
2346 fmt::from_fn(move |w| {
2347 write!(
2348 w,
2349 "{}{}{}",
2350 visibility_print_with_space(it, cx),
2351 if structhead { "struct " } else { "" },
2352 it.name.unwrap()
2353 )?;
2354 if let Some(g) = g {
2355 write!(w, "{}", g.print(cx))?;
2356 }
2357 write!(
2358 w,
2359 "{}",
2360 render_struct_fields(
2361 g,
2362 ty,
2363 fields,
2364 tab,
2365 structhead,
2366 it.has_stripped_entries().unwrap_or(false),
2367 cx,
2368 )
2369 )
2370 })
2371}
2372
2373fn render_struct_fields(
2374 g: Option<&clean::Generics>,
2375 ty: Option<CtorKind>,
2376 fields: &[clean::Item],
2377 tab: &str,
2378 structhead: bool,
2379 has_stripped_entries: bool,
2380 cx: &Context<'_>,
2381) -> impl fmt::Display {
2382 fmt::from_fn(move |w| {
2383 match ty {
2384 None => {
2385 let where_displayed = if let Some(generics) = g
2386 && let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline)
2387 {
2388 write!(w, "{where_clause}")?;
2389 true
2390 } else {
2391 false
2392 };
2393
2394 if !where_displayed {
2396 w.write_str(" {")?;
2397 } else {
2398 w.write_str("{")?;
2399 }
2400 let count_fields =
2401 fields.iter().filter(|f| matches!(f.kind, clean::StructFieldItem(..))).count();
2402 let has_visible_fields = count_fields > 0;
2403 let toggle = should_hide_fields(count_fields);
2404 if toggle {
2405 toggle_open(&mut *w, format_args!("{count_fields} fields"));
2406 }
2407 for field in fields {
2408 if let clean::StructFieldItem(ref ty) = field.kind {
2409 write!(
2410 w,
2411 "\n{tab} {vis}{name}: {ty},",
2412 vis = visibility_print_with_space(field, cx),
2413 name = field.name.unwrap(),
2414 ty = ty.print(cx)
2415 )?;
2416 }
2417 }
2418
2419 if has_visible_fields {
2420 if has_stripped_entries {
2421 write!(
2422 w,
2423 "\n{tab} <span class=\"comment\">/* private fields */</span>"
2424 )?;
2425 }
2426 write!(w, "\n{tab}")?;
2427 } else if has_stripped_entries {
2428 write!(w, " <span class=\"comment\">/* private fields */</span> ")?;
2429 }
2430 if toggle {
2431 toggle_close(&mut *w);
2432 }
2433 w.write_str("}")?;
2434 }
2435 Some(CtorKind::Fn) => {
2436 w.write_str("(")?;
2437 if !fields.is_empty()
2438 && fields.iter().all(|field| {
2439 matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
2440 })
2441 {
2442 write!(w, "<span class=\"comment\">/* private fields */</span>")?;
2443 } else {
2444 for (i, field) in fields.iter().enumerate() {
2445 if i > 0 {
2446 w.write_str(", ")?;
2447 }
2448 match field.kind {
2449 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2450 write!(w, "_")?;
2451 }
2452 clean::StructFieldItem(ref ty) => {
2453 write!(
2454 w,
2455 "{}{}",
2456 visibility_print_with_space(field, cx),
2457 ty.print(cx)
2458 )?;
2459 }
2460 _ => unreachable!(),
2461 }
2462 }
2463 }
2464 w.write_str(")")?;
2465 if let Some(g) = g {
2466 write!(
2467 w,
2468 "{}",
2469 print_where_clause(g, cx, 0, Ending::NoNewline).maybe_display()
2470 )?;
2471 }
2472 if structhead {
2474 w.write_str(";")?;
2475 }
2476 }
2477 Some(CtorKind::Const) => {
2478 if let Some(g) = g {
2480 write!(
2481 w,
2482 "{}",
2483 print_where_clause(g, cx, 0, Ending::NoNewline).maybe_display()
2484 )?;
2485 }
2486 w.write_str(";")?;
2487 }
2488 }
2489 Ok(())
2490 })
2491}
2492
2493fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2494 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2495}
2496
2497fn document_non_exhaustive(item: &clean::Item) -> impl Display {
2498 fmt::from_fn(|f| {
2499 if item.is_non_exhaustive() {
2500 write!(
2501 f,
2502 "<details class=\"toggle non-exhaustive\">\
2503 <summary class=\"hideme\"><span>{}</span></summary>\
2504 <div class=\"docblock\">",
2505 {
2506 if item.is_struct() {
2507 "This struct is marked as non-exhaustive"
2508 } else if item.is_enum() {
2509 "This enum is marked as non-exhaustive"
2510 } else if item.is_variant() {
2511 "This variant is marked as non-exhaustive"
2512 } else {
2513 "This type is marked as non-exhaustive"
2514 }
2515 }
2516 )?;
2517
2518 if item.is_struct() {
2519 f.write_str(
2520 "Non-exhaustive structs could have additional fields added in future. \
2521 Therefore, non-exhaustive structs cannot be constructed in external crates \
2522 using the traditional <code>Struct { .. }</code> syntax; cannot be \
2523 matched against without a wildcard <code>..</code>; and \
2524 struct update syntax will not work.",
2525 )?;
2526 } else if item.is_enum() {
2527 f.write_str(
2528 "Non-exhaustive enums could have additional variants added in future. \
2529 Therefore, when matching against variants of non-exhaustive enums, an \
2530 extra wildcard arm must be added to account for any future variants.",
2531 )?;
2532 } else if item.is_variant() {
2533 f.write_str(
2534 "Non-exhaustive enum variants could have additional fields added in future. \
2535 Therefore, non-exhaustive enum variants cannot be constructed in external \
2536 crates and cannot be matched against.",
2537 )?;
2538 } else {
2539 f.write_str(
2540 "This type will require a wildcard arm in any match statements or constructors.",
2541 )?;
2542 }
2543
2544 f.write_str("</div></details>")?;
2545 }
2546 Ok(())
2547 })
2548}
2549
2550fn pluralize(count: usize) -> &'static str {
2551 if count > 1 { "s" } else { "" }
2552}