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