1use std::cmp::Ordering;
2use std::fmt::{self, Display, Write as _};
3use std::iter;
4
5use askama::Template;
6use rustc_abi::VariantIdx;
7use rustc_ast::join_path_syms;
8use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
9use rustc_hir as hir;
10use rustc_hir::def::CtorKind;
11use rustc_hir::def_id::DefId;
12use rustc_index::IndexVec;
13use rustc_middle::ty::{self, TyCtxt};
14use rustc_span::hygiene::MacroKind;
15use rustc_span::symbol::{Symbol, sym};
16use tracing::{debug, info};
17
18use super::type_layout::document_type_layout;
19use super::{
20 AssocItemLink, AssocItemRender, Context, ImplRenderingParameters, RenderMode,
21 collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference,
22 item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls,
23 render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre,
24 render_impl, render_repr_attributes_in_code, render_rightside, render_stability_since_raw,
25 render_stability_since_raw_with_extra, write_section_heading,
26};
27use crate::clean;
28use crate::config::ModuleSorting;
29use crate::display::{Joined as _, MaybeDisplay as _};
30use crate::formats::Impl;
31use crate::formats::item_type::ItemType;
32use crate::html::escape::{Escape, EscapeBodyTextWithWbr};
33use crate::html::format::{
34 Ending, PrintWithSpace, print_abi_with_space, print_constness_with_space, print_where_clause,
35 visibility_print_with_space,
36};
37use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine};
38use crate::html::render::{document_full, document_item_info};
39use crate::html::url_parts_builder::UrlPartsBuilder;
40
41macro_rules! item_template {
60 (
61 $(#[$meta:meta])*
62 struct $name:ident<'a, 'cx> {
63 cx: &'a Context<'cx>,
64 it: &'a clean::Item,
65 $($field_name:ident: $field_ty:ty),*,
66 },
67 methods = [$($methods:tt),* $(,)?]
68 ) => {
69 #[derive(Template)]
70 $(#[$meta])*
71 struct $name<'a, 'cx> {
72 cx: &'a Context<'cx>,
73 it: &'a clean::Item,
74 $($field_name: $field_ty),*
75 }
76
77 impl<'a, 'cx: 'a> ItemTemplate<'a, 'cx> for $name<'a, 'cx> {
78 fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>) {
79 (&self.it, &self.cx)
80 }
81 }
82
83 impl<'a, 'cx: 'a> $name<'a, 'cx> {
84 item_template_methods!($($methods)*);
85 }
86 };
87}
88
89macro_rules! item_template_methods {
93 () => {};
94 (document $($rest:tt)*) => {
95 fn document(&self) -> impl fmt::Display {
96 let (item, cx) = self.item_and_cx();
97 document(cx, item, None, HeadingOffset::H2)
98 }
99 item_template_methods!($($rest)*);
100 };
101 (document_type_layout $($rest:tt)*) => {
102 fn document_type_layout(&self) -> impl fmt::Display {
103 let (item, cx) = self.item_and_cx();
104 let def_id = item.item_id.expect_def_id();
105 document_type_layout(cx, def_id)
106 }
107 item_template_methods!($($rest)*);
108 };
109 (render_attributes_in_pre $($rest:tt)*) => {
110 fn render_attributes_in_pre(&self) -> impl fmt::Display {
111 let (item, cx) = self.item_and_cx();
112 render_attributes_in_pre(item, "", cx)
113 }
114 item_template_methods!($($rest)*);
115 };
116 (render_assoc_items $($rest:tt)*) => {
117 fn render_assoc_items(&self) -> impl fmt::Display {
118 let (item, cx) = self.item_and_cx();
119 let def_id = item.item_id.expect_def_id();
120 render_assoc_items(cx, item, def_id, AssocItemRender::All)
121 }
122 item_template_methods!($($rest)*);
123 };
124 ($method:ident $($rest:tt)*) => {
125 compile_error!(concat!("unknown method: ", stringify!($method)));
126 };
127 ($token:tt $($rest:tt)*) => {
128 compile_error!(concat!("unexpected token: ", stringify!($token)));
129 };
130}
131
132const ITEM_TABLE_OPEN: &str = "<dl class=\"item-table\">";
133const REEXPORTS_TABLE_OPEN: &str = "<dl class=\"item-table reexports\">";
134const ITEM_TABLE_CLOSE: &str = "</dl>";
135
136struct PathComponent {
138 path: String,
139 name: Symbol,
140}
141
142#[derive(Template)]
143#[template(path = "print_item.html")]
144struct ItemVars<'a> {
145 typ: &'a str,
146 name: &'a str,
147 item_type: &'a str,
148 path_components: Vec<PathComponent>,
149 stability_since_raw: &'a str,
150 src_href: Option<&'a str>,
151}
152
153pub(super) fn print_item(cx: &Context<'_>, item: &clean::Item) -> impl fmt::Display {
154 debug_assert!(!item.is_stripped());
155
156 fmt::from_fn(|buf| {
157 let typ = match item.kind {
158 clean::ModuleItem(_) => {
159 if item.is_crate() {
160 "Crate "
161 } else {
162 "Module "
163 }
164 }
165 clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ",
166 clean::TraitItem(..) => "Trait ",
167 clean::StructItem(..) => "Struct ",
168 clean::UnionItem(..) => "Union ",
169 clean::EnumItem(..) => "Enum ",
170 clean::TypeAliasItem(..) => "Type Alias ",
171 clean::MacroItem(..) => "Macro ",
172 clean::ProcMacroItem(ref mac) => match mac.kind {
173 MacroKind::Bang => "Macro ",
174 MacroKind::Attr => "Attribute Macro ",
175 MacroKind::Derive => "Derive Macro ",
176 },
177 clean::PrimitiveItem(..) => "Primitive Type ",
178 clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ",
179 clean::ConstantItem(..) => "Constant ",
180 clean::ForeignTypeItem => "Foreign Type ",
181 clean::KeywordItem => "Keyword ",
182 clean::TraitAliasItem(..) => "Trait Alias ",
183 _ => {
184 unreachable!();
186 }
187 };
188 let stability_since_raw =
189 render_stability_since_raw(item.stable_since(cx.tcx()), item.const_stability(cx.tcx()))
190 .maybe_display()
191 .to_string();
192
193 let src_href =
200 if cx.info.include_sources && !item.is_primitive() { cx.src_href(item) } else { None };
201
202 let path_components = if item.is_primitive() || item.is_keyword() {
203 vec![]
204 } else {
205 let cur = &cx.current;
206 let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() };
207 cur.iter()
208 .enumerate()
209 .take(amt)
210 .map(|(i, component)| PathComponent {
211 path: "../".repeat(cur.len() - i - 1),
212 name: *component,
213 })
214 .collect()
215 };
216
217 let item_vars = ItemVars {
218 typ,
219 name: item.name.as_ref().unwrap().as_str(),
220 item_type: &item.type_().to_string(),
221 path_components,
222 stability_since_raw: &stability_since_raw,
223 src_href: src_href.as_deref(),
224 };
225
226 item_vars.render_into(buf).unwrap();
227
228 match &item.kind {
229 clean::ModuleItem(m) => {
230 write!(buf, "{}", item_module(cx, item, &m.items))
231 }
232 clean::FunctionItem(f) | clean::ForeignFunctionItem(f, _) => {
233 write!(buf, "{}", item_function(cx, item, f))
234 }
235 clean::TraitItem(t) => write!(buf, "{}", item_trait(cx, item, t)),
236 clean::StructItem(s) => {
237 write!(buf, "{}", item_struct(cx, item, s))
238 }
239 clean::UnionItem(s) => write!(buf, "{}", item_union(cx, item, s)),
240 clean::EnumItem(e) => write!(buf, "{}", item_enum(cx, item, e)),
241 clean::TypeAliasItem(t) => {
242 write!(buf, "{}", item_type_alias(cx, item, t))
243 }
244 clean::MacroItem(m) => write!(buf, "{}", item_macro(cx, item, m)),
245 clean::ProcMacroItem(m) => {
246 write!(buf, "{}", item_proc_macro(cx, item, m))
247 }
248 clean::PrimitiveItem(_) => write!(buf, "{}", item_primitive(cx, item)),
249 clean::StaticItem(i) => {
250 write!(buf, "{}", item_static(cx, item, i, None))
251 }
252 clean::ForeignStaticItem(i, safety) => {
253 write!(buf, "{}", item_static(cx, item, i, Some(*safety)))
254 }
255 clean::ConstantItem(ci) => {
256 write!(buf, "{}", item_constant(cx, item, &ci.generics, &ci.type_, &ci.kind))
257 }
258 clean::ForeignTypeItem => {
259 write!(buf, "{}", item_foreign_type(cx, item))
260 }
261 clean::KeywordItem => write!(buf, "{}", item_keyword(cx, item)),
262 clean::TraitAliasItem(ta) => {
263 write!(buf, "{}", item_trait_alias(cx, item, ta))
264 }
265 _ => {
266 unreachable!();
268 }
269 }?;
270
271 let mut types_with_notable_traits = cx.types_with_notable_traits.borrow_mut();
273 if !types_with_notable_traits.is_empty() {
274 write!(
275 buf,
276 r#"<script type="text/json" id="notable-traits-data">{}</script>"#,
277 notable_traits_json(types_with_notable_traits.iter(), cx),
278 )?;
279 types_with_notable_traits.clear();
280 }
281 Ok(())
282 })
283}
284
285fn should_hide_fields(n_fields: usize) -> bool {
287 n_fields > 12
288}
289
290fn toggle_open(mut w: impl fmt::Write, text: impl Display) {
291 write!(
292 w,
293 "<details class=\"toggle type-contents-toggle\">\
294 <summary class=\"hideme\">\
295 <span>Show {text}</span>\
296 </summary>",
297 )
298 .unwrap();
299}
300
301fn toggle_close(mut w: impl fmt::Write) {
302 w.write_str("</details>").unwrap();
303}
304
305trait ItemTemplate<'a, 'cx: 'a>: askama::Template + Display {
306 fn item_and_cx(&self) -> (&'a clean::Item, &'a Context<'cx>);
307}
308
309fn item_module(cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) -> impl fmt::Display {
310 fmt::from_fn(|w| {
311 write!(w, "{}", document(cx, item, None, HeadingOffset::H2))?;
312
313 let mut not_stripped_items =
314 items.iter().filter(|i| !i.is_stripped()).enumerate().collect::<Vec<_>>();
315
316 fn reorder(ty: ItemType) -> u8 {
318 match ty {
319 ItemType::ExternCrate => 0,
320 ItemType::Import => 1,
321 ItemType::Primitive => 2,
322 ItemType::Module => 3,
323 ItemType::Macro => 4,
324 ItemType::Struct => 5,
325 ItemType::Enum => 6,
326 ItemType::Constant => 7,
327 ItemType::Static => 8,
328 ItemType::Trait => 9,
329 ItemType::Function => 10,
330 ItemType::TypeAlias => 12,
331 ItemType::Union => 13,
332 _ => 14 + ty as u8,
333 }
334 }
335
336 fn cmp(i1: &clean::Item, i2: &clean::Item, tcx: TyCtxt<'_>) -> Ordering {
337 let rty1 = reorder(i1.type_());
338 let rty2 = reorder(i2.type_());
339 if rty1 != rty2 {
340 return rty1.cmp(&rty2);
341 }
342 let is_stable1 =
343 i1.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
344 let is_stable2 =
345 i2.stability(tcx).as_ref().map(|s| s.level.is_stable()).unwrap_or(true);
346 if is_stable1 != is_stable2 {
347 return is_stable2.cmp(&is_stable1);
350 }
351 match (i1.name, i2.name) {
352 (Some(name1), Some(name2)) => compare_names(name1.as_str(), name2.as_str()),
353 (Some(_), None) => Ordering::Greater,
354 (None, Some(_)) => Ordering::Less,
355 (None, None) => Ordering::Equal,
356 }
357 }
358
359 let tcx = cx.tcx();
360
361 match cx.shared.module_sorting {
362 ModuleSorting::Alphabetical => {
363 not_stripped_items.sort_by(|(_, i1), (_, i2)| cmp(i1, i2, tcx));
364 }
365 ModuleSorting::DeclarationOrder => {}
366 }
367 not_stripped_items.dedup_by_key(|(idx, i)| {
387 (
388 i.item_id,
389 if i.name.is_some() { Some(full_path(cx, i)) } else { None },
390 i.type_(),
391 if i.is_import() { *idx } else { 0 },
392 )
393 });
394
395 debug!("{not_stripped_items:?}");
396 let mut last_section = None;
397
398 for (_, myitem) in ¬_stripped_items {
399 let my_section = item_ty_to_section(myitem.type_());
400 if Some(my_section) != last_section {
401 if last_section.is_some() {
402 w.write_str(ITEM_TABLE_CLOSE)?;
403 }
404 last_section = Some(my_section);
405 let section_id = my_section.id();
406 let tag =
407 if section_id == "reexports" { REEXPORTS_TABLE_OPEN } else { ITEM_TABLE_OPEN };
408 write!(
409 w,
410 "{}",
411 write_section_heading(my_section.name(), &cx.derive_id(section_id), None, tag)
412 )?;
413 }
414
415 match myitem.kind {
416 clean::ExternCrateItem { ref src } => {
417 use crate::html::format::print_anchor;
418
419 match *src {
420 Some(src) => {
421 write!(
422 w,
423 "<dt><code>{}extern crate {} as {};",
424 visibility_print_with_space(myitem, cx),
425 print_anchor(myitem.item_id.expect_def_id(), src, cx),
426 EscapeBodyTextWithWbr(myitem.name.unwrap().as_str())
427 )?;
428 }
429 None => {
430 write!(
431 w,
432 "<dt><code>{}extern crate {};",
433 visibility_print_with_space(myitem, cx),
434 print_anchor(
435 myitem.item_id.expect_def_id(),
436 myitem.name.unwrap(),
437 cx
438 )
439 )?;
440 }
441 }
442 w.write_str("</code></dt>")?;
443 }
444
445 clean::ImportItem(ref import) => {
446 let stab_tags = import.source.did.map_or_else(String::new, |import_def_id| {
447 print_extra_info_tags(tcx, myitem, item, Some(import_def_id)).to_string()
448 });
449
450 let id = match import.kind {
451 clean::ImportKind::Simple(s) => {
452 format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
453 }
454 clean::ImportKind::Glob => String::new(),
455 };
456 write!(
457 w,
458 "<dt{id}>\
459 <code>{vis}{imp}</code>{stab_tags}\
460 </dt>",
461 vis = visibility_print_with_space(myitem, cx),
462 imp = import.print(cx)
463 )?;
464 }
465
466 _ => {
467 if myitem.name.is_none() {
468 continue;
469 }
470
471 let unsafety_flag = match myitem.kind {
472 clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
473 if myitem.fn_header(tcx).unwrap().safety
474 == hir::HeaderSafety::Normal(hir::Safety::Unsafe) =>
475 {
476 "<sup title=\"unsafe function\">âš </sup>"
477 }
478 clean::ForeignStaticItem(_, hir::Safety::Unsafe) => {
479 "<sup title=\"unsafe static\">âš </sup>"
480 }
481 _ => "",
482 };
483
484 let visibility_and_hidden = match myitem.visibility(tcx) {
485 Some(ty::Visibility::Restricted(_)) => {
486 if myitem.is_doc_hidden() {
487 "<span title=\"Restricted Visibility\"> 🔒</span><span title=\"Hidden item\">👻</span> "
489 } else {
490 "<span title=\"Restricted Visibility\"> 🔒</span> "
491 }
492 }
493 _ if myitem.is_doc_hidden() => {
494 "<span title=\"Hidden item\"> 👻</span> "
495 }
496 _ => "",
497 };
498
499 let docs =
500 MarkdownSummaryLine(&myitem.doc_value(), &myitem.links(cx)).into_string();
501 let (docs_before, docs_after) =
502 if docs.is_empty() { ("", "") } else { ("<dd>", "</dd>") };
503 write!(
504 w,
505 "<dt>\
506 <a class=\"{class}\" href=\"{href}\" title=\"{title1} {title2}\">\
507 {name}\
508 </a>\
509 {visibility_and_hidden}\
510 {unsafety_flag}\
511 {stab_tags}\
512 </dt>\
513 {docs_before}{docs}{docs_after}",
514 name = EscapeBodyTextWithWbr(myitem.name.unwrap().as_str()),
515 visibility_and_hidden = visibility_and_hidden,
516 stab_tags = print_extra_info_tags(tcx, myitem, item, None),
517 class = myitem.type_(),
518 unsafety_flag = unsafety_flag,
519 href = print_item_path(myitem.type_(), myitem.name.unwrap().as_str()),
520 title1 = myitem.type_(),
521 title2 = full_path(cx, myitem),
522 )?;
523 }
524 }
525 }
526
527 if last_section.is_some() {
528 w.write_str(ITEM_TABLE_CLOSE)?;
529 }
530 Ok(())
531 })
532}
533
534fn print_extra_info_tags(
537 tcx: TyCtxt<'_>,
538 item: &clean::Item,
539 parent: &clean::Item,
540 import_def_id: Option<DefId>,
541) -> impl Display {
542 fmt::from_fn(move |f| {
543 fn tag_html(class: &str, title: &str, contents: &str) -> impl Display {
544 fmt::from_fn(move |f| {
545 write!(
546 f,
547 r#"<wbr><span class="stab {class}" title="{title}">{contents}</span>"#,
548 title = Escape(title),
549 )
550 })
551 }
552
553 let deprecation = import_def_id
555 .map_or_else(|| item.deprecation(tcx), |import_did| tcx.lookup_deprecation(import_did));
556 if let Some(depr) = deprecation {
557 let message = if depr.is_in_effect() { "Deprecated" } else { "Deprecation planned" };
558 write!(f, "{}", tag_html("deprecated", "", message))?;
559 }
560
561 let stability = import_def_id
564 .map_or_else(|| item.stability(tcx), |import_did| tcx.lookup_stability(import_did));
565 if stability.is_some_and(|s| s.is_unstable() && s.feature != sym::rustc_private) {
566 write!(f, "{}", tag_html("unstable", "", "Experimental"))?;
567 }
568
569 let cfg = match (&item.cfg, parent.cfg.as_ref()) {
570 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
571 (cfg, _) => cfg.as_deref().cloned(),
572 };
573
574 debug!(
575 "Portability name={name:?} {cfg:?} - {parent_cfg:?} = {cfg:?}",
576 name = item.name,
577 cfg = item.cfg,
578 parent_cfg = parent.cfg
579 );
580 if let Some(ref cfg) = cfg {
581 write!(
582 f,
583 "{}",
584 tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html())
585 )
586 } else {
587 Ok(())
588 }
589 })
590}
591
592fn item_function(cx: &Context<'_>, it: &clean::Item, f: &clean::Function) -> impl fmt::Display {
593 fmt::from_fn(|w| {
594 let tcx = cx.tcx();
595 let header = it.fn_header(tcx).expect("printing a function which isn't a function");
596 debug!(
597 "item_function/const: {:?} {:?} {:?} {:?}",
598 it.name,
599 &header.constness,
600 it.stable_since(tcx),
601 it.const_stability(tcx),
602 );
603 let constness = print_constness_with_space(
604 &header.constness,
605 it.stable_since(tcx),
606 it.const_stability(tcx),
607 );
608 let safety = header.safety.print_with_space();
609 let abi = print_abi_with_space(header.abi).to_string();
610 let asyncness = header.asyncness.print_with_space();
611 let visibility = visibility_print_with_space(it, cx).to_string();
612 let name = it.name.unwrap();
613
614 let generics_len = format!("{:#}", f.generics.print(cx)).len();
615 let header_len = "fn ".len()
616 + visibility.len()
617 + constness.len()
618 + asyncness.len()
619 + safety.len()
620 + abi.len()
621 + name.as_str().len()
622 + generics_len;
623
624 let notable_traits = notable_traits_button(&f.decl.output, cx).maybe_display();
625
626 wrap_item(w, |w| {
627 write!(
628 w,
629 "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \
630 {name}{generics}{decl}{notable_traits}{where_clause}",
631 attrs = render_attributes_in_pre(it, "", cx),
632 vis = visibility,
633 constness = constness,
634 asyncness = asyncness,
635 safety = safety,
636 abi = abi,
637 name = name,
638 generics = f.generics.print(cx),
639 where_clause =
640 print_where_clause(&f.generics, cx, 0, Ending::Newline).maybe_display(),
641 decl = f.decl.full_print(header_len, 0, cx),
642 )
643 })?;
644 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))
645 })
646}
647
648fn item_trait(cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) -> impl fmt::Display {
649 fmt::from_fn(|w| {
650 let tcx = cx.tcx();
651 let bounds = print_bounds(&t.bounds, false, cx);
652 let required_types =
653 t.items.iter().filter(|m| m.is_required_associated_type()).collect::<Vec<_>>();
654 let provided_types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
655 let required_consts =
656 t.items.iter().filter(|m| m.is_required_associated_const()).collect::<Vec<_>>();
657 let provided_consts =
658 t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
659 let required_methods = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
660 let provided_methods = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
661 let count_types = required_types.len() + provided_types.len();
662 let count_consts = required_consts.len() + provided_consts.len();
663 let count_methods = required_methods.len() + provided_methods.len();
664 let must_implement_one_of_functions = &tcx.trait_def(t.def_id).must_implement_one_of;
665
666 wrap_item(w, |mut w| {
668 write!(
669 w,
670 "{attrs}{vis}{safety}{is_auto}trait {name}{generics}{bounds}",
671 attrs = render_attributes_in_pre(it, "", cx),
672 vis = visibility_print_with_space(it, cx),
673 safety = t.safety(tcx).print_with_space(),
674 is_auto = if t.is_auto(tcx) { "auto " } else { "" },
675 name = it.name.unwrap(),
676 generics = t.generics.print(cx),
677 )?;
678
679 if !t.generics.where_predicates.is_empty() {
680 write!(
681 w,
682 "{}",
683 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display()
684 )?;
685 } else {
686 w.write_char(' ')?;
687 }
688
689 if t.items.is_empty() {
690 w.write_str("{ }")
691 } else {
692 w.write_str("{\n")?;
694 let mut toggle = false;
695
696 if should_hide_fields(count_types) {
698 toggle = true;
699 toggle_open(
700 &mut w,
701 format_args!(
702 "{} associated items",
703 count_types + count_consts + count_methods
704 ),
705 );
706 }
707 for types in [&required_types, &provided_types] {
708 for t in types {
709 writeln!(
710 w,
711 "{};",
712 render_assoc_item(
713 t,
714 AssocItemLink::Anchor(None),
715 ItemType::Trait,
716 cx,
717 RenderMode::Normal,
718 )
719 )?;
720 }
721 }
722 if !toggle && should_hide_fields(count_types + count_consts) {
727 toggle = true;
728 toggle_open(
729 &mut w,
730 format_args!(
731 "{count_consts} associated constant{plural_const} and \
732 {count_methods} method{plural_method}",
733 plural_const = pluralize(count_consts),
734 plural_method = pluralize(count_methods),
735 ),
736 );
737 }
738 if count_types != 0 && (count_consts != 0 || count_methods != 0) {
739 w.write_str("\n")?;
740 }
741 for consts in [&required_consts, &provided_consts] {
742 for c in consts {
743 writeln!(
744 w,
745 "{};",
746 render_assoc_item(
747 c,
748 AssocItemLink::Anchor(None),
749 ItemType::Trait,
750 cx,
751 RenderMode::Normal,
752 )
753 )?;
754 }
755 }
756 if !toggle && should_hide_fields(count_methods) {
757 toggle = true;
758 toggle_open(&mut w, format_args!("{count_methods} methods"));
759 }
760 if count_consts != 0 && count_methods != 0 {
761 w.write_str("\n")?;
762 }
763
764 if !required_methods.is_empty() {
765 writeln!(w, " // Required method{}", pluralize(required_methods.len()))?;
766 }
767 for (pos, m) in required_methods.iter().enumerate() {
768 writeln!(
769 w,
770 "{};",
771 render_assoc_item(
772 m,
773 AssocItemLink::Anchor(None),
774 ItemType::Trait,
775 cx,
776 RenderMode::Normal,
777 )
778 )?;
779
780 if pos < required_methods.len() - 1 {
781 w.write_str("<span class=\"item-spacer\"></span>")?;
782 }
783 }
784 if !required_methods.is_empty() && !provided_methods.is_empty() {
785 w.write_str("\n")?;
786 }
787
788 if !provided_methods.is_empty() {
789 writeln!(w, " // Provided method{}", pluralize(provided_methods.len()))?;
790 }
791 for (pos, m) in provided_methods.iter().enumerate() {
792 writeln!(
793 w,
794 "{} {{ ... }}",
795 render_assoc_item(
796 m,
797 AssocItemLink::Anchor(None),
798 ItemType::Trait,
799 cx,
800 RenderMode::Normal,
801 )
802 )?;
803
804 if pos < provided_methods.len() - 1 {
805 w.write_str("<span class=\"item-spacer\"></span>")?;
806 }
807 }
808 if toggle {
809 toggle_close(&mut w);
810 }
811 w.write_str("}")
812 }
813 })?;
814
815 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
817
818 fn trait_item(cx: &Context<'_>, m: &clean::Item, t: &clean::Item) -> impl fmt::Display {
819 fmt::from_fn(|w| {
820 let name = m.name.unwrap();
821 info!("Documenting {name} on {ty_name:?}", ty_name = t.name);
822 let item_type = m.type_();
823 let id = cx.derive_id(format!("{item_type}.{name}"));
824
825 let content = document_full(m, cx, HeadingOffset::H5).to_string();
826
827 let toggled = !content.is_empty();
828 if toggled {
829 let method_toggle_class =
830 if item_type.is_method() { " method-toggle" } else { "" };
831 write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>")?;
832 }
833 write!(
834 w,
835 "<section id=\"{id}\" class=\"method\">\
836 {}\
837 <h4 class=\"code-header\">{}</h4></section>",
838 render_rightside(cx, m, RenderMode::Normal),
839 render_assoc_item(
840 m,
841 AssocItemLink::Anchor(Some(&id)),
842 ItemType::Impl,
843 cx,
844 RenderMode::Normal,
845 )
846 )?;
847 document_item_info(cx, m, Some(t)).render_into(w).unwrap();
848 if toggled {
849 write!(w, "</summary>{content}</details>")?;
850 }
851 Ok(())
852 })
853 }
854
855 if !required_consts.is_empty() {
856 write!(
857 w,
858 "{}",
859 write_section_heading(
860 "Required Associated Constants",
861 "required-associated-consts",
862 None,
863 "<div class=\"methods\">",
864 )
865 )?;
866 for t in required_consts {
867 write!(w, "{}", trait_item(cx, t, it))?;
868 }
869 w.write_str("</div>")?;
870 }
871 if !provided_consts.is_empty() {
872 write!(
873 w,
874 "{}",
875 write_section_heading(
876 "Provided Associated Constants",
877 "provided-associated-consts",
878 None,
879 "<div class=\"methods\">",
880 )
881 )?;
882 for t in provided_consts {
883 write!(w, "{}", trait_item(cx, t, it))?;
884 }
885 w.write_str("</div>")?;
886 }
887
888 if !required_types.is_empty() {
889 write!(
890 w,
891 "{}",
892 write_section_heading(
893 "Required Associated Types",
894 "required-associated-types",
895 None,
896 "<div class=\"methods\">",
897 )
898 )?;
899 for t in required_types {
900 write!(w, "{}", trait_item(cx, t, it))?;
901 }
902 w.write_str("</div>")?;
903 }
904 if !provided_types.is_empty() {
905 write!(
906 w,
907 "{}",
908 write_section_heading(
909 "Provided Associated Types",
910 "provided-associated-types",
911 None,
912 "<div class=\"methods\">",
913 )
914 )?;
915 for t in provided_types {
916 write!(w, "{}", trait_item(cx, t, it))?;
917 }
918 w.write_str("</div>")?;
919 }
920
921 if !required_methods.is_empty() || must_implement_one_of_functions.is_some() {
923 write!(
924 w,
925 "{}",
926 write_section_heading(
927 "Required Methods",
928 "required-methods",
929 None,
930 "<div class=\"methods\">",
931 )
932 )?;
933
934 if let Some(list) = must_implement_one_of_functions.as_deref() {
935 write!(
936 w,
937 "<div class=\"stab must_implement\">At least one of the `{}` methods is required.</div>",
938 fmt::from_fn(|f| list.iter().joined("`, `", f)),
939 )?;
940 }
941
942 for m in required_methods {
943 write!(w, "{}", trait_item(cx, m, it))?;
944 }
945 w.write_str("</div>")?;
946 }
947 if !provided_methods.is_empty() {
948 write!(
949 w,
950 "{}",
951 write_section_heading(
952 "Provided Methods",
953 "provided-methods",
954 None,
955 "<div class=\"methods\">",
956 )
957 )?;
958 for m in provided_methods {
959 write!(w, "{}", trait_item(cx, m, it))?;
960 }
961 w.write_str("</div>")?;
962 }
963
964 write!(
966 w,
967 "{}",
968 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
969 )?;
970
971 let mut extern_crates = FxIndexSet::default();
972
973 if !t.is_dyn_compatible(cx.tcx()) {
974 write!(
975 w,
976 "{}",
977 write_section_heading(
978 "Dyn Compatibility",
979 "dyn-compatibility",
980 None,
981 format!(
982 "<div class=\"dyn-compatibility-info\"><p>This trait is <b>not</b> \
983 <a href=\"{base}/reference/items/traits.html#dyn-compatibility\">dyn compatible</a>.</p>\
984 <p><i>In older versions of Rust, dyn compatibility was called \"object safety\", \
985 so this trait is not object safe.</i></p></div>",
986 base = crate::clean::utils::DOC_RUST_LANG_ORG_VERSION
987 ),
988 ),
989 )?;
990 }
991
992 if let Some(implementors) = cx.shared.cache.implementors.get(&it.item_id.expect_def_id()) {
993 let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default();
996 for implementor in implementors {
997 if let Some(did) =
998 implementor.inner_impl().for_.without_borrowed_ref().def_id(&cx.shared.cache)
999 && !did.is_local()
1000 {
1001 extern_crates.insert(did.krate);
1002 }
1003 match implementor.inner_impl().for_.without_borrowed_ref() {
1004 clean::Type::Path { path } if !path.is_assoc_ty() => {
1005 let did = path.def_id();
1006 let &mut (prev_did, ref mut has_duplicates) =
1007 implementor_dups.entry(path.last()).or_insert((did, false));
1008 if prev_did != did {
1009 *has_duplicates = true;
1010 }
1011 }
1012 _ => {}
1013 }
1014 }
1015
1016 let (local, mut foreign) =
1017 implementors.iter().partition::<Vec<_>, _>(|i| i.is_on_local_type(cx));
1018
1019 let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
1020 local.iter().partition(|i| i.inner_impl().kind.is_auto());
1021
1022 synthetic.sort_by_cached_key(|i| ImplString::new(i, cx));
1023 concrete.sort_by_cached_key(|i| ImplString::new(i, cx));
1024 foreign.sort_by_cached_key(|i| ImplString::new(i, cx));
1025
1026 if !foreign.is_empty() {
1027 write!(
1028 w,
1029 "{}",
1030 write_section_heading(
1031 "Implementations on Foreign Types",
1032 "foreign-impls",
1033 None,
1034 ""
1035 )
1036 )?;
1037
1038 for implementor in foreign {
1039 let provided_methods = implementor.inner_impl().provided_trait_methods(tcx);
1040 let assoc_link =
1041 AssocItemLink::GotoSource(implementor.impl_item.item_id, &provided_methods);
1042 write!(
1043 w,
1044 "{}",
1045 render_impl(
1046 cx,
1047 implementor,
1048 it,
1049 assoc_link,
1050 RenderMode::Normal,
1051 None,
1052 &[],
1053 ImplRenderingParameters {
1054 show_def_docs: false,
1055 show_default_items: false,
1056 show_non_assoc_items: true,
1057 toggle_open_by_default: false,
1058 },
1059 )
1060 )?;
1061 }
1062 }
1063
1064 write!(
1065 w,
1066 "{}",
1067 write_section_heading(
1068 "Implementors",
1069 "implementors",
1070 None,
1071 "<div id=\"implementors-list\">",
1072 )
1073 )?;
1074 for implementor in concrete {
1075 write!(w, "{}", render_implementor(cx, implementor, it, &implementor_dups, &[]))?;
1076 }
1077 w.write_str("</div>")?;
1078
1079 if t.is_auto(tcx) {
1080 write!(
1081 w,
1082 "{}",
1083 write_section_heading(
1084 "Auto implementors",
1085 "synthetic-implementors",
1086 None,
1087 "<div id=\"synthetic-implementors-list\">",
1088 )
1089 )?;
1090 for implementor in synthetic {
1091 write!(
1092 w,
1093 "{}",
1094 render_implementor(
1095 cx,
1096 implementor,
1097 it,
1098 &implementor_dups,
1099 &collect_paths_for_type(
1100 &implementor.inner_impl().for_,
1101 &cx.shared.cache,
1102 ),
1103 )
1104 )?;
1105 }
1106 w.write_str("</div>")?;
1107 }
1108 } else {
1109 write!(
1112 w,
1113 "{}",
1114 write_section_heading(
1115 "Implementors",
1116 "implementors",
1117 None,
1118 "<div id=\"implementors-list\"></div>",
1119 )
1120 )?;
1121
1122 if t.is_auto(tcx) {
1123 write!(
1124 w,
1125 "{}",
1126 write_section_heading(
1127 "Auto implementors",
1128 "synthetic-implementors",
1129 None,
1130 "<div id=\"synthetic-implementors-list\"></div>",
1131 )
1132 )?;
1133 }
1134 }
1135
1136 let mut js_src_path: UrlPartsBuilder =
1208 iter::repeat_n("..", cx.current.len()).chain(iter::once("trait.impl")).collect();
1209 if let Some(did) = it.item_id.as_def_id()
1210 && let get_extern = { || cx.shared.cache.external_paths.get(&did).map(|s| &s.0) }
1211 && let Some(fqp) = cx.shared.cache.exact_paths.get(&did).or_else(get_extern)
1212 {
1213 js_src_path.extend(fqp[..fqp.len() - 1].iter().copied());
1214 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), fqp.last().unwrap()));
1215 } else {
1216 js_src_path.extend(cx.current.iter().copied());
1217 js_src_path.push_fmt(format_args!("{}.{}.js", it.type_(), it.name.unwrap()));
1218 }
1219 let extern_crates = fmt::from_fn(|f| {
1220 if !extern_crates.is_empty() {
1221 f.write_str(" data-ignore-extern-crates=\"")?;
1222 extern_crates.iter().map(|&cnum| tcx.crate_name(cnum)).joined(",", f)?;
1223 f.write_str("\"")?;
1224 }
1225 Ok(())
1226 });
1227 write!(
1228 w,
1229 "<script src=\"{src}\"{extern_crates} async></script>",
1230 src = js_src_path.finish()
1231 )
1232 })
1233}
1234
1235fn item_trait_alias(
1236 cx: &Context<'_>,
1237 it: &clean::Item,
1238 t: &clean::TraitAlias,
1239) -> impl fmt::Display {
1240 fmt::from_fn(|w| {
1241 wrap_item(w, |w| {
1242 write!(
1243 w,
1244 "{attrs}trait {name}{generics} = {bounds}{where_clause};",
1245 attrs = render_attributes_in_pre(it, "", cx),
1246 name = it.name.unwrap(),
1247 generics = t.generics.print(cx),
1248 bounds = print_bounds(&t.bounds, true, cx),
1249 where_clause =
1250 print_where_clause(&t.generics, cx, 0, Ending::NoNewline).maybe_display(),
1251 )
1252 })?;
1253
1254 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1255 write!(
1260 w,
1261 "{}",
1262 render_assoc_items(cx, it, it.item_id.expect_def_id(), AssocItemRender::All)
1263 )
1264 })
1265}
1266
1267fn item_type_alias(cx: &Context<'_>, it: &clean::Item, t: &clean::TypeAlias) -> impl fmt::Display {
1268 fmt::from_fn(|w| {
1269 wrap_item(w, |w| {
1270 write!(
1271 w,
1272 "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
1273 attrs = render_attributes_in_pre(it, "", cx),
1274 vis = visibility_print_with_space(it, cx),
1275 name = it.name.unwrap(),
1276 generics = t.generics.print(cx),
1277 where_clause =
1278 print_where_clause(&t.generics, cx, 0, Ending::Newline).maybe_display(),
1279 type_ = t.type_.print(cx),
1280 )
1281 })?;
1282
1283 write!(w, "{}", document(cx, it, None, HeadingOffset::H2))?;
1284
1285 if let Some(inner_type) = &t.inner_type {
1286 write!(w, "{}", write_section_heading("Aliased Type", "aliased-type", None, ""),)?;
1287
1288 match inner_type {
1289 clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive } => {
1290 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1291 let enum_def_id = ty.ty_adt_def().unwrap().did();
1292
1293 DisplayEnum {
1294 variants,
1295 generics: &t.generics,
1296 is_non_exhaustive: *is_non_exhaustive,
1297 def_id: enum_def_id,
1298 }
1299 .render_into(cx, it, true, w)?;
1300 }
1301 clean::TypeAliasInnerType::Union { fields } => {
1302 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1303 let union_def_id = ty.ty_adt_def().unwrap().did();
1304
1305 ItemUnion {
1306 cx,
1307 it,
1308 fields,
1309 generics: &t.generics,
1310 is_type_alias: true,
1311 def_id: union_def_id,
1312 }
1313 .render_into(w)?;
1314 }
1315 clean::TypeAliasInnerType::Struct { ctor_kind, fields } => {
1316 let ty = cx.tcx().type_of(it.def_id().unwrap()).instantiate_identity();
1317 let struct_def_id = ty.ty_adt_def().unwrap().did();
1318
1319 DisplayStruct {
1320 ctor_kind: *ctor_kind,
1321 generics: &t.generics,
1322 fields,
1323 def_id: struct_def_id,
1324 }
1325 .render_into(cx, it, true, w)?;
1326 }
1327 }
1328 } else {
1329 let def_id = it.item_id.expect_def_id();
1330 write!(
1335 w,
1336 "{}{}",
1337 render_assoc_items(cx, it, def_id, AssocItemRender::All),
1338 document_type_layout(cx, def_id)
1339 )?;
1340 }
1341
1342 let cache = &cx.shared.cache;
1415 if let Some(target_did) = t.type_.def_id(cache)
1416 && let get_extern = { || cache.external_paths.get(&target_did) }
1417 && let Some(&(ref target_fqp, target_type)) =
1418 cache.paths.get(&target_did).or_else(get_extern)
1419 && target_type.is_adt() && let Some(self_did) = it.item_id.as_def_id()
1421 && let get_local = { || cache.paths.get(&self_did).map(|(p, _)| p) }
1422 && let Some(self_fqp) = cache.exact_paths.get(&self_did).or_else(get_local)
1423 {
1424 let mut js_src_path: UrlPartsBuilder =
1425 iter::repeat_n("..", cx.current.len()).chain(iter::once("type.impl")).collect();
1426 js_src_path.extend(target_fqp[..target_fqp.len() - 1].iter().copied());
1427 js_src_path.push_fmt(format_args!("{target_type}.{}.js", target_fqp.last().unwrap()));
1428 let self_path = join_path_syms(self_fqp);
1429 write!(
1430 w,
1431 "<script src=\"{src}\" data-self-path=\"{self_path}\" async></script>",
1432 src = js_src_path.finish(),
1433 )?;
1434 }
1435 Ok(())
1436 })
1437}
1438
1439item_template!(
1440 #[template(path = "item_union.html")]
1441 struct ItemUnion<'a, 'cx> {
1442 cx: &'a Context<'cx>,
1443 it: &'a clean::Item,
1444 fields: &'a [clean::Item],
1445 generics: &'a clean::Generics,
1446 is_type_alias: bool,
1447 def_id: DefId,
1448 },
1449 methods = [document, document_type_layout, render_assoc_items]
1450);
1451
1452impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> {
1453 fn render_union(&self) -> impl Display {
1454 render_union(self.it, Some(&self.generics), &self.fields, self.cx)
1455 }
1456
1457 fn document_field(&self, field: &'a clean::Item) -> impl Display {
1458 document(self.cx, field, Some(self.it), HeadingOffset::H3)
1459 }
1460
1461 fn stability_field(&self, field: &clean::Item) -> Option<String> {
1462 field.stability_class(self.cx.tcx())
1463 }
1464
1465 fn print_ty(&self, ty: &'a clean::Type) -> impl Display {
1466 ty.print(self.cx)
1467 }
1468
1469 fn fields_iter(&self) -> impl Iterator<Item = (&'a clean::Item, &'a clean::Type)> {
1476 self.fields.iter().filter_map(|f| match f.kind {
1477 clean::StructFieldItem(ref ty) => Some((f, ty)),
1478 _ => None,
1479 })
1480 }
1481
1482 fn render_attributes_in_pre(&self) -> impl fmt::Display {
1483 fmt::from_fn(move |f| {
1484 if self.is_type_alias {
1485 if let Some(repr) = clean::repr_attributes(
1487 self.cx.tcx(),
1488 self.cx.cache(),
1489 self.def_id,
1490 ItemType::Union,
1491 ) {
1492 writeln!(f, "{repr}")?;
1493 };
1494 } else {
1495 for a in self.it.attributes(self.cx.tcx(), self.cx.cache()) {
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_path_syms(&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}