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_repr_attributes_in_code, 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::print_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 print_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 print_anchor(
434 myitem.item_id.expect_def_id(),
435 myitem.name.unwrap(),
436 cx
437 )
438 )?;
439 }
440 }
441 w.write_str("</code></dt>")?;
442 }
443
444 clean::ImportItem(ref import) => {
445 let stab_tags = import.source.did.map_or_else(String::new, |import_def_id| {
446 print_extra_info_tags(tcx, myitem, item, Some(import_def_id)).to_string()
447 });
448
449 let id = match import.kind {
450 clean::ImportKind::Simple(s) => {
451 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
452 }
453 clean::ImportKind::Glob => String::new(),
454 };
455 write!(
456 w,
457 "<dt{id}>\
458 <code>{vis}{imp}</code>{stab_tags}\
459 </dt>",
460 vis = visibility_print_with_space(myitem, cx),
461 imp = import.print(cx)
462 )?;
463 }
464
465 _ => {
466 if myitem.name.is_none() {
467 continue;
468 }
469
470 let unsafety_flag = match myitem.kind {
471 clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
472 if myitem.fn_header(tcx).unwrap().safety
473 == hir::HeaderSafety::Normal(hir::Safety::Unsafe) =>
474 {
475 "<sup title=\"unsafe function\">âš </sup>"
476 }
477 clean::ForeignStaticItem(_, hir::Safety::Unsafe) => {
478 "<sup title=\"unsafe static\">âš </sup>"
479 }
480 _ => "",
481 };
482
483 let visibility_and_hidden = match myitem.visibility(tcx) {
484 Some(ty::Visibility::Restricted(_)) => {
485 if myitem.is_doc_hidden() {
486 "<span title=\"Restricted Visibility\"> 🔒</span><span title=\"Hidden item\">👻</span> "
488 } else {
489 "<span title=\"Restricted Visibility\"> 🔒</span> "
490 }
491 }
492 _ if myitem.is_doc_hidden() => {
493 "<span title=\"Hidden item\"> 👻</span> "
494 }
495 _ => "",
496 };
497
498 let docs =
499 MarkdownSummaryLine(&myitem.doc_value(), &myitem.links(cx)).into_string();
500 let (docs_before, docs_after) =
501 if docs.is_empty() { ("", "") } else { ("<dd>", "</dd>") };
502 write!(
503 w,
504 "<dt>\
505 <a class=\"{class}\" href=\"{href}\" title=\"{title1} {title2}\">\
506 {name}\
507 </a>\
508 {visibility_and_hidden}\
509 {unsafety_flag}\
510 {stab_tags}\
511 </dt>\
512 {docs_before}{docs}{docs_after}",
513 name = EscapeBodyTextWithWbr(myitem.name.unwrap().as_str()),
514 visibility_and_hidden = visibility_and_hidden,
515 stab_tags = print_extra_info_tags(tcx, myitem, item, None),
516 class = myitem.type_(),
517 unsafety_flag = unsafety_flag,
518 href = print_item_path(myitem.type_(), myitem.name.unwrap().as_str()),
519 title1 = myitem.type_(),
520 title2 = full_path(cx, myitem),
521 )?;
522 }
523 }
524 }
525
526 if last_section.is_some() {
527 w.write_str(ITEM_TABLE_CLOSE)?;
528 }
529 Ok(())
530 })
531}
532
533fn print_extra_info_tags(
536 tcx: TyCtxt<'_>,
537 item: &clean::Item,
538 parent: &clean::Item,
539 import_def_id: Option<DefId>,
540) -> impl Display {
541 fmt::from_fn(move |f| {
542 fn tag_html(class: &str, title: &str, contents: &str) -> impl Display {
543 fmt::from_fn(move |f| {
544 write!(
545 f,
546 r#"<wbr><span class="stab {class}" title="{title}">{contents}</span>"#,
547 title = Escape(title),
548 )
549 })
550 }
551
552 let deprecation = import_def_id
554 .map_or_else(|| item.deprecation(tcx), |import_did| tcx.lookup_deprecation(import_did));
555 if let Some(depr) = deprecation {
556 let message = if depr.is_in_effect() { "Deprecated" } else { "Deprecation planned" };
557 write!(f, "{}", tag_html("deprecated", "", message))?;
558 }
559
560 let stability = import_def_id
563 .map_or_else(|| item.stability(tcx), |import_did| tcx.lookup_stability(import_did));
564 if stability.is_some_and(|s| s.is_unstable() && s.feature != sym::rustc_private) {
565 write!(f, "{}", tag_html("unstable", "", "Experimental"))?;
566 }
567
568 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
569 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
570 (cfg, _) => cfg.as_deref().cloned(),
571 };
572
573 debug!(
574 "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
575 name = item.name,
576 cfg = item.cfg,
577 parent_cfg = parent.cfg
578 );
579 if let Some(ref cfg) = cfg {
580 write!(
581 f,
582 "{}",
583 tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html())
584 )
585 } else {
586 Ok(())
587 }
588 })
589}
590
591fn item_function(cx: &Context<'_>, it: &clean::Item, f: &clean::Function) -> impl fmt::Display {
592 fmt::from_fn(|w| {
593 let tcx = cx.tcx();
594 let header = it.fn_header(tcx).expect("printing a function which isn't a function");
595 debug!(
596 "item_function/const: {:?} {:?} {:?} {:?}",
597 it.name,
598 &header.constness,
599 it.stable_since(tcx),
600 it.const_stability(tcx),
601 );
602 let constness = print_constness_with_space(
603 &header.constness,
604 it.stable_since(tcx),
605 it.const_stability(tcx),
606 );
607 let safety = header.safety.print_with_space();
608 let abi = print_abi_with_space(header.abi).to_string();
609 let asyncness = header.asyncness.print_with_space();
610 let visibility = visibility_print_with_space(it, cx).to_string();
611 let name = it.name.unwrap();
612
613 let generics_len = format!("{:#}", f.generics.print(cx)).len();
614 let header_len = "fn ".len()
615 + visibility.len()
616 + constness.len()
617 + asyncness.len()
618 + safety.len()
619 + abi.len()
620 + name.as_str().len()
621 + generics_len;
622
623 let notable_traits = notable_traits_button(&f.decl.output, cx).maybe_display();
624
625 wrap_item(w, |w| {
626 write!(
627 w,
628 "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \
629 {name}{generics}{decl}{notable_traits}{where_clause}",
630 attrs = render_attributes_in_pre(it, "", cx),
631 vis = visibility,
632 constness = constness,
633 asyncness = asyncness,
634 safety = safety,
635 abi = abi,
636 name = name,
637 generics = f.generics.print(cx),
638 where_clause =
639 print_where_clause(&f.generics, cx, 0, Ending::Newline).maybe_display(),
640 decl = f.decl.full_print(header_len, 0, cx),
641 )
642 })?;
643 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
644 })
645}
646
647fn item_trait(cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) -> impl fmt::Display {
648 fmt::from_fn(|w| {
649 let tcx = cx.tcx();
650 let bounds = print_bounds(&t.bounds, false, cx);
651 let required_types =
652 t.items.iter().filter(|m| m.is_required_associated_type()).collect::<Vec<_>>();
653 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
654 let required_consts =
655 t.items.iter().filter(|m| m.is_required_associated_const()).collect::<Vec<_>>();
656 let provided_consts =
657 t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
658 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
659 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
660 let count_types = required_types.len() + provided_types.len();
661 let count_consts = required_consts.len() + provided_consts.len();
662 let count_methods = required_methods.len() + provided_methods.len();
663 let must_implement_one_of_functions = &tcx.trait_def(t.def_id).must_implement_one_of;
664
665 wrap_item(w, |mut w| {
667 write!(
668 w,
669 "{attrs}{vis}{safety}{is_auto}trait {name}{generics}{bounds}",
670 attrs = render_attributes_in_pre(it, "", cx),
671 vis = visibility_print_with_space(it, cx),
672 safety = t.safety(tcx).print_with_space(),
673 is_auto = if t.is_auto(tcx) { "auto " } else { "" },
674 name = it.name.unwrap(),
675 generics = t.generics.print(cx),
676 )?;
677
678 if !t.generics.where_predicates.is_empty() {
679 write!(
680 w,
681 "{}",
682 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display()
683 )?;
684 } else {
685 w.write_char(' ')?;
686 }
687
688 if t.items.is_empty() {
689 w.write_str("{ }")
690 } else {
691 w.write_str("{\n")?;
693 let mut toggle = false;
694
695 if should_hide_fields(count_types) {
697 toggle = true;
698 toggle_open(
699 &mut w,
700 format_args!(
701 "{} associated items",
702 count_types + count_consts + count_methods
703 ),
704 );
705 }
706 for types in [&required_types, &provided_types] {
707 for t in types {
708 writeln!(
709 w,
710 "{};",
711 render_assoc_item(
712 t,
713 AssocItemLink::Anchor(None),
714 ItemType::Trait,
715 cx,
716 RenderMode::Normal,
717 )
718 )?;
719 }
720 }
721 if !toggle && should_hide_fields(count_types + count_consts) {
726 toggle = true;
727 toggle_open(
728 &mut w,
729 format_args!(
730 "{count_consts} associated constant{plural_const} and \
731 {count_methods} method{plural_method}",
732 plural_const = pluralize(count_consts),
733 plural_method = pluralize(count_methods),
734 ),
735 );
736 }
737 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
738 w.write_str("\n")?;
739 }
740 for consts in [&required_consts, &provided_consts] {
741 for c in consts {
742 writeln!(
743 w,
744 "{};",
745 render_assoc_item(
746 c,
747 AssocItemLink::Anchor(None),
748 ItemType::Trait,
749 cx,
750 RenderMode::Normal,
751 )
752 )?;
753 }
754 }
755 if !toggle && should_hide_fields(count_methods) {
756 toggle = true;
757 toggle_open(&mut w, format_args!("{count_methods} methods"));
758 }
759 if count_consts != 0 && count_methods != 0 {
760 w.write_str("\n")?;
761 }
762
763 if !required_methods.is_empty() {
764 writeln!(w, " // Required method{}", pluralize(required_methods.len()))?;
765 }
766 for (pos, m) in required_methods.iter().enumerate() {
767 writeln!(
768 w,
769 "{};",
770 render_assoc_item(
771 m,
772 AssocItemLink::Anchor(None),
773 ItemType::Trait,
774 cx,
775 RenderMode::Normal,
776 )
777 )?;
778
779 if pos < required_methods.len() - 1 {
780 w.write_str("<span class=\"item-spacer\"></span>")?;
781 }
782 }
783 if !required_methods.is_empty() && !provided_methods.is_empty() {
784 w.write_str("\n")?;
785 }
786
787 if !provided_methods.is_empty() {
788 writeln!(w, " // Provided method{}", pluralize(provided_methods.len()))?;
789 }
790 for (pos, m) in provided_methods.iter().enumerate() {
791 writeln!(
792 w,
793 "{} {{ ... }}",
794 render_assoc_item(
795 m,
796 AssocItemLink::Anchor(None),
797 ItemType::Trait,
798 cx,
799 RenderMode::Normal,
800 )
801 )?;
802
803 if pos < provided_methods.len() - 1 {
804 w.write_str("<span class=\"item-spacer\"></span>")?;
805 }
806 }
807 if toggle {
808 toggle_close(&mut w);
809 }
810 w.write_str("}")
811 }
812 })?;
813
814 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
816
817 fn trait_item(cx: &Context<'_>, m: &clean::Item, t: &clean::Item) -> impl fmt::Display {
818 fmt::from_fn(|w| {
819 let name = m.name.unwrap();
820 info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
821 let item_type = m.type_();
822 let id = cx.derive_id(format!("{item_type}.{name}"));
823
824 let content = document_full(m, cx, HeadingOffset::H5).to_string();
825
826 let toggled = !content.is_empty();
827 if toggled {
828 let method_toggle_class =
829 if item_type.is_method() { " method-toggle" } else { "" };
830 write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>")?;
831 }
832 write!(
833 w,
834 "<section id=\"{id}\" class=\"method\">\
835 {}\
836 <h4 class=\"code-header\">{}</h4></section>",
837 render_rightside(cx, m, RenderMode::Normal),
838 render_assoc_item(
839 m,
840 AssocItemLink::Anchor(Some(&id)),
841 ItemType::Impl,
842 cx,
843 RenderMode::Normal,
844 )
845 )?;
846 document_item_info(cx, m, Some(t)).render_into(w).unwrap();
847 if toggled {
848 write!(w, "</summary>{content}</details>")?;
849 }
850 Ok(())
851 })
852 }
853
854 if !required_consts.is_empty() {
855 write!(
856 w,
857 "{}",
858 write_section_heading(
859 "Required Associated Constants",
860 "required-associated-consts",
861 None,
862 "<div class=\"methods\">",
863 )
864 )?;
865 for t in required_consts {
866 write!(w, "{}", trait_item(cx, t, it))?;
867 }
868 w.write_str("</div>")?;
869 }
870 if !provided_consts.is_empty() {
871 write!(
872 w,
873 "{}",
874 write_section_heading(
875 "Provided Associated Constants",
876 "provided-associated-consts",
877 None,
878 "<div class=\"methods\">",
879 )
880 )?;
881 for t in provided_consts {
882 write!(w, "{}", trait_item(cx, t, it))?;
883 }
884 w.write_str("</div>")?;
885 }
886
887 if !required_types.is_empty() {
888 write!(
889 w,
890 "{}",
891 write_section_heading(
892 "Required Associated Types",
893 "required-associated-types",
894 None,
895 "<div class=\"methods\">",
896 )
897 )?;
898 for t in required_types {
899 write!(w, "{}", trait_item(cx, t, it))?;
900 }
901 w.write_str("</div>")?;
902 }
903 if !provided_types.is_empty() {
904 write!(
905 w,
906 "{}",
907 write_section_heading(
908 "Provided Associated Types",
909 "provided-associated-types",
910 None,
911 "<div class=\"methods\">",
912 )
913 )?;
914 for t in provided_types {
915 write!(w, "{}", trait_item(cx, t, it))?;
916 }
917 w.write_str("</div>")?;
918 }
919
920 if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
922 write!(
923 w,
924 "{}",
925 write_section_heading(
926 "Required Methods",
927 "required-methods",
928 None,
929 "<div class=\"methods\">",
930 )
931 )?;
932
933 if let Some(list) = must_implement_one_of_functions.as_deref() {
934 write!(
935 w,
936 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
937 fmt::from_fn(|f| list.iter().joined("`, `", f)),
938 )?;
939 }
940
941 for m in required_methods {
942 write!(w, "{}", trait_item(cx, m, it))?;
943 }
944 w.write_str("</div>")?;
945 }
946 if !provided_methods.is_empty() {
947 write!(
948 w,
949 "{}",
950 write_section_heading(
951 "Provided Methods",
952 "provided-methods",
953 None,
954 "<div class=\"methods\">",
955 )
956 )?;
957 for m in provided_methods {
958 write!(w, "{}", trait_item(cx, m, it))?;
959 }
960 w.write_str("</div>")?;
961 }
962
963 write!(
965 w,
966 "{}",
967 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
968 )?;
969
970 let mut extern_crates = FxIndexSet::default();
971
972 if !t.is_dyn_compatible(cx.tcx()) {
973 write!(
974 w,
975 "{}",
976 write_section_heading(
977 "Dyn Compatibility",
978 "dyn-compatibility",
979 None,
980 format!(
981 "<div class=\"dyn-compatibility-info\"><p>This trait is <b>not</b> \
982 <a href=\"{base}/reference/items/traits.html#dyn-compatibility\">dyn compatible</a>.</p>\
983 <p><i>In older versions of Rust, dyn compatibility was called \"object safety\", \
984 so this trait is not object safe.</i></p></div>",
985 base = crate::clean::utils::DOC_RUST_LANG_ORG_VERSION
986 ),
987 ),
988 )?;
989 }
990
991 if let Some(implementors) = cx.shared.cache.implementors.get(&it.item_id.expect_def_id()) {
992 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
995 for implementor in implementors {
996 if let Some(did) =
997 implementor.inner_impl().for_.without_borrowed_ref().def_id(&cx.shared.cache)
998 && !did.is_local()
999 {
1000 extern_crates.insert(did.krate);
1001 }
1002 match implementor.inner_impl().for_.without_borrowed_ref() {
1003 clean::Type::Path { path } if !path.is_assoc_ty() => {
1004 let did = path.def_id();
1005 let &mut (prev_did, ref mut has_duplicates) =
1006 implementor_dups.entry(path.last()).or_insert((did, false));
1007 if prev_did != did {
1008 *has_duplicates = true;
1009 }
1010 }
1011 _ => {}
1012 }
1013 }
1014
1015 let (local, mut foreign) =
1016 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
1017
1018 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1019 local.iter().partition(|i| i.inner_impl().kind.is_auto());
1020
1021 synthetic.sort_by_cached_key(|i| ImplString::new(i, cx));
1022 concrete.sort_by_cached_key(|i| ImplString::new(i, cx));
1023 foreign.sort_by_cached_key(|i| ImplString::new(i, cx));
1024
1025 if !foreign.is_empty() {
1026 write!(
1027 w,
1028 "{}",
1029 write_section_heading(
1030 "Implementations on Foreign Types",
1031 "foreign-impls",
1032 None,
1033 ""
1034 )
1035 )?;
1036
1037 for implementor in foreign {
1038 let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
1039 let assoc_link =
1040 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
1041 write!(
1042 w,
1043 "{}",
1044 render_impl(
1045 cx,
1046 implementor,
1047 it,
1048 assoc_link,
1049 RenderMode::Normal,
1050 None,
1051 &[],
1052 ImplRenderingParameters {
1053 show_def_docs: false,
1054 show_default_items: false,
1055 show_non_assoc_items: true,
1056 toggle_open_by_default: false,
1057 },
1058 )
1059 )?;
1060 }
1061 }
1062
1063 write!(
1064 w,
1065 "{}",
1066 write_section_heading(
1067 "Implementors",
1068 "implementors",
1069 None,
1070 "<div id=\"implementors-list\">",
1071 )
1072 )?;
1073 for implementor in concrete {
1074 write!(w, "{}", render_implementor(cx, implementor, it, &implementor_dups, &[]))?;
1075 }
1076 w.write_str("</div>")?;
1077
1078 if t.is_auto(tcx) {
1079 write!(
1080 w,
1081 "{}",
1082 write_section_heading(
1083 "Auto implementors",
1084 "synthetic-implementors",
1085 None,
1086 "<div id=\"synthetic-implementors-list\">",
1087 )
1088 )?;
1089 for implementor in synthetic {
1090 write!(
1091 w,
1092 "{}",
1093 render_implementor(
1094 cx,
1095 implementor,
1096 it,
1097 &implementor_dups,
1098 &collect_paths_for_type(
1099 &implementor.inner_impl().for_,
1100 &cx.shared.cache,
1101 ),
1102 )
1103 )?;
1104 }
1105 w.write_str("</div>")?;
1106 }
1107 } else {
1108 write!(
1111 w,
1112 "{}",
1113 write_section_heading(
1114 "Implementors",
1115 "implementors",
1116 None,
1117 "<div id=\"implementors-list\"></div>",
1118 )
1119 )?;
1120
1121 if t.is_auto(tcx) {
1122 write!(
1123 w,
1124 "{}",
1125 write_section_heading(
1126 "Auto implementors",
1127 "synthetic-implementors",
1128 None,
1129 "<div id=\"synthetic-implementors-list\"></div>",
1130 )
1131 )?;
1132 }
1133 }
1134
1135 let mut js_src_path: UrlPartsBuilder =
1207 iter::repeat_n("..", cx.current.len()).chain(iter::once("trait.impl")).collect();
1208 if let Some(did) = it.item_id.as_def_id()
1209 && let get_extern = { || cx.shared.cache.external_paths.get(&did).map(|s| &s.0) }
1210 && let Some(fqp) = cx.shared.cache.exact_paths.get(&did).or_else(get_extern)
1211 {
1212 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1213 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1214 } else {
1215 js_src_path.extend(cx.current.iter().copied());
1216 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1217 }
1218 let extern_crates = fmt::from_fn(|f| {
1219 if !extern_crates.is_empty() {
1220 f.write_str(" data-ignore-extern-crates=\"")?;
1221 extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
1222 f.write_str("\"")?;
1223 }
1224 Ok(())
1225 });
1226 write!(
1227 w,
1228 "<script src=\"{src}\"{extern_crates} async></script>",
1229 src = js_src_path.finish()
1230 )
1231 })
1232}
1233
1234fn item_trait_alias(
1235 cx: &Context<'_>,
1236 it: &clean::Item,
1237 t: &clean::TraitAlias,
1238) -> impl fmt::Display {
1239 fmt::from_fn(|w| {
1240 wrap_item(w, |w| {
1241 write!(
1242 w,
1243 "{attrs}trait {name}{generics} = {bounds}{where_clause};",
1244 attrs = render_attributes_in_pre(it, "", cx),
1245 name = it.name.unwrap(),
1246 generics = t.generics.print(cx),
1247 bounds = print_bounds(&t.bounds, true, cx),
1248 where_clause =
1249 print_where_clause(&t.generics, cx, 0, Ending::NoNewline).maybe_display(),
1250 )
1251 })?;
1252
1253 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1254 write!(
1259 w,
1260 "{}",
1261 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1262 )
1263 })
1264}
1265
1266fn item_type_alias(cx: &Context<'_>, it: &clean::Item, t: &clean::TypeAlias) -> impl fmt::Display {
1267 fmt::from_fn(|w| {
1268 wrap_item(w, |w| {
1269 write!(
1270 w,
1271 "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
1272 attrs = render_attributes_in_pre(it, "", cx),
1273 vis = visibility_print_with_space(it, cx),
1274 name = it.name.unwrap(),
1275 generics = t.generics.print(cx),
1276 where_clause =
1277 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display(),
1278 type_ = t.type_.print(cx),
1279 )
1280 })?;
1281
1282 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1283
1284 if let Some(inner_type) = &t.inner_type {
1285 write!(w, "{}", write_section_heading("Aliased Type", "aliased-type", None, ""),)?;
1286
1287 match inner_type {
1288 clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive } => {
1289 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1290 let enum_def_id = ty.ty_adt_def().unwrap().did();
1291
1292 DisplayEnum {
1293 variants,
1294 generics: &t.generics,
1295 is_non_exhaustive: *is_non_exhaustive,
1296 def_id: enum_def_id,
1297 }
1298 .render_into(cx, it, true, w)?;
1299 }
1300 clean::TypeAliasInnerType::Union { fields } => {
1301 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1302 let union_def_id = ty.ty_adt_def().unwrap().did();
1303
1304 ItemUnion {
1305 cx,
1306 it,
1307 fields,
1308 generics: &t.generics,
1309 is_type_alias: true,
1310 def_id: union_def_id,
1311 }
1312 .render_into(w)?;
1313 }
1314 clean::TypeAliasInnerType::Struct { ctor_kind, fields } => {
1315 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1316 let struct_def_id = ty.ty_adt_def().unwrap().did();
1317
1318 DisplayStruct {
1319 ctor_kind: *ctor_kind,
1320 generics: &t.generics,
1321 fields,
1322 def_id: struct_def_id,
1323 }
1324 .render_into(cx, it, true, w)?;
1325 }
1326 }
1327 } else {
1328 let def_id = it.item_id.expect_def_id();
1329 write!(
1334 w,
1335 "{}{}",
1336 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1337 document_type_layout(cx, def_id)
1338 )?;
1339 }
1340
1341 let cache = &cx.shared.cache;
1414 if let Some(target_did) = t.type_.def_id(cache)
1415 && let get_extern = { || cache.external_paths.get(&target_did) }
1416 && let Some(&(ref target_fqp, target_type)) =
1417 cache.paths.get(&target_did).or_else(get_extern)
1418 && target_type.is_adt() && let Some(self_did) = it.item_id.as_def_id()
1420 && let get_local = { || cache.paths.get(&self_did).map(|(p, _)| p) }
1421 && let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local)
1422 {
1423 let mut js_src_path: UrlPartsBuilder =
1424 iter::repeat_n("..", cx.current.len()).chain(iter::once("type.impl")).collect();
1425 js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
1426 js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
1427 let self_path = fmt::from_fn(|f| self_fqp.iter().joined("::", f));
1428 write!(
1429 w,
1430 "<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
1431 src = js_src_path.finish(),
1432 )?;
1433 }
1434 Ok(())
1435 })
1436}
1437
1438item_template!(
1439 #[template(path = "item_union.html")]
1440 struct ItemUnion<'a, 'cx> {
1441 cx: &'a Context<'cx>,
1442 it: &'a clean::Item,
1443 fields: &'a [clean::Item],
1444 generics: &'a clean::Generics,
1445 is_type_alias: bool,
1446 def_id: DefId,
1447 },
1448 methods = [document, document_type_layout, render_assoc_items]
1449);
1450
1451impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
1452 fn render_union(&self) -> impl Display {
1453 render_union(self.it, Some(&self.generics), &self.fields, self.cx)
1454 }
1455
1456 fn document_field(&self, field: &'a clean::Item) -> impl Display {
1457 document(self.cx, field, Some(self.it), HeadingOffset::H3)
1458 }
1459
1460 fn stability_field(&self, field: &clean::Item) -> Option<String> {
1461 field.stability_class(self.cx.tcx())
1462 }
1463
1464 fn print_ty(&self, ty: &'a clean::Type) -> impl Display {
1465 ty.print(self.cx)
1466 }
1467
1468 fn fields_iter(&self) -> impl Iterator<Item = (&'a clean::Item, &'a clean::Type)> {
1475 self.fields.iter().filter_map(|f| match f.kind {
1476 clean::StructFieldItem(ref ty) => Some((f, ty)),
1477 _ => None,
1478 })
1479 }
1480
1481 fn render_attributes_in_pre(&self) -> impl fmt::Display {
1482 fmt::from_fn(move |f| {
1483 if self.is_type_alias {
1484 if let Some(repr) = clean::repr_attributes(
1486 self.cx.tcx(),
1487 self.cx.cache(),
1488 self.def_id,
1489 ItemType::Union,
1490 false,
1491 ) {
1492 writeln!(f, "{repr}")?;
1493 };
1494 } else {
1495 for a in self.it.attributes(self.cx.tcx(), self.cx.cache(), false) {
1496 writeln!(f, "{a}")?;
1497 }
1498 }
1499 Ok(())
1500 })
1501 }
1502}
1503
1504fn item_union(cx: &Context<'_>, it: &clean::Item, s: &clean::Union) -> impl fmt::Display {
1505 fmt::from_fn(|w| {
1506 ItemUnion {
1507 cx,
1508 it,
1509 fields: &s.fields,
1510 generics: &s.generics,
1511 is_type_alias: false,
1512 def_id: it.def_id().unwrap(),
1513 }
1514 .render_into(w)?;
1515 Ok(())
1516 })
1517}
1518
1519fn print_tuple_struct_fields(cx: &Context<'_>, s: &[clean::Item]) -> impl Display {
1520 fmt::from_fn(|f| {
1521 if !s.is_empty()
1522 && s.iter().all(|field| {
1523 matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
1524 })
1525 {
1526 return f.write_str("<span class=\"comment\">/* private fields */</span>");
1527 }
1528
1529 s.iter()
1530 .map(|ty| {
1531 fmt::from_fn(|f| match ty.kind {
1532 clean::StrippedItem(box clean::StructFieldItem(_)) => f.write_str("_"),
1533 clean::StructFieldItem(ref ty) => write!(f, "{}", ty.print(cx)),
1534 _ => unreachable!(),
1535 })
1536 })
1537 .joined(", ", f)
1538 })
1539}
1540
1541struct DisplayEnum<'clean> {
1542 variants: &'clean IndexVec<VariantIdx, clean::Item>,
1543 generics: &'clean clean::Generics,
1544 is_non_exhaustive: bool,
1545 def_id: DefId,
1546}
1547
1548impl<'clean> DisplayEnum<'clean> {
1549 fn render_into<W: fmt::Write>(
1550 self,
1551 cx: &Context<'_>,
1552 it: &clean::Item,
1553 is_type_alias: bool,
1554 w: &mut W,
1555 ) -> fmt::Result {
1556 let non_stripped_variant_count = self.variants.iter().filter(|i| !i.is_stripped()).count();
1557 let variants_len = self.variants.len();
1558 let has_stripped_entries = variants_len != non_stripped_variant_count;
1559
1560 wrap_item(w, |w| {
1561 if is_type_alias {
1562 render_repr_attributes_in_code(w, cx, self.def_id, ItemType::Enum);
1564 } else {
1565 render_attributes_in_code(w, it, cx);
1566 }
1567 write!(
1568 w,
1569 "{}enum {}{}{}",
1570 visibility_print_with_space(it, cx),
1571 it.name.unwrap(),
1572 self.generics.print(cx),
1573 render_enum_fields(
1574 cx,
1575 Some(self.generics),
1576 self.variants,
1577 non_stripped_variant_count,
1578 has_stripped_entries,
1579 self.is_non_exhaustive,
1580 self.def_id,
1581 ),
1582 )
1583 })?;
1584
1585 let def_id = it.item_id.expect_def_id();
1586 let layout_def_id = if is_type_alias {
1587 self.def_id
1588 } else {
1589 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1590 def_id
1593 };
1594
1595 if non_stripped_variant_count != 0 {
1596 write!(w, "{}", item_variants(cx, it, self.variants, self.def_id))?;
1597 }
1598 write!(
1599 w,
1600 "{}{}",
1601 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1602 document_type_layout(cx, layout_def_id)
1603 )
1604 }
1605}
1606
1607fn item_enum(cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) -> impl fmt::Display {
1608 fmt::from_fn(|w| {
1609 DisplayEnum {
1610 variants: &e.variants,
1611 generics: &e.generics,
1612 is_non_exhaustive: it.is_non_exhaustive(),
1613 def_id: it.def_id().unwrap(),
1614 }
1615 .render_into(cx, it, false, w)
1616 })
1617}
1618
1619fn should_show_enum_discriminant(
1623 cx: &Context<'_>,
1624 enum_def_id: DefId,
1625 variants: &IndexVec<VariantIdx, clean::Item>,
1626) -> bool {
1627 let mut has_variants_with_value = false;
1628 for variant in variants {
1629 if let clean::VariantItem(ref var) = variant.kind
1630 && matches!(var.kind, clean::VariantKind::CLike)
1631 {
1632 has_variants_with_value |= var.discriminant.is_some();
1633 } else {
1634 return false;
1635 }
1636 }
1637 if has_variants_with_value {
1638 return true;
1639 }
1640 let repr = cx.tcx().adt_def(enum_def_id).repr();
1641 repr.c() || repr.int.is_some()
1642}
1643
1644fn display_c_like_variant(
1645 cx: &Context<'_>,
1646 item: &clean::Item,
1647 variant: &clean::Variant,
1648 index: VariantIdx,
1649 should_show_enum_discriminant: bool,
1650 enum_def_id: DefId,
1651) -> impl fmt::Display {
1652 fmt::from_fn(move |w| {
1653 let name = item.name.unwrap();
1654 if let Some(ref value) = variant.discriminant {
1655 write!(w, "{} = {}", name.as_str(), value.value(cx.tcx(), true))?;
1656 } else if should_show_enum_discriminant {
1657 let adt_def = cx.tcx().adt_def(enum_def_id);
1658 let discr = adt_def.discriminant_for_variant(cx.tcx(), index);
1659 if discr.ty.is_signed() {
1660 write!(w, "{} = {}", name.as_str(), discr.val as i128)?;
1661 } else {
1662 write!(w, "{} = {}", name.as_str(), discr.val)?;
1663 }
1664 } else {
1665 write!(w, "{name}")?;
1666 }
1667 Ok(())
1668 })
1669}
1670
1671fn render_enum_fields(
1672 cx: &Context<'_>,
1673 g: Option<&clean::Generics>,
1674 variants: &IndexVec<VariantIdx, clean::Item>,
1675 count_variants: usize,
1676 has_stripped_entries: bool,
1677 is_non_exhaustive: bool,
1678 enum_def_id: DefId,
1679) -> impl fmt::Display {
1680 fmt::from_fn(move |w| {
1681 let should_show_enum_discriminant =
1682 should_show_enum_discriminant(cx, enum_def_id, variants);
1683 if let Some(generics) = g
1684 && let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline)
1685 {
1686 write!(w, "{where_clause}")?;
1687 } else {
1688 w.write_char(' ')?;
1690 }
1691
1692 let variants_stripped = has_stripped_entries;
1693 if count_variants == 0 && !variants_stripped {
1694 w.write_str("{}")
1695 } else {
1696 w.write_str("{\n")?;
1697 let toggle = should_hide_fields(count_variants);
1698 if toggle {
1699 toggle_open(&mut *w, format_args!("{count_variants} variants"));
1700 }
1701 const TAB: &str = " ";
1702 for (index, v) in variants.iter_enumerated() {
1703 if v.is_stripped() {
1704 continue;
1705 }
1706 write!(w, "{}", render_attributes_in_pre(v, TAB, cx))?;
1707 w.write_str(TAB)?;
1708 match v.kind {
1709 clean::VariantItem(ref var) => match var.kind {
1710 clean::VariantKind::CLike => {
1711 write!(
1712 w,
1713 "{}",
1714 display_c_like_variant(
1715 cx,
1716 v,
1717 var,
1718 index,
1719 should_show_enum_discriminant,
1720 enum_def_id,
1721 )
1722 )?;
1723 }
1724 clean::VariantKind::Tuple(ref s) => {
1725 write!(w, "{}({})", v.name.unwrap(), print_tuple_struct_fields(cx, s))?;
1726 }
1727 clean::VariantKind::Struct(ref s) => {
1728 write!(
1729 w,
1730 "{}",
1731 render_struct(v, None, None, &s.fields, TAB, false, cx)
1732 )?;
1733 }
1734 },
1735 _ => unreachable!(),
1736 }
1737 w.write_str(",\n")?;
1738 }
1739
1740 if variants_stripped && !is_non_exhaustive {
1741 w.write_str(" <span class=\"comment\">// some variants omitted</span>\n")?;
1742 }
1743 if toggle {
1744 toggle_close(&mut *w);
1745 }
1746 w.write_str("}")
1747 }
1748 })
1749}
1750
1751fn item_variants(
1752 cx: &Context<'_>,
1753 it: &clean::Item,
1754 variants: &IndexVec<VariantIdx, clean::Item>,
1755 enum_def_id: DefId,
1756) -> impl fmt::Display {
1757 fmt::from_fn(move |w| {
1758 let tcx = cx.tcx();
1759 write!(
1760 w,
1761 "{}",
1762 write_section_heading(
1763 &format!("Variants{}", document_non_exhaustive_header(it)),
1764 "variants",
1765 Some("variants"),
1766 format!("{}<div class=\"variants\">", document_non_exhaustive(it)),
1767 ),
1768 )?;
1769
1770 let should_show_enum_discriminant =
1771 should_show_enum_discriminant(cx, enum_def_id, variants);
1772 for (index, variant) in variants.iter_enumerated() {
1773 if variant.is_stripped() {
1774 continue;
1775 }
1776 let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.unwrap()));
1777 write!(
1778 w,
1779 "<section id=\"{id}\" class=\"variant\">\
1780 <a href=\"#{id}\" class=\"anchor\">§</a>\
1781 {}\
1782 <h3 class=\"code-header\">",
1783 render_stability_since_raw_with_extra(
1784 variant.stable_since(tcx),
1785 variant.const_stability(tcx),
1786 " rightside",
1787 )
1788 .maybe_display()
1789 )?;
1790 if let clean::VariantItem(ref var) = variant.kind
1791 && let clean::VariantKind::CLike = var.kind
1792 {
1793 write!(
1794 w,
1795 "{}",
1796 display_c_like_variant(
1797 cx,
1798 variant,
1799 var,
1800 index,
1801 should_show_enum_discriminant,
1802 enum_def_id,
1803 )
1804 )?;
1805 } else {
1806 w.write_str(variant.name.unwrap().as_str())?;
1807 }
1808
1809 let clean::VariantItem(variant_data) = &variant.kind else { unreachable!() };
1810
1811 if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
1812 write!(w, "({})", print_tuple_struct_fields(cx, s))?;
1813 }
1814 w.write_str("</h3></section>")?;
1815
1816 write!(w, "{}", document(cx, variant, Some(it), HeadingOffset::H4))?;
1817
1818 let heading_and_fields = match &variant_data.kind {
1819 clean::VariantKind::Struct(s) => {
1820 if s.fields.iter().any(|f| !f.is_doc_hidden()) {
1822 Some(("Fields", &s.fields))
1823 } else {
1824 None
1825 }
1826 }
1827 clean::VariantKind::Tuple(fields) => {
1828 if fields.iter().any(|f| !f.doc_value().is_empty()) {
1831 Some(("Tuple Fields", fields))
1832 } else {
1833 None
1834 }
1835 }
1836 clean::VariantKind::CLike => None,
1837 };
1838
1839 if let Some((heading, fields)) = heading_and_fields {
1840 let variant_id =
1841 cx.derive_id(format!("{}.{}.fields", ItemType::Variant, variant.name.unwrap()));
1842 write!(
1843 w,
1844 "<div class=\"sub-variant\" id=\"{variant_id}\">\
1845 <h4>{heading}</h4>\
1846 {}",
1847 document_non_exhaustive(variant)
1848 )?;
1849 for field in fields {
1850 match field.kind {
1851 clean::StrippedItem(box clean::StructFieldItem(_)) => {}
1852 clean::StructFieldItem(ref ty) => {
1853 let id = cx.derive_id(format!(
1854 "variant.{}.field.{}",
1855 variant.name.unwrap(),
1856 field.name.unwrap()
1857 ));
1858 write!(
1859 w,
1860 "<div class=\"sub-variant-field\">\
1861 <span id=\"{id}\" class=\"section-header\">\
1862 <a href=\"#{id}\" class=\"anchor field\">§</a>\
1863 <code>{f}: {t}</code>\
1864 </span>\
1865 {doc}\
1866 </div>",
1867 f = field.name.unwrap(),
1868 t = ty.print(cx),
1869 doc = document(cx, field, Some(variant), HeadingOffset::H5),
1870 )?;
1871 }
1872 _ => unreachable!(),
1873 }
1874 }
1875 w.write_str("</div>")?;
1876 }
1877 }
1878 w.write_str("</div>")
1879 })
1880}
1881
1882fn item_macro(cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) -> impl fmt::Display {
1883 fmt::from_fn(|w| {
1884 wrap_item(w, |w| {
1885 if !t.macro_rules {
1887 write!(w, "{}", visibility_print_with_space(it, cx))?;
1888 }
1889 write!(w, "{}", Escape(&t.source))
1890 })?;
1891 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
1892 })
1893}
1894
1895fn item_proc_macro(cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) -> impl fmt::Display {
1896 fmt::from_fn(|w| {
1897 wrap_item(w, |w| {
1898 let name = it.name.expect("proc-macros always have names");
1899 match m.kind {
1900 MacroKind::Bang => {
1901 write!(w, "{name}!() {{ <span class=\"comment\">/* proc-macro */</span> }}")?;
1902 }
1903 MacroKind::Attr => {
1904 write!(w, "#[{name}]")?;
1905 }
1906 MacroKind::Derive => {
1907 write!(w, "#[derive({name})]")?;
1908 if !m.helpers.is_empty() {
1909 w.write_str(
1910 "\n{\n \
1911 <span class=\"comment\">// Attributes available to this derive:</span>\n",
1912 )?;
1913 for attr in &m.helpers {
1914 writeln!(w, " #[{attr}]")?;
1915 }
1916 w.write_str("}\n")?;
1917 }
1918 }
1919 }
1920 fmt::Result::Ok(())
1921 })?;
1922 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
1923 })
1924}
1925
1926fn item_primitive(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
1927 fmt::from_fn(|w| {
1928 let def_id = it.item_id.expect_def_id();
1929 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1930 if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
1931 write!(w, "{}", render_assoc_items(cx, it, def_id, AssocItemRender::All))?;
1932 } else {
1933 let (concrete, synthetic, blanket_impl) =
1936 get_filtered_impls_for_reference(&cx.shared, it);
1937
1938 render_all_impls(w, cx, it, &concrete, &synthetic, &blanket_impl);
1939 }
1940 Ok(())
1941 })
1942}
1943
1944fn item_constant(
1945 cx: &Context<'_>,
1946 it: &clean::Item,
1947 generics: &clean::Generics,
1948 ty: &clean::Type,
1949 c: &clean::ConstantKind,
1950) -> impl fmt::Display {
1951 fmt::from_fn(|w| {
1952 wrap_item(w, |w| {
1953 let tcx = cx.tcx();
1954 render_attributes_in_code(w, it, cx);
1955
1956 write!(
1957 w,
1958 "{vis}const {name}{generics}: {typ}{where_clause}",
1959 vis = visibility_print_with_space(it, cx),
1960 name = it.name.unwrap(),
1961 generics = generics.print(cx),
1962 typ = ty.print(cx),
1963 where_clause =
1964 print_where_clause(generics, cx, 0, Ending::NoNewline).maybe_display(),
1965 )?;
1966
1967 let value = c.value(tcx);
1977 let is_literal = c.is_literal(tcx);
1978 let expr = c.expr(tcx);
1979 if value.is_some() || is_literal {
1980 write!(w, " = {expr};", expr = Escape(&expr))?;
1981 } else {
1982 w.write_str(";")?;
1983 }
1984
1985 if !is_literal {
1986 if let Some(value) = &value {
1987 let value_lowercase = value.to_lowercase();
1988 let expr_lowercase = expr.to_lowercase();
1989
1990 if value_lowercase != expr_lowercase
1991 && value_lowercase.trim_end_matches("i32") != expr_lowercase
1992 {
1993 write!(w, " // {value}", value = Escape(value))?;
1994 }
1995 }
1996 }
1997 Ok::<(), fmt::Error>(())
1998 })?;
1999
2000 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
2001 })
2002}
2003
2004struct DisplayStruct<'a> {
2005 ctor_kind: Option<CtorKind>,
2006 generics: &'a clean::Generics,
2007 fields: &'a [clean::Item],
2008 def_id: DefId,
2009}
2010
2011impl<'a> DisplayStruct<'a> {
2012 fn render_into<W: fmt::Write>(
2013 self,
2014 cx: &Context<'_>,
2015 it: &clean::Item,
2016 is_type_alias: bool,
2017 w: &mut W,
2018 ) -> fmt::Result {
2019 wrap_item(w, |w| {
2020 if is_type_alias {
2021 render_repr_attributes_in_code(w, cx, self.def_id, ItemType::Struct);
2023 } else {
2024 render_attributes_in_code(w, it, cx);
2025 }
2026 write!(
2027 w,
2028 "{}",
2029 render_struct(it, Some(self.generics), self.ctor_kind, self.fields, "", true, cx)
2030 )
2031 })?;
2032
2033 if !is_type_alias {
2034 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
2035 }
2036
2037 let def_id = it.item_id.expect_def_id();
2038 write!(
2039 w,
2040 "{}{}{}",
2041 item_fields(cx, it, self.fields, self.ctor_kind),
2042 render_assoc_items(cx, it, def_id, AssocItemRender::All),
2043 document_type_layout(cx, def_id),
2044 )
2045 }
2046}
2047
2048fn item_struct(cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) -> impl fmt::Display {
2049 fmt::from_fn(|w| {
2050 DisplayStruct {
2051 ctor_kind: s.ctor_kind,
2052 generics: &s.generics,
2053 fields: s.fields.as_slice(),
2054 def_id: it.def_id().unwrap(),
2055 }
2056 .render_into(cx, it, false, w)
2057 })
2058}
2059
2060fn item_fields(
2061 cx: &Context<'_>,
2062 it: &clean::Item,
2063 fields: &[clean::Item],
2064 ctor_kind: Option<CtorKind>,
2065) -> impl fmt::Display {
2066 fmt::from_fn(move |w| {
2067 let mut fields = fields
2068 .iter()
2069 .filter_map(|f| match f.kind {
2070 clean::StructFieldItem(ref ty) => Some((f, ty)),
2071 _ => None,
2072 })
2073 .peekable();
2074 if let None | Some(CtorKind::Fn) = ctor_kind {
2075 if fields.peek().is_some() {
2076 let title = format!(
2077 "{}{}",
2078 if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" },
2079 document_non_exhaustive_header(it),
2080 );
2081 write!(
2082 w,
2083 "{}",
2084 write_section_heading(
2085 &title,
2086 "fields",
2087 Some("fields"),
2088 document_non_exhaustive(it)
2089 )
2090 )?;
2091 for (index, (field, ty)) in fields.enumerate() {
2092 let field_name = field
2093 .name
2094 .map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
2095 let id =
2096 cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField));
2097 write!(
2098 w,
2099 "<span id=\"{id}\" class=\"{item_type} section-header\">\
2100 <a href=\"#{id}\" class=\"anchor field\">§</a>\
2101 <code>{field_name}: {ty}</code>\
2102 </span>\
2103 {doc}",
2104 item_type = ItemType::StructField,
2105 ty = ty.print(cx),
2106 doc = document(cx, field, Some(it), HeadingOffset::H3),
2107 )?;
2108 }
2109 }
2110 }
2111 Ok(())
2112 })
2113}
2114
2115fn item_static(
2116 cx: &Context<'_>,
2117 it: &clean::Item,
2118 s: &clean::Static,
2119 safety: Option<hir::Safety>,
2120) -> impl fmt::Display {
2121 fmt::from_fn(move |w| {
2122 wrap_item(w, |w| {
2123 render_attributes_in_code(w, it, cx);
2124 write!(
2125 w,
2126 "{vis}{safe}static {mutability}{name}: {typ}",
2127 vis = visibility_print_with_space(it, cx),
2128 safe = safety.map(|safe| safe.prefix_str()).unwrap_or(""),
2129 mutability = s.mutability.print_with_space(),
2130 name = it.name.unwrap(),
2131 typ = s.type_.print(cx)
2132 )
2133 })?;
2134
2135 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
2136 })
2137}
2138
2139fn item_foreign_type(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
2140 fmt::from_fn(|w| {
2141 wrap_item(w, |w| {
2142 w.write_str("extern {\n")?;
2143 render_attributes_in_code(w, it, cx);
2144 write!(w, " {}type {};\n}}", visibility_print_with_space(it, cx), it.name.unwrap(),)
2145 })?;
2146
2147 write!(
2148 w,
2149 "{}{}",
2150 document(cx, it, None, HeadingOffset::H2),
2151 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
2152 )
2153 })
2154}
2155
2156fn item_keyword(cx: &Context<'_>, it: &clean::Item) -> impl fmt::Display {
2157 document(cx, it, None, HeadingOffset::H2)
2158}
2159
2160pub(crate) fn compare_names(left: &str, right: &str) -> Ordering {
2166 let mut left = left.chars().peekable();
2167 let mut right = right.chars().peekable();
2168
2169 loop {
2170 let (l, r) = match (left.next(), right.next()) {
2172 (None, None) => return Ordering::Equal,
2174 (None, Some(_)) => return Ordering::Less,
2176 (Some(_), None) => return Ordering::Greater,
2177 (Some(l), Some(r)) => (l, r),
2178 };
2179 let next_ordering = match (l.to_digit(10), r.to_digit(10)) {
2180 (None, None) => Ord::cmp(&l, &r),
2182 (None, Some(_)) => Ordering::Greater,
2185 (Some(_), None) => Ordering::Less,
2186 (Some(l), Some(r)) => {
2188 if l == 0 || r == 0 {
2189 let ordering = Ord::cmp(&l, &r);
2191 if ordering != Ordering::Equal {
2192 return ordering;
2193 }
2194 loop {
2195 let (l, r) = match (left.peek(), right.peek()) {
2197 (None, None) => return Ordering::Equal,
2199 (None, Some(_)) => return Ordering::Less,
2201 (Some(_), None) => return Ordering::Greater,
2202 (Some(l), Some(r)) => (l, r),
2203 };
2204 match (l.to_digit(10), r.to_digit(10)) {
2206 (None, None) => break Ordering::Equal,
2208 (None, Some(_)) => return Ordering::Less,
2210 (Some(_), None) => return Ordering::Greater,
2211 (Some(l), Some(r)) => {
2213 left.next();
2214 right.next();
2215 let ordering = Ord::cmp(&l, &r);
2216 if ordering != Ordering::Equal {
2217 return ordering;
2218 }
2219 }
2220 }
2221 }
2222 } else {
2223 let mut same_length_ordering = Ord::cmp(&l, &r);
2225 loop {
2226 let (l, r) = match (left.peek(), right.peek()) {
2228 (None, None) => return same_length_ordering,
2230 (None, Some(_)) => return Ordering::Less,
2232 (Some(_), None) => return Ordering::Greater,
2233 (Some(l), Some(r)) => (l, r),
2234 };
2235 match (l.to_digit(10), r.to_digit(10)) {
2237 (None, None) => break same_length_ordering,
2239 (None, Some(_)) => return Ordering::Less,
2241 (Some(_), None) => return Ordering::Greater,
2242 (Some(l), Some(r)) => {
2244 left.next();
2245 right.next();
2246 same_length_ordering = same_length_ordering.then(Ord::cmp(&l, &r));
2247 }
2248 }
2249 }
2250 }
2251 }
2252 };
2253 if next_ordering != Ordering::Equal {
2254 return next_ordering;
2255 }
2256 }
2257}
2258
2259pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
2260 let mut s = join_with_double_colon(&cx.current);
2261 s.push_str("::");
2262 s.push_str(item.name.unwrap().as_str());
2263 s
2264}
2265
2266pub(super) fn print_item_path(ty: ItemType, name: &str) -> impl Display {
2267 fmt::from_fn(move |f| match ty {
2268 ItemType::Module => write!(f, "{}index.html", ensure_trailing_slash(name)),
2269 _ => write!(f, "{ty}.{name}.html"),
2270 })
2271}
2272
2273fn print_bounds(
2274 bounds: &[clean::GenericBound],
2275 trait_alias: bool,
2276 cx: &Context<'_>,
2277) -> impl Display {
2278 (!bounds.is_empty())
2279 .then_some(fmt::from_fn(move |f| {
2280 let has_lots_of_bounds = bounds.len() > 2;
2281 let inter_str = if has_lots_of_bounds { "\n + " } else { " + " };
2282 if !trait_alias {
2283 if has_lots_of_bounds {
2284 f.write_str(":\n ")?;
2285 } else {
2286 f.write_str(": ")?;
2287 }
2288 }
2289
2290 bounds.iter().map(|p| p.print(cx)).joined(inter_str, f)
2291 }))
2292 .maybe_display()
2293}
2294
2295fn wrap_item<W, F, T>(w: &mut W, f: F) -> T
2296where
2297 W: fmt::Write,
2298 F: FnOnce(&mut W) -> T,
2299{
2300 write!(w, r#"<pre class="rust item-decl"><code>"#).unwrap();
2301 let res = f(w);
2302 write!(w, "</code></pre>").unwrap();
2303 res
2304}
2305
2306#[derive(PartialEq, Eq)]
2307struct ImplString(String);
2308
2309impl ImplString {
2310 fn new(i: &Impl, cx: &Context<'_>) -> ImplString {
2311 ImplString(format!("{}", i.inner_impl().print(false, cx)))
2312 }
2313}
2314
2315impl PartialOrd for ImplString {
2316 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2317 Some(Ord::cmp(self, other))
2318 }
2319}
2320
2321impl Ord for ImplString {
2322 fn cmp(&self, other: &Self) -> Ordering {
2323 compare_names(&self.0, &other.0)
2324 }
2325}
2326
2327fn render_implementor(
2328 cx: &Context<'_>,
2329 implementor: &Impl,
2330 trait_: &clean::Item,
2331 implementor_dups: &FxHashMap<Symbol, (DefId, bool)>,
2332 aliases: &[String],
2333) -> impl fmt::Display {
2334 let use_absolute = match implementor.inner_impl().for_ {
2337 clean::Type::Path { ref path, .. }
2338 | clean::BorrowedRef { type_: box clean::Type::Path { ref path, .. }, .. }
2339 if !path.is_assoc_ty() =>
2340 {
2341 implementor_dups[&path.last()].1
2342 }
2343 _ => false,
2344 };
2345 render_impl(
2346 cx,
2347 implementor,
2348 trait_,
2349 AssocItemLink::Anchor(None),
2350 RenderMode::Normal,
2351 Some(use_absolute),
2352 aliases,
2353 ImplRenderingParameters {
2354 show_def_docs: false,
2355 show_default_items: false,
2356 show_non_assoc_items: false,
2357 toggle_open_by_default: false,
2358 },
2359 )
2360}
2361
2362fn render_union(
2363 it: &clean::Item,
2364 g: Option<&clean::Generics>,
2365 fields: &[clean::Item],
2366 cx: &Context<'_>,
2367) -> impl Display {
2368 fmt::from_fn(move |mut f| {
2369 write!(f, "{}union {}", visibility_print_with_space(it, cx), it.name.unwrap(),)?;
2370
2371 let where_displayed = if let Some(generics) = g {
2372 write!(f, "{}", generics.print(cx))?;
2373 if let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline) {
2374 write!(f, "{where_clause}")?;
2375 true
2376 } else {
2377 false
2378 }
2379 } else {
2380 false
2381 };
2382
2383 if !where_displayed {
2385 f.write_str(" ")?;
2386 }
2387
2388 writeln!(f, "{{")?;
2389 let count_fields =
2390 fields.iter().filter(|field| matches!(field.kind, clean::StructFieldItem(..))).count();
2391 let toggle = should_hide_fields(count_fields);
2392 if toggle {
2393 toggle_open(&mut f, format_args!("{count_fields} fields"));
2394 }
2395
2396 for field in fields {
2397 if let clean::StructFieldItem(ref ty) = field.kind {
2398 writeln!(
2399 f,
2400 " {}{}: {},",
2401 visibility_print_with_space(field, cx),
2402 field.name.unwrap(),
2403 ty.print(cx)
2404 )?;
2405 }
2406 }
2407
2408 if it.has_stripped_entries().unwrap() {
2409 writeln!(f, " <span class=\"comment\">/* private fields */</span>")?;
2410 }
2411 if toggle {
2412 toggle_close(&mut f);
2413 }
2414 f.write_str("}").unwrap();
2415 Ok(())
2416 })
2417}
2418
2419fn render_struct(
2420 it: &clean::Item,
2421 g: Option<&clean::Generics>,
2422 ty: Option<CtorKind>,
2423 fields: &[clean::Item],
2424 tab: &str,
2425 structhead: bool,
2426 cx: &Context<'_>,
2427) -> impl fmt::Display {
2428 fmt::from_fn(move |w| {
2429 write!(
2430 w,
2431 "{}{}{}",
2432 visibility_print_with_space(it, cx),
2433 if structhead { "struct " } else { "" },
2434 it.name.unwrap()
2435 )?;
2436 if let Some(g) = g {
2437 write!(w, "{}", g.print(cx))?;
2438 }
2439 write!(
2440 w,
2441 "{}",
2442 render_struct_fields(
2443 g,
2444 ty,
2445 fields,
2446 tab,
2447 structhead,
2448 it.has_stripped_entries().unwrap_or(false),
2449 cx,
2450 )
2451 )
2452 })
2453}
2454
2455fn render_struct_fields(
2456 g: Option<&clean::Generics>,
2457 ty: Option<CtorKind>,
2458 fields: &[clean::Item],
2459 tab: &str,
2460 structhead: bool,
2461 has_stripped_entries: bool,
2462 cx: &Context<'_>,
2463) -> impl fmt::Display {
2464 fmt::from_fn(move |w| {
2465 match ty {
2466 None => {
2467 let where_displayed = if let Some(generics) = g
2468 && let Some(where_clause) = print_where_clause(generics, cx, 0, Ending::Newline)
2469 {
2470 write!(w, "{where_clause}")?;
2471 true
2472 } else {
2473 false
2474 };
2475
2476 if !where_displayed {
2478 w.write_str(" {")?;
2479 } else {
2480 w.write_str("{")?;
2481 }
2482 let count_fields =
2483 fields.iter().filter(|f| matches!(f.kind, clean::StructFieldItem(..))).count();
2484 let has_visible_fields = count_fields > 0;
2485 let toggle = should_hide_fields(count_fields);
2486 if toggle {
2487 toggle_open(&mut *w, format_args!("{count_fields} fields"));
2488 }
2489 for field in fields {
2490 if let clean::StructFieldItem(ref ty) = field.kind {
2491 write!(
2492 w,
2493 "\n{tab} {vis}{name}: {ty},",
2494 vis = visibility_print_with_space(field, cx),
2495 name = field.name.unwrap(),
2496 ty = ty.print(cx)
2497 )?;
2498 }
2499 }
2500
2501 if has_visible_fields {
2502 if has_stripped_entries {
2503 write!(
2504 w,
2505 "\n{tab} <span class=\"comment\">/* private fields */</span>"
2506 )?;
2507 }
2508 write!(w, "\n{tab}")?;
2509 } else if has_stripped_entries {
2510 write!(w, " <span class=\"comment\">/* private fields */</span> ")?;
2511 }
2512 if toggle {
2513 toggle_close(&mut *w);
2514 }
2515 w.write_str("}")?;
2516 }
2517 Some(CtorKind::Fn) => {
2518 w.write_str("(")?;
2519 if !fields.is_empty()
2520 && fields.iter().all(|field| {
2521 matches!(field.kind, clean::StrippedItem(box clean::StructFieldItem(..)))
2522 })
2523 {
2524 write!(w, "<span class=\"comment\">/* private fields */</span>")?;
2525 } else {
2526 for (i, field) in fields.iter().enumerate() {
2527 if i > 0 {
2528 w.write_str(", ")?;
2529 }
2530 match field.kind {
2531 clean::StrippedItem(box clean::StructFieldItem(..)) => {
2532 write!(w, "_")?;
2533 }
2534 clean::StructFieldItem(ref ty) => {
2535 write!(
2536 w,
2537 "{}{}",
2538 visibility_print_with_space(field, cx),
2539 ty.print(cx)
2540 )?;
2541 }
2542 _ => unreachable!(),
2543 }
2544 }
2545 }
2546 w.write_str(")")?;
2547 if let Some(g) = g {
2548 write!(
2549 w,
2550 "{}",
2551 print_where_clause(g, cx, 0, Ending::NoNewline).maybe_display()
2552 )?;
2553 }
2554 if structhead {
2556 w.write_str(";")?;
2557 }
2558 }
2559 Some(CtorKind::Const) => {
2560 if let Some(g) = g {
2562 write!(
2563 w,
2564 "{}",
2565 print_where_clause(g, cx, 0, Ending::NoNewline).maybe_display()
2566 )?;
2567 }
2568 w.write_str(";")?;
2569 }
2570 }
2571 Ok(())
2572 })
2573}
2574
2575fn document_non_exhaustive_header(item: &clean::Item) -> &str {
2576 if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" }
2577}
2578
2579fn document_non_exhaustive(item: &clean::Item) -> impl Display {
2580 fmt::from_fn(|f| {
2581 if item.is_non_exhaustive() {
2582 write!(
2583 f,
2584 "<details class=\"toggle non-exhaustive\">\
2585 <summary class=\"hideme\"><span>{}</span></summary>\
2586 <div class=\"docblock\">",
2587 {
2588 if item.is_struct() {
2589 "This struct is marked as non-exhaustive"
2590 } else if item.is_enum() {
2591 "This enum is marked as non-exhaustive"
2592 } else if item.is_variant() {
2593 "This variant is marked as non-exhaustive"
2594 } else {
2595 "This type is marked as non-exhaustive"
2596 }
2597 }
2598 )?;
2599
2600 if item.is_struct() {
2601 f.write_str(
2602 "Non-exhaustive structs could have additional fields added in future. \
2603 Therefore, non-exhaustive structs cannot be constructed in external crates \
2604 using the traditional <code>Struct { .. }</code> syntax; cannot be \
2605 matched against without a wildcard <code>..</code>; and \
2606 struct update syntax will not work.",
2607 )?;
2608 } else if item.is_enum() {
2609 f.write_str(
2610 "Non-exhaustive enums could have additional variants added in future. \
2611 Therefore, when matching against variants of non-exhaustive enums, an \
2612 extra wildcard arm must be added to account for any future variants.",
2613 )?;
2614 } else if item.is_variant() {
2615 f.write_str(
2616 "Non-exhaustive enum variants could have additional fields added in future. \
2617 Therefore, non-exhaustive enum variants cannot be constructed in external \
2618 crates and cannot be matched against.",
2619 )?;
2620 } else {
2621 f.write_str(
2622 "This type will require a wildcard arm in any match statements or constructors.",
2623 )?;
2624 }
2625
2626 f.write_str("</div></details>")?;
2627 }
2628 Ok(())
2629 })
2630}
2631
2632fn pluralize(count: usize) -> &'static str {
2633 if count > 1 { "s" } else { "" }
2634}