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