1pub(crate) mod search_index;
30
31#[cfg(test)]
32mod tests;
33
34mod context;
35mod ordered_json;
36mod print_item;
37pub(crate) mod sidebar;
38mod sorted_template;
39mod type_layout;
40mod write_shared;
41
42use std::borrow::{Borrow, Cow};
43use std::cmp::Ordering;
44use std::collections::{BTreeMap, VecDeque};
45use std::fmt::{self, Display as _, Write};
46use std::iter::Peekable;
47use std::path::PathBuf;
48use std::{fs, str};
49
50use askama::Template;
51use indexmap::IndexMap;
52use itertools::Either;
53use rustc_ast::join_path_syms;
54use rustc_attr_ir::{
55 AttributeKind, ConstStability, DeprecatedSince, Deprecation, NotableTraitColor, RustcVersion,
56 StabilityLevel, StableSince, find_attr,
57};
58use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
59use rustc_hir::Mutability;
60use rustc_hir::def::DefKind;
61use rustc_hir::def_id::{DefId, DefIdSet};
62use rustc_middle::ty::print::PrintTraitRefExt;
63use rustc_middle::ty::{self, TyCtxt};
64use rustc_span::DUMMY_SP;
65use rustc_span::symbol::{Symbol, sym};
66use tracing::{debug, info};
67
68pub(crate) use self::context::*;
69pub(crate) use self::write_shared::*;
70use crate::clean::{self, Defaultness, Item, ItemId, ItemKind, RenderedLink};
71use crate::display::{Joined as _, MaybeDisplay as _};
72use crate::error::Error;
73use crate::formats::Impl;
74use crate::formats::cache::Cache;
75use crate::formats::item_type::ItemType;
76use crate::html::escape::Escape;
77use crate::html::format::{
78 Ending, HrefError, HrefInfo, PrintWithSpace, full_print_fn_decl, href, print_abi_with_space,
79 print_constness_with_space, print_generic_bounds, print_generics, print_impl, print_path,
80 print_type, print_where_clause, visibility_print_with_space,
81};
82use crate::html::markdown::{
83 HeadingOffset, IdMap, Markdown, MarkdownItemInfo, MarkdownSummaryLine, short_markdown_summary,
84};
85use crate::html::render::print_item::ImplString;
86use crate::html::render::search_index::get_function_type_for_search;
87use crate::html::static_files::SCRAPE_EXAMPLES_HELP_MD;
88use crate::html::{highlight, sources};
89use crate::scrape_examples::{CallData, CallLocation};
90use crate::{DOC_RUST_LANG_ORG_VERSION, try_none};
91
92pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display {
93 fmt::from_fn(move |f| {
94 if !v.ends_with('/') && !v.is_empty() { write!(f, "{v}/") } else { f.write_str(v) }
95 })
96}
97
98#[derive(Copy, Clone, Debug)]
101enum AssocItemRender<'a> {
102 All,
103 DerefFor {
104 trait_: &'a clean::Path,
105 type_: &'a clean::Type,
106 resolved_type: &'a clean::Type,
107 deref_mut_: bool,
108 deref_impl_def_id: DefId,
109 },
110}
111
112impl AssocItemRender<'_> {
113 fn render_mode(&self, tcx: TyCtxt<'_>) -> RenderMode {
114 match self {
115 Self::All => RenderMode::Normal,
116 &Self::DerefFor { deref_mut_, deref_impl_def_id, .. } => {
117 let is_deref_target_copy =
118 compute_if_deref_target_implements_copy(tcx, deref_impl_def_id);
119 RenderMode::ForDeref { mut_: deref_mut_, is_deref_target_copy }
120 }
121 }
122 }
123
124 fn class(&self) -> Option<&'static str> {
125 if let Self::DerefFor { .. } = self { Some("impl-items") } else { None }
126 }
127}
128
129#[derive(Copy, Clone, PartialEq)]
132enum RenderMode {
133 Normal,
134 ForDeref { mut_: bool, is_deref_target_copy: bool },
135}
136
137#[derive(Debug, Clone)]
141pub(crate) struct IndexItemInfo {
142 pub(crate) ty: ItemType,
143 pub(crate) desc: String,
144 pub(crate) search_type: Option<IndexItemFunctionType>,
145 pub(crate) aliases: Box<[Symbol]>,
146 pub(crate) deprecation: Option<Deprecation>,
147 pub(crate) is_unstable: bool,
148}
149
150impl IndexItemInfo {
151 pub(crate) fn new(
152 tcx: TyCtxt<'_>,
153 cache: &Cache,
154 item: &Item,
155 parent_did: Option<DefId>,
156 impl_generics: Option<&(clean::Type, clean::Generics)>,
157 ty: ItemType,
158 ) -> Self {
159 let desc = short_markdown_summary(&item.doc_value(), &item.link_names(cache));
160 let search_type = get_function_type_for_search(item, tcx, impl_generics, parent_did, cache);
161 let aliases = item.attrs.get_doc_aliases();
162 let deprecation = item.deprecation(tcx);
163 let is_unstable = item.is_unstable();
164 Self { ty, desc, search_type, aliases, deprecation, is_unstable }
165 }
166}
167
168#[derive(Debug, Clone)]
171pub(crate) struct IndexItem {
172 pub(crate) defid: Option<DefId>,
173 pub(crate) name: Symbol,
174 pub(crate) module_path: Vec<Symbol>,
175 pub(crate) parent: Option<DefId>,
176 pub(crate) parent_idx: Option<usize>,
177 pub(crate) trait_parent: Option<DefId>,
178 pub(crate) trait_parent_idx: Option<usize>,
179 pub(crate) exact_module_path: Option<Vec<Symbol>>,
180 pub(crate) impl_id: Option<DefId>,
181 pub(crate) info: IndexItemInfo,
182}
183
184#[derive(Clone, Debug, Eq, PartialEq)]
186struct RenderType {
187 id: Option<RenderTypeId>,
188 generics: Option<Vec<RenderType>>,
189 bindings: Option<Vec<(RenderTypeId, Vec<RenderType>)>>,
190}
191
192impl RenderType {
193 fn size(&self) -> usize {
194 let mut size = 1;
195 if let Some(generics) = &self.generics {
196 size += generics.iter().map(RenderType::size).sum::<usize>();
197 }
198 if let Some(bindings) = &self.bindings {
199 for (_, constraints) in bindings.iter() {
200 size += 1;
201 size += constraints.iter().map(RenderType::size).sum::<usize>();
202 }
203 }
204 size
205 }
206 fn write_to_string(&self, string: &mut String) {
211 fn write_optional_id(id: Option<RenderTypeId>, string: &mut String) {
212 match id {
214 Some(id) => id.write_to_string(string),
215 None => string.push('`'),
216 }
217 }
218 if self.generics.is_some() || self.bindings.is_some() {
222 string.push('{');
223 write_optional_id(self.id, string);
224 string.push('{');
225 for generic in self.generics.as_deref().unwrap_or_default() {
226 generic.write_to_string(string);
227 }
228 string.push('}');
229 if self.bindings.is_some() {
230 string.push('{');
231 for binding in self.bindings.as_deref().unwrap_or_default() {
232 string.push('{');
233 binding.0.write_to_string(string);
234 string.push('{');
235 for constraint in &binding.1[..] {
236 constraint.write_to_string(string);
237 }
238 string.push_str("}}");
239 }
240 string.push('}');
241 }
242 string.push('}');
243 } else {
244 write_optional_id(self.id, string);
245 }
246 }
247 fn read_from_bytes(string: &[u8]) -> (RenderType, usize) {
248 let mut i = 0;
249 if string[i] == b'{' {
250 i += 1;
251 let (id, offset) = RenderTypeId::read_from_bytes(&string[i..]);
252 i += offset;
253 let generics = if string[i] == b'{' {
254 i += 1;
255 let mut generics = Vec::new();
256 while string[i] != b'}' {
257 let (ty, offset) = RenderType::read_from_bytes(&string[i..]);
258 i += offset;
259 generics.push(ty);
260 }
261 assert!(string[i] == b'}');
262 i += 1;
263 Some(generics)
264 } else {
265 None
266 };
267 let bindings = if string[i] == b'{' {
268 i += 1;
269 let mut bindings = Vec::new();
270 while string[i] == b'{' {
271 i += 1;
272 let (binding, boffset) = RenderTypeId::read_from_bytes(&string[i..]);
273 i += boffset;
274 let mut bconstraints = Vec::new();
275 assert!(string[i] == b'{');
276 i += 1;
277 while string[i] != b'}' {
278 let (constraint, coffset) = RenderType::read_from_bytes(&string[i..]);
279 i += coffset;
280 bconstraints.push(constraint);
281 }
282 assert!(string[i] == b'}');
283 i += 1;
284 bindings.push((binding.unwrap(), bconstraints));
285 assert!(string[i] == b'}');
286 i += 1;
287 }
288 assert!(string[i] == b'}');
289 i += 1;
290 Some(bindings)
291 } else {
292 None
293 };
294 assert!(string[i] == b'}');
295 i += 1;
296 (RenderType { id, generics, bindings }, i)
297 } else {
298 let (id, offset) = RenderTypeId::read_from_bytes(string);
299 i += offset;
300 (RenderType { id, generics: None, bindings: None }, i)
301 }
302 }
303}
304
305#[derive(Clone, Copy, Debug, Eq, PartialEq)]
306enum RenderTypeId {
307 DefId(DefId),
308 Primitive(clean::PrimitiveType),
309 AssociatedType(Symbol),
310 Index(isize),
311 Mut,
312}
313
314impl RenderTypeId {
315 fn write_to_string(&self, string: &mut String) {
316 let id: i32 = match &self {
317 RenderTypeId::Index(idx) if *idx >= 0 => (idx + 1isize).try_into().unwrap(),
320 RenderTypeId::Index(idx) => (*idx).try_into().unwrap(),
322 _ => panic!("must convert render types to indexes before serializing"),
323 };
324 search_index::encode::write_signed_vlqhex_to_string(id, string);
325 }
326 fn read_from_bytes(string: &[u8]) -> (Option<RenderTypeId>, usize) {
327 let Some((value, offset)) = search_index::encode::read_signed_vlqhex_from_string(string)
328 else {
329 return (None, 0);
330 };
331 let value = isize::try_from(value).unwrap();
332 let ty = match value {
333 ..0 => Some(RenderTypeId::Index(value)),
334 0 => None,
335 1.. => Some(RenderTypeId::Index(value - 1)),
336 };
337 (ty, offset)
338 }
339}
340
341#[derive(Clone, Debug, Eq, PartialEq)]
343pub(crate) struct IndexItemFunctionType {
344 inputs: Vec<RenderType>,
345 output: Vec<RenderType>,
346 where_clause: Vec<Vec<RenderType>>,
347 param_names: Vec<Option<Symbol>>,
348}
349
350impl IndexItemFunctionType {
351 fn size(&self) -> usize {
352 self.inputs.iter().map(RenderType::size).sum::<usize>()
353 + self.output.iter().map(RenderType::size).sum::<usize>()
354 + self
355 .where_clause
356 .iter()
357 .map(|constraints| constraints.iter().map(RenderType::size).sum::<usize>())
358 .sum::<usize>()
359 }
360 fn read_from_string_without_param_names(string: &[u8]) -> (IndexItemFunctionType, usize) {
361 let mut i = 0;
362 if string[i] == b'`' {
363 return (
364 IndexItemFunctionType {
365 inputs: Vec::new(),
366 output: Vec::new(),
367 where_clause: Vec::new(),
368 param_names: Vec::new(),
369 },
370 1,
371 );
372 }
373 assert_eq!(b'{', string[i]);
374 i += 1;
375 fn read_args_from_string(string: &[u8]) -> (Vec<RenderType>, usize) {
376 let mut i = 0;
377 let mut params = Vec::new();
378 if string[i] == b'{' {
379 i += 1;
381 while string[i] != b'}' {
382 let (ty, offset) = RenderType::read_from_bytes(&string[i..]);
383 i += offset;
384 params.push(ty);
385 }
386 i += 1;
387 } else if string[i] != b'}' {
388 let (tyid, offset) = RenderTypeId::read_from_bytes(&string[i..]);
389 params.push(RenderType { id: tyid, generics: None, bindings: None });
390 i += offset;
391 }
392 (params, i)
393 }
394 let (inputs, offset) = read_args_from_string(&string[i..]);
395 i += offset;
396 let (output, offset) = read_args_from_string(&string[i..]);
397 i += offset;
398 let mut where_clause = Vec::new();
399 while string[i] != b'}' {
400 let (constraint, offset) = read_args_from_string(&string[i..]);
401 i += offset;
402 where_clause.push(constraint);
403 }
404 assert_eq!(b'}', string[i], "{} {}", String::from_utf8_lossy(&string), i);
405 i += 1;
406 (IndexItemFunctionType { inputs, output, where_clause, param_names: Vec::new() }, i)
407 }
408 fn write_to_string_without_param_names<'a>(&'a self, string: &mut String) {
409 let has_missing = self
412 .inputs
413 .iter()
414 .chain(self.output.iter())
415 .any(|i| i.id.is_none() && i.generics.is_none());
416 if has_missing {
417 string.push('`');
418 } else {
419 string.push('{');
420 match &self.inputs[..] {
421 [one] if one.generics.is_none() && one.bindings.is_none() => {
422 one.write_to_string(string);
423 }
424 _ => {
425 string.push('{');
426 for item in &self.inputs[..] {
427 item.write_to_string(string);
428 }
429 string.push('}');
430 }
431 }
432 match &self.output[..] {
433 [] if self.where_clause.is_empty() => {}
434 [one] if one.generics.is_none() && one.bindings.is_none() => {
435 one.write_to_string(string);
436 }
437 _ => {
438 string.push('{');
439 for item in &self.output[..] {
440 item.write_to_string(string);
441 }
442 string.push('}');
443 }
444 }
445 for constraint in &self.where_clause {
446 if let [one] = &constraint[..]
447 && one.generics.is_none()
448 && one.bindings.is_none()
449 {
450 one.write_to_string(string);
451 } else {
452 string.push('{');
453 for item in &constraint[..] {
454 item.write_to_string(string);
455 }
456 string.push('}');
457 }
458 }
459 string.push('}');
460 }
461 }
462}
463
464#[derive(Debug, Clone)]
465pub(crate) struct StylePath {
466 pub(crate) path: PathBuf,
468}
469
470impl StylePath {
471 pub(crate) fn basename(&self) -> Result<String, Error> {
472 Ok(try_none!(try_none!(self.path.file_stem(), &self.path).to_str(), &self.path).to_string())
473 }
474}
475
476#[derive(Debug, Eq, PartialEq, Hash)]
477struct ItemEntry {
478 url: String,
479 name: String,
480}
481
482impl ItemEntry {
483 fn new(mut url: String, name: String) -> ItemEntry {
484 while url.starts_with('/') {
485 url.remove(0);
486 }
487 ItemEntry { url, name }
488 }
489}
490
491impl ItemEntry {
492 fn print(&self) -> impl fmt::Display {
493 fmt::from_fn(move |f| write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name)))
494 }
495}
496
497impl PartialOrd for ItemEntry {
498 fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> {
499 Some(self.cmp(other))
500 }
501}
502
503impl Ord for ItemEntry {
504 fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering {
505 self.name.cmp(&other.name)
506 }
507}
508
509#[derive(Debug)]
510struct AllTypes {
511 structs: FxIndexSet<ItemEntry>,
512 enums: FxIndexSet<ItemEntry>,
513 unions: FxIndexSet<ItemEntry>,
514 primitives: FxIndexSet<ItemEntry>,
515 traits: FxIndexSet<ItemEntry>,
516 macros: FxIndexSet<ItemEntry>,
517 functions: FxIndexSet<ItemEntry>,
518 type_aliases: FxIndexSet<ItemEntry>,
519 statics: FxIndexSet<ItemEntry>,
520 constants: FxIndexSet<ItemEntry>,
521 attribute_macros: FxIndexSet<ItemEntry>,
522 derive_macros: FxIndexSet<ItemEntry>,
523 trait_aliases: FxIndexSet<ItemEntry>,
524}
525
526impl AllTypes {
527 fn new() -> AllTypes {
528 let new_set = |cap| FxIndexSet::with_capacity_and_hasher(cap, Default::default());
529 AllTypes {
530 structs: new_set(100),
531 enums: new_set(100),
532 unions: new_set(100),
533 primitives: new_set(26),
534 traits: new_set(100),
535 macros: new_set(100),
536 functions: new_set(100),
537 type_aliases: new_set(100),
538 statics: new_set(100),
539 constants: new_set(100),
540 attribute_macros: new_set(100),
541 derive_macros: new_set(100),
542 trait_aliases: new_set(100),
543 }
544 }
545
546 fn add_item_entry(&mut self, item_type: ItemType, new_url: String, name: String) {
547 match item_type {
548 ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)),
549 ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)),
550 ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)),
551 ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)),
552 ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)),
553 ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)),
554 ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)),
555 ItemType::TypeAlias => self.type_aliases.insert(ItemEntry::new(new_url, name)),
556 ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)),
557 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
558 ItemType::ProcAttribute | ItemType::DeclMacroAttribute => {
559 self.attribute_macros.insert(ItemEntry::new(new_url, name))
560 }
561 ItemType::ProcDerive | ItemType::DeclMacroDerive => {
562 self.derive_macros.insert(ItemEntry::new(new_url, name))
563 }
564 ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
565 _ => true,
566 };
567 }
568
569 fn append(&mut self, item_name: String, item: &clean::Item) {
570 let mut url: Vec<_> = item_name.split("::").skip(1).collect();
571 if let Some(name) = url.pop() {
572 let new_url = format!("{}/{}", url.join("/"), item.html_filename());
573 url.push(name);
574 let name = url.join("::");
575 for type_ in item.types() {
576 self.add_item_entry(type_, new_url.clone(), name.clone());
577 }
578 }
579 }
580
581 fn item_sections(&self) -> FxHashSet<ItemSection> {
582 let mut sections = FxHashSet::default();
583
584 if !self.structs.is_empty() {
585 sections.insert(ItemSection::Structs);
586 }
587 if !self.enums.is_empty() {
588 sections.insert(ItemSection::Enums);
589 }
590 if !self.unions.is_empty() {
591 sections.insert(ItemSection::Unions);
592 }
593 if !self.primitives.is_empty() {
594 sections.insert(ItemSection::PrimitiveTypes);
595 }
596 if !self.traits.is_empty() {
597 sections.insert(ItemSection::Traits);
598 }
599 if !self.macros.is_empty() {
600 sections.insert(ItemSection::Macros);
601 }
602 if !self.functions.is_empty() {
603 sections.insert(ItemSection::Functions);
604 }
605 if !self.type_aliases.is_empty() {
606 sections.insert(ItemSection::TypeAliases);
607 }
608 if !self.statics.is_empty() {
609 sections.insert(ItemSection::Statics);
610 }
611 if !self.constants.is_empty() {
612 sections.insert(ItemSection::Constants);
613 }
614 if !self.attribute_macros.is_empty() {
615 sections.insert(ItemSection::AttributeMacros);
616 }
617 if !self.derive_macros.is_empty() {
618 sections.insert(ItemSection::DeriveMacros);
619 }
620 if !self.trait_aliases.is_empty() {
621 sections.insert(ItemSection::TraitAliases);
622 }
623
624 sections
625 }
626
627 fn print(&self) -> impl fmt::Display {
628 fn print_entries(e: &FxIndexSet<ItemEntry>, kind: ItemSection) -> impl fmt::Display {
629 fmt::from_fn(move |f| {
630 if e.is_empty() {
631 return Ok(());
632 }
633
634 let mut e: Vec<&ItemEntry> = e.iter().collect();
635 e.sort();
636 write!(
637 f,
638 "<h3 id=\"{id}\">{title}</h3><ul class=\"all-items\">",
639 id = kind.id(),
640 title = kind.name(),
641 )?;
642
643 for s in e.iter() {
644 write!(f, "<li>{}</li>", s.print())?;
645 }
646
647 f.write_str("</ul>")
648 })
649 }
650
651 fmt::from_fn(|f| {
652 f.write_str(
653 "<div class=\"main-heading\">\
654 <h1>List of all items</h1>\
655 <rustdoc-toolbar></rustdoc-toolbar>\
656 </div>",
657 )?;
658 print_entries(&self.structs, ItemSection::Structs).fmt(f)?;
661 print_entries(&self.enums, ItemSection::Enums).fmt(f)?;
662 print_entries(&self.unions, ItemSection::Unions).fmt(f)?;
663 print_entries(&self.primitives, ItemSection::PrimitiveTypes).fmt(f)?;
664 print_entries(&self.traits, ItemSection::Traits).fmt(f)?;
665 print_entries(&self.macros, ItemSection::Macros).fmt(f)?;
666 print_entries(&self.attribute_macros, ItemSection::AttributeMacros).fmt(f)?;
667 print_entries(&self.derive_macros, ItemSection::DeriveMacros).fmt(f)?;
668 print_entries(&self.functions, ItemSection::Functions).fmt(f)?;
669 print_entries(&self.type_aliases, ItemSection::TypeAliases).fmt(f)?;
670 print_entries(&self.trait_aliases, ItemSection::TraitAliases).fmt(f)?;
671 print_entries(&self.statics, ItemSection::Statics).fmt(f)?;
672 print_entries(&self.constants, ItemSection::Constants).fmt(f)?;
673 Ok(())
674 })
675 }
676}
677
678fn scrape_examples_help() -> String {
679 let mut content = SCRAPE_EXAMPLES_HELP_MD.to_owned();
680 content.push_str(&format!(
681 "## More information\n\n\
682 If you want more information about this feature, please read the [corresponding chapter in \
683 the Rustdoc book]({DOC_RUST_LANG_ORG_VERSION}/rustdoc/scraped-examples.html)."
684 ));
685
686 format!(
687 "<div class=\"main-heading\">\
688 <h1>About scraped examples</h1>\
689 </div>\
690 <div>{}</div>",
691 fmt::from_fn(|f| Markdown {
692 content: &content,
693 links: &[],
694 ids: &mut IdMap::default(),
695 error_codes: crate::html::markdown::ErrorCodes::No,
697 edition: rustc_span::edition::LATEST_STABLE_EDITION,
698 playground: &Default::default(),
699 heading_offset: HeadingOffset::H1,
700 }
701 .write_into(f))
702 )
703}
704
705fn document(
706 cx: &Context<'_>,
707 item: &clean::Item,
708 parent: Option<&clean::Item>,
709 heading_offset: HeadingOffset,
710) -> impl fmt::Display {
711 if let Some(ref name) = item.name {
712 info!("Documenting {name}");
713 }
714
715 fmt::from_fn(move |f| {
716 document_item_info(cx, item, parent).render_into(f)?;
717 if parent.is_none() {
718 write!(f, "{}", document_full_collapsible(item, cx, heading_offset))
719 } else {
720 write!(f, "{}", document_full(item, cx, heading_offset))
721 }
722 })
723}
724
725fn render_markdown(
727 cx: &Context<'_>,
728 md_text: &str,
729 links: Vec<RenderedLink>,
730 heading_offset: HeadingOffset,
731) -> impl fmt::Display {
732 fmt::from_fn(move |f| {
733 f.write_str("<div class=\"docblock\">")?;
734 Markdown {
735 content: md_text,
736 links: &links,
737 ids: &mut cx.id_map.borrow_mut(),
738 error_codes: cx.shared.codes,
739 edition: cx.shared.edition(),
740 playground: &cx.shared.playground,
741 heading_offset,
742 }
743 .write_into(&mut *f)?;
744 f.write_str("</div>")
745 })
746}
747
748fn document_short(
751 item: &clean::Item,
752 cx: &Context<'_>,
753 link: AssocItemLink<'_>,
754 parent: &clean::Item,
755 show_def_docs: bool,
756) -> impl fmt::Display {
757 fmt::from_fn(move |f| {
758 document_item_info(cx, item, Some(parent)).render_into(f)?;
759 if !show_def_docs {
760 return Ok(());
761 }
762 let s = item.doc_value();
763 if !s.is_empty() {
764 let (mut summary_html, has_more_content) =
765 MarkdownSummaryLine(&s, &item.links(cx)).into_string_with_has_more_content();
766
767 let link = if has_more_content {
768 let link = fmt::from_fn(|f| {
769 write!(
770 f,
771 " <a{}>Read more</a>",
772 assoc_href_attr(item, link, cx).maybe_display()
773 )
774 });
775
776 if let Some(idx) = summary_html.rfind("</p>") {
777 summary_html.insert_str(idx, &link.to_string());
778 None
779 } else {
780 Some(link)
781 }
782 } else {
783 None
784 }
785 .maybe_display();
786
787 write!(f, "<div class='docblock'>{summary_html}{link}</div>")?;
788 }
789 Ok(())
790 })
791}
792
793fn document_full_collapsible(
794 item: &clean::Item,
795 cx: &Context<'_>,
796 heading_offset: HeadingOffset,
797) -> impl fmt::Display {
798 document_full_inner(item, cx, true, heading_offset)
799}
800
801fn document_full(
802 item: &clean::Item,
803 cx: &Context<'_>,
804 heading_offset: HeadingOffset,
805) -> impl fmt::Display {
806 document_full_inner(item, cx, false, heading_offset)
807}
808
809fn document_full_inner(
810 item: &clean::Item,
811 cx: &Context<'_>,
812 is_collapsible: bool,
813 heading_offset: HeadingOffset,
814) -> impl fmt::Display {
815 fmt::from_fn(move |f| {
816 if let Some(s) = item.opt_doc_value() {
817 debug!("Doc block: =====\n{s}\n=====");
818 if is_collapsible {
819 write!(
820 f,
821 "<details class=\"toggle top-doc\" open>\
822 <summary class=\"hideme\">\
823 <span>Expand description</span>\
824 </summary>{}</details>",
825 render_markdown(cx, &s, item.links(cx), heading_offset)
826 )?;
827 } else {
828 write!(f, "{}", render_markdown(cx, &s, item.links(cx), heading_offset))?;
829 }
830 }
831
832 if let ItemKind::Function(..)
833 | ItemKind::AssocFunction(clean::AssocFunction { body: Some(_), .. }) =
834 item.kind.unstripped()
835 {
836 render_call_locations(f, cx, item)?;
837 }
838 Ok(())
839 })
840}
841
842#[derive(Template)]
843#[template(path = "item_info.html")]
844struct ItemInfo {
845 items: Vec<ShortItemInfo>,
846}
847fn document_item_info(
853 cx: &Context<'_>,
854 item: &clean::Item,
855 parent: Option<&clean::Item>,
856) -> ItemInfo {
857 let items = short_item_info(item, cx, parent);
858 ItemInfo { items }
859}
860
861fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> {
862 let cfg = match (&item.cfg, parent.and_then(|p| p.cfg.as_ref())) {
863 (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg),
864 (cfg, _) => cfg.as_deref().cloned(),
865 };
866
867 debug!(
868 "Portability {name:?} {item_cfg:?} (parent: {parent:?}) - {parent_cfg:?} = {cfg:?}",
869 name = item.name,
870 item_cfg = item.cfg,
871 parent_cfg = parent.and_then(|p| p.cfg.as_ref()),
872 );
873
874 Some(cfg?.render_long_html())
875}
876
877#[derive(Template)]
878#[template(path = "short_item_info.html")]
879enum ShortItemInfo {
880 Deprecation {
882 message: String,
883 },
884 Unstable {
887 feature: String,
888 tracking: Option<(String, u32)>,
889 },
890 Portability {
891 message: String,
892 },
893}
894
895fn short_item_info(
898 item: &clean::Item,
899 cx: &Context<'_>,
900 parent: Option<&clean::Item>,
901) -> Vec<ShortItemInfo> {
902 let mut extra_info = vec![];
903
904 if let Some(depr @ Deprecation { note, since, suggestion: _ }) = item.deprecation(cx.tcx()) {
905 let mut message = match since {
908 DeprecatedSince::RustcVersion(version) => {
909 if depr.is_in_effect() {
910 format!("Deprecated since {version}")
911 } else {
912 format!("Deprecating in {version}")
913 }
914 }
915 DeprecatedSince::Future => String::from("Deprecating in a future version"),
916 DeprecatedSince::NonStandard(since) => {
917 format!("Deprecated since {}", Escape(since.as_str()))
918 }
919 DeprecatedSince::Unspecified | DeprecatedSince::Err => String::from("Deprecated"),
920 };
921
922 if let Some(note) = note {
923 let note = note.as_str();
924 let mut id_map = cx.id_map.borrow_mut();
925 let links = item.links(cx);
926 let html = MarkdownItemInfo::new(note, &links, &mut id_map);
927 message.push_str(": ");
928 html.write_into(&mut message).unwrap();
929 }
930 extra_info.push(ShortItemInfo::Deprecation { message });
931 }
932
933 if let Some((StabilityLevel::Unstable { reason: _, issue, .. }, feature)) = item
936 .stability(cx.tcx())
937 .as_ref()
938 .filter(|stab| stab.feature != sym::rustc_private)
939 .map(|stab| (stab.level, stab.feature))
940 {
941 let tracking = if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue)
942 {
943 Some((url.clone(), issue.get()))
944 } else {
945 None
946 };
947 extra_info.push(ShortItemInfo::Unstable { feature: feature.to_string(), tracking });
948 }
949
950 if let Some(message) = portability(item, parent) {
951 extra_info.push(ShortItemInfo::Portability { message });
952 }
953
954 extra_info
955}
956
957fn impl_trait_key(cx: &Context<'_>, i: &Impl) -> Option<String> {
959 let trait_ = i.inner_impl().trait_.as_ref()?;
960 let prefix = match i.inner_impl().polarity {
961 ty::ImplPolarity::Positive => "",
962 ty::ImplPolarity::Negative => "!",
963 };
964 Some(format!("{prefix}{:#}", print_path(trait_, cx)))
965}
966
967fn render_impls<'a, 'cx>(
970 cx: &'a Context<'cx>,
971 mut impls: Vec<&'a Impl>,
972 containing_item: &'a clean::Item,
973 toggle_open_by_default: bool,
974) -> impl fmt::Display + use<'a, 'cx> {
975 impls.sort_by_cached_key(|imp| {
976 let prefix = match imp.inner_impl().polarity {
977 ty::ImplPolarity::Positive => Ordering::Greater,
978 ty::ImplPolarity::Negative => Ordering::Less,
979 };
980 (prefix, ImplString::new_path(imp, cx))
981 });
982 fmt::from_fn(move |f| {
986 impls
987 .iter()
988 .map(|i| {
989 fmt::from_fn(|f| {
990 let did = i.trait_did().unwrap();
991 let provided_trait_methods = i.inner_impl().provided_trait_methods(cx.tcx());
992 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_trait_methods);
993 render_impl(
994 cx,
995 i,
996 containing_item,
997 assoc_link,
998 RenderMode::Normal,
999 None,
1000 &[],
1001 ImplRenderingParameters {
1002 show_def_docs: true,
1003 show_default_items: true,
1004 show_non_assoc_items: true,
1005 toggle_open_by_default,
1006 },
1007 )
1008 .fmt(f)
1009 })
1010 })
1011 .joined("", f)
1012 })
1013}
1014
1015fn assoc_href_attr(
1017 it: &clean::Item,
1018 link: AssocItemLink<'_>,
1019 cx: &Context<'_>,
1020) -> Option<impl fmt::Display> {
1021 let name = it.name.unwrap();
1022 let item_type = it.type_();
1023
1024 enum Href<'a> {
1025 AnchorId(&'a str),
1026 Anchor(ItemType),
1027 Url(String, ItemType),
1028 }
1029
1030 let href = match link {
1031 AssocItemLink::Anchor(Some(id)) => Href::AnchorId(id),
1032 AssocItemLink::Anchor(None) => Href::Anchor(item_type),
1033 AssocItemLink::GotoSource(did, provided_methods) => {
1034 let item_type = match item_type {
1037 ItemType::AssocFnWithBody | ItemType::AssocFnWithoutBody => {
1038 if provided_methods.contains(&name) {
1039 ItemType::AssocFnWithBody
1040 } else {
1041 ItemType::AssocFnWithoutBody
1042 }
1043 }
1044 item_type => item_type,
1045 };
1046
1047 match href(did.expect_def_id(), cx) {
1048 Ok(HrefInfo { url, .. }) => Href::Url(url, item_type),
1049 Err(HrefError::DocumentationNotBuilt) => return None,
1061 Err(_) => Href::Anchor(item_type),
1062 }
1063 }
1064 };
1065
1066 let href = fmt::from_fn(move |f| match &href {
1067 Href::AnchorId(id) => write!(f, "#{id}"),
1068 Href::Url(url, item_type) => {
1069 write!(f, "{url}#{item_type}.{name}")
1070 }
1071 Href::Anchor(item_type) => {
1072 write!(f, "#{item_type}.{name}")
1073 }
1074 });
1075
1076 Some(fmt::from_fn(move |f| write!(f, " href=\"{href}\"")))
1079}
1080
1081fn assoc_const(
1082 it: &clean::Item,
1083 ct: &clean::AssocConstant,
1084 parent: ItemType,
1085 link: AssocItemLink<'_>,
1086 indent: usize,
1087 ending: Ending,
1088 cx: &Context<'_>,
1089) -> impl fmt::Display {
1090 let tcx = cx.tcx();
1091 fmt::from_fn(move |w| {
1092 render_attributes_in_code(w, it, &" ".repeat(indent), cx)?;
1093 write!(
1094 w,
1095 "{indent}{vis}const <a{href} class=\"constant\">{name}</a>{generics}: {ty}",
1096 indent = " ".repeat(indent),
1097 vis = visibility_print_with_space(it, cx),
1098 href = assoc_href_attr(it, link, cx).maybe_display(),
1099 name = it.name.as_ref().unwrap(),
1100 generics = print_generics(&ct.generics, cx),
1101 ty = print_type(&ct.type_, cx),
1102 )?;
1103 if let Some(body) = &ct.body {
1104 let body = body.rendered(tcx);
1105 if parent == ItemType::Trait || body != "_" {
1112 write!(w, " = {}", Escape(&body))?;
1113 }
1114 }
1115 let where_clause = print_where_clause(&ct.generics, cx, indent, ending).maybe_display();
1116 write!(w, "{where_clause}")
1117 })
1118}
1119
1120fn assoc_ty(
1121 it: &clean::Item,
1122 ty: &clean::AssocType,
1123 link: AssocItemLink<'_>,
1124 indent: usize,
1125 ending: Ending,
1126 cx: &Context<'_>,
1127) -> impl fmt::Display {
1128 fmt::from_fn(move |w| {
1129 render_attributes_in_code(w, it, &" ".repeat(indent), cx)?;
1130 write!(
1131 w,
1132 "{indent}{vis}type <a{href} class=\"associatedtype\">{name}</a>{generics}",
1133 indent = " ".repeat(indent),
1134 vis = visibility_print_with_space(it, cx),
1135 href = assoc_href_attr(it, link, cx).maybe_display(),
1136 name = it.name.as_ref().unwrap(),
1137 generics = print_generics(&ty.generics, cx),
1138 )?;
1139 if !ty.bounds.is_empty() {
1140 write!(w, ": {}", print_generic_bounds(&ty.bounds, cx))?;
1141 }
1142 if let Some(type_) = &ty.type_ {
1144 let type_ = type_.middle_type.as_ref().unwrap_or(&type_.type_);
1145 write!(w, " = {}", print_type(type_, cx))?;
1146 }
1147 write!(w, "{}", print_where_clause(&ty.generics, cx, indent, ending).maybe_display())
1148 })
1149}
1150
1151fn assoc_fn(
1152 it: &clean::Item,
1153 fn_: &clean::AssocFunction,
1154 link: AssocItemLink<'_>,
1155 indent: usize,
1156 ending: Ending,
1157 render_mode: RenderMode,
1158 cx: &Context<'_>,
1159) -> impl fmt::Display {
1160 let tcx = cx.tcx();
1161 let header = it.fn_header(tcx).expect("Trying to get header from a non-function item");
1162 let name = it.name.as_ref().unwrap();
1163 let vis = visibility_print_with_space(it, cx).to_string();
1164 let defaultness = match fn_.body {
1165 Some(Defaultness::Implicit) | None => "",
1166 Some(Defaultness::Final) => "final ",
1167 Some(Defaultness::Default) => "default ",
1168 };
1169 let constness = match render_mode {
1172 RenderMode::Normal => print_constness_with_space(
1173 &header.constness,
1174 it.stable_since(tcx),
1175 it.const_stability(tcx),
1176 ),
1177 RenderMode::ForDeref { .. } => "",
1178 };
1179
1180 fmt::from_fn(move |w| {
1181 let indent_str = " ".repeat(indent);
1182 render_attributes_in_code(w, it, &indent_str, cx)?;
1183
1184 let asyncness = header.asyncness.print_with_space();
1185 let safety = header.safety.print_with_space();
1186 let abi = print_abi_with_space(header.abi).to_string();
1187 let href = assoc_href_attr(it, link, cx).maybe_display();
1188
1189 let generics_len = format!("{:#}", print_generics(&fn_.generics, cx)).len();
1191 let header_len = indent
1192 + "fn ".len()
1193 + vis.len()
1194 + defaultness.len()
1195 + constness.len()
1196 + asyncness.len()
1197 + safety.len()
1198 + abi.len()
1199 + name.as_str().len()
1200 + generics_len;
1201
1202 let notable_traits = notable_traits_button(&fn_.decl.output, cx).maybe_display();
1203
1204 write!(
1205 w,
1206 "{indent}{vis}{defaultness}{constness}{asyncness}{safety}{abi}fn \
1207 <a{href} class=\"fn\">{name}</a>{generics}{decl}{notable_traits}{where_clause}",
1208 indent = indent_str,
1209 generics = print_generics(&fn_.generics, cx),
1210 decl = full_print_fn_decl(&fn_.decl, header_len, indent, cx),
1211 where_clause = print_where_clause(&fn_.generics, cx, indent, ending).maybe_display(),
1212 )
1213 })
1214}
1215
1216fn render_stability_since_raw_with_extra(
1231 stable_version: Option<StableSince>,
1232 const_stability: Option<ConstStability>,
1233 extra_class: &str,
1234) -> Option<impl fmt::Display> {
1235 let mut title = String::new();
1236 let mut stability = String::new();
1237
1238 if let Some(version) = stable_version.and_then(|version| since_to_string(&version)) {
1239 stability.push_str(&version);
1240 title.push_str(&format!("Stable since Rust version {version}"));
1241 }
1242
1243 let const_title_and_stability = match const_stability {
1244 Some(ConstStability { level: StabilityLevel::Stable { since, .. }, .. }) => {
1245 since_to_string(&since)
1246 .map(|since| (format!("const since {since}"), format!("const: {since}")))
1247 }
1248 Some(ConstStability { level: StabilityLevel::Unstable { issue, .. }, feature, .. }) => {
1249 if stable_version.is_none() {
1250 None
1252 } else {
1253 let unstable = if let Some(n) = issue {
1254 format!(
1255 "<a \
1256 href=\"https://github.com/rust-lang/rust/issues/{n}\" \
1257 title=\"Tracking issue for {feature}\"\
1258 >unstable</a>"
1259 )
1260 } else {
1261 String::from("unstable")
1262 };
1263
1264 Some((String::from("const unstable"), format!("const: {unstable}")))
1265 }
1266 }
1267 _ => None,
1268 };
1269
1270 if let Some((const_title, const_stability)) = const_title_and_stability {
1271 if !title.is_empty() {
1272 title.push_str(&format!(", {const_title}"));
1273 } else {
1274 title.push_str(&const_title);
1275 }
1276
1277 if !stability.is_empty() {
1278 stability.push_str(&format!(" ({const_stability})"));
1279 } else {
1280 stability.push_str(&const_stability);
1281 }
1282 }
1283
1284 (!stability.is_empty()).then_some(fmt::from_fn(move |w| {
1285 write!(w, r#"<span class="since{extra_class}" title="{title}">{stability}</span>"#)
1286 }))
1287}
1288
1289fn since_to_string(since: &StableSince) -> Option<String> {
1290 match since {
1291 StableSince::Version(since) => Some(since.to_string()),
1292 StableSince::Current => Some(RustcVersion::CURRENT.to_string()),
1293 StableSince::Err(_) => None,
1294 }
1295}
1296
1297#[inline]
1298fn render_stability_since_raw(
1299 ver: Option<StableSince>,
1300 const_stability: Option<ConstStability>,
1301) -> Option<impl fmt::Display> {
1302 render_stability_since_raw_with_extra(ver, const_stability, "")
1303}
1304
1305fn render_assoc_item(
1306 item: &clean::Item,
1307 link: AssocItemLink<'_>,
1308 parent: ItemType,
1309 indent: usize,
1310 ending: Ending,
1311 render_mode: RenderMode,
1312 cx: &Context<'_>,
1313) -> impl fmt::Display {
1314 fmt::from_fn(move |f| match &item.kind {
1315 ItemKind::Stripped(..) => Ok(()),
1316 ItemKind::AssocFunction(fn_) => {
1317 assoc_fn(item, fn_, link, indent, ending, render_mode, cx).fmt(f)
1318 }
1319 ItemKind::AssocConstant(ct) => {
1320 assoc_const(item, ct, parent, link, indent, ending, cx).fmt(f)
1321 }
1322 ItemKind::AssocType(ty) => assoc_ty(item, ty, link, indent, ending, cx).fmt(f),
1323 _ => panic!("render_assoc_item called on non-associated-item"),
1324 })
1325}
1326
1327#[derive(Copy, Clone)]
1328enum AssocItemLink<'a> {
1329 Anchor(Option<&'a str>),
1330 GotoSource(ItemId, &'a FxIndexSet<Symbol>),
1331}
1332
1333impl<'a> AssocItemLink<'a> {
1334 fn anchor(&self, id: &'a str) -> Self {
1335 match *self {
1336 AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(id)),
1337 ref other => *other,
1338 }
1339 }
1340}
1341
1342fn write_section_heading(
1343 title: impl fmt::Display,
1344 id: &str,
1345 extra_class: Option<&str>,
1346 extra: impl fmt::Display,
1347) -> impl fmt::Display {
1348 fmt::from_fn(move |w| {
1349 let (extra_class, whitespace) = match extra_class {
1350 Some(extra) => (extra, " "),
1351 None => ("", ""),
1352 };
1353 write!(
1354 w,
1355 "<h2 id=\"{id}\" class=\"{extra_class}{whitespace}section-header\">\
1356 {title}\
1357 <a href=\"#{id}\" class=\"anchor\">§</a>\
1358 </h2>{extra}",
1359 )
1360 })
1361}
1362
1363fn write_impl_section_heading(title: impl fmt::Display, id: &str) -> impl fmt::Display {
1364 write_section_heading(title, id, None, "")
1365}
1366
1367fn render_all_impls(
1368 mut w: impl Write,
1369 cx: &Context<'_>,
1370 containing_item: &clean::Item,
1371 concrete_impls: Vec<&Impl>,
1372 auto_trait_impls: Vec<&Impl>,
1373 blanket_impls: Vec<&Impl>,
1374) -> fmt::Result {
1375 if !concrete_impls.is_empty() {
1376 let impls = render_impls(cx, concrete_impls, containing_item, true);
1377 write!(
1378 w,
1379 "{}<div id=\"trait-implementations-list\">{impls}</div>",
1380 write_impl_section_heading("Trait Implementations", "trait-implementations")
1381 )?;
1382 }
1383
1384 if !auto_trait_impls.is_empty() {
1385 let impls = render_impls(cx, auto_trait_impls, containing_item, false);
1386 write!(
1388 w,
1389 "{}<div id=\"synthetic-implementations-list\">{impls}</div>",
1390 write_impl_section_heading("Auto Trait Implementations", "synthetic-implementations",)
1391 )?;
1392 }
1393
1394 if !blanket_impls.is_empty() {
1395 let impls = render_impls(cx, blanket_impls, containing_item, false);
1396 write!(
1397 w,
1398 "{}<div id=\"blanket-implementations-list\">{impls}</div>",
1399 write_impl_section_heading("Blanket Implementations", "blanket-implementations")
1400 )?;
1401 }
1402
1403 Ok(())
1404}
1405
1406fn aliased_type_deref_impl<'a>(
1407 cx: &'a Context<'_>,
1408 alias_def_id: DefId,
1409 aliased_def_id: DefId,
1410) -> Option<(&'a Impl, bool)> {
1411 let tcx = cx.tcx();
1412 let applies = |impl_: &Impl| {
1413 impl_.impl_item.item_id.as_def_id().is_some_and(|impl_def_id| {
1414 clean::types::impl_may_apply_to_type_alias(tcx, alias_def_id, impl_def_id)
1415 })
1416 };
1417 let impls = cx.cache().impls.get(&aliased_def_id)?;
1418 let mut deref_impl = None;
1419 let mut has_deref_mut = false;
1420
1421 for impl_ in impls {
1422 if impl_.is_deref_trait(tcx) {
1423 if !impl_.is_negative_trait_impl() && applies(impl_) {
1424 deref_impl = Some(impl_);
1425 }
1426 } else if impl_.is_deref_mut_trait(tcx) && applies(impl_) {
1427 has_deref_mut = true;
1428 }
1429 }
1430 Some((deref_impl?, has_deref_mut))
1431}
1432
1433fn get_deref_impls<'a, I: Borrow<Impl>>(
1437 cx: &'a Context<'_>,
1438 trait_impls: &'a [I],
1439 item: DefId,
1440 aliased_type: Option<DefId>,
1441) -> Option<(&'a Impl, bool)> {
1442 let tcx = cx.tcx();
1443 let mut impls = trait_impls.iter().map(|t| t.borrow());
1444 if let Some(impl_) =
1445 impls.clone().find(|t| t.is_deref_trait(tcx) && !t.is_negative_trait_impl())
1446 {
1447 let has_deref_mut = impls.any(|t| t.is_deref_mut_trait(tcx));
1448 Some((impl_, has_deref_mut))
1449 } else {
1450 aliased_type.and_then(|aliased_did| aliased_type_deref_impl(cx, item, aliased_did))
1451 }
1452}
1453
1454fn render_assoc_items(
1455 cx: &Context<'_>,
1456 containing_item: &clean::Item,
1457 it: DefId,
1458 what: AssocItemRender<'_>,
1459) -> impl fmt::Display {
1460 render_assoc_items_with_aliased_type(cx, containing_item, it, what, None)
1461}
1462
1463fn render_assoc_items_with_aliased_type(
1464 cx: &Context<'_>,
1465 containing_item: &clean::Item,
1466 it: DefId,
1467 what: AssocItemRender<'_>,
1468 aliased_type: Option<DefId>,
1469) -> impl fmt::Display {
1470 fmt::from_fn(move |f| {
1471 let mut derefs = DefIdSet::default();
1472 derefs.insert(it);
1473 if let Some(aliased_type) = aliased_type {
1474 derefs.insert(aliased_type);
1475 }
1476 render_assoc_items_inner(f, cx, containing_item, it, what, &mut derefs, aliased_type)
1477 })
1478}
1479
1480fn render_assoc_items_inner(
1481 mut w: &mut dyn fmt::Write,
1482 cx: &Context<'_>,
1483 containing_item: &clean::Item,
1484 it: DefId,
1485 what: AssocItemRender<'_>,
1486 derefs: &mut DefIdSet,
1487 aliased_type: Option<DefId>,
1488) -> fmt::Result {
1489 info!("Documenting associated items of {:?}", containing_item.name);
1490 let cache = &cx.shared.cache;
1491 let impls = match cache.impls.get(&it) {
1492 Some(impls) => impls.as_slice(),
1493 None if aliased_type.is_some() => &[],
1494 None => return Ok(()),
1495 };
1496 let (mut inherent_impls, trait_impls): (Vec<_>, _) =
1497 impls.iter().partition(|i| i.inner_impl().trait_.is_none());
1498 if !inherent_impls.is_empty() {
1499 let render_mode = what.render_mode(cx.tcx());
1500 let class_html = what
1501 .class()
1502 .map(|class| fmt::from_fn(move |f| write!(f, r#" class="{class}""#)))
1503 .maybe_display();
1504 let (section_heading, id) = match what {
1505 AssocItemRender::All => (
1506 Either::Left(write_impl_section_heading("Implementations", "implementations")),
1507 Cow::Borrowed("implementations-list"),
1508 ),
1509 AssocItemRender::DerefFor { trait_, type_, resolved_type, .. } => {
1510 let id = cx.derive_id(small_url_encode(format!(
1511 "deref-methods-{:#}",
1512 print_type(type_, cx)
1513 )));
1514 inherent_impls
1522 .retain(|impl_| resolved_type.is_doc_subtype_of(&impl_.inner_impl().for_, &cx));
1523 let derived_id = cx.derive_id(&id);
1524 if let Some(def_id) = type_.def_id(cx.cache()) {
1525 cx.deref_id_map.borrow_mut().insert(def_id, id.clone());
1526 }
1527 (
1528 Either::Right(fmt::from_fn(move |f| {
1529 write!(
1530 f,
1531 "<details class=\"toggle big-toggle\" open><summary>{}</summary>",
1532 write_impl_section_heading(
1533 fmt::from_fn(|f| write!(
1534 f,
1535 "<span>Methods from {trait_}<Target = {type_}></span>",
1536 trait_ = print_path(trait_, cx),
1537 type_ = print_type(type_, cx),
1538 )),
1539 &id,
1540 )
1541 )
1542 })),
1543 Cow::Owned(derived_id),
1544 )
1545 }
1546 };
1547 let inherent_impls_buf = fmt::from_fn(|f| {
1548 inherent_impls
1549 .iter()
1550 .map(|i| {
1551 render_impl(
1552 cx,
1553 i,
1554 containing_item,
1555 AssocItemLink::Anchor(None),
1556 render_mode,
1557 None,
1558 &[],
1559 ImplRenderingParameters {
1560 show_def_docs: true,
1561 show_default_items: true,
1562 show_non_assoc_items: true,
1563 toggle_open_by_default: true,
1564 },
1565 )
1566 })
1567 .joined("", f)
1568 })
1569 .to_string();
1570
1571 if !inherent_impls_buf.is_empty() {
1572 write!(
1573 w,
1574 "{section_heading}<div id=\"{id}\"{class_html}>{inherent_impls_buf}</div>{}",
1575 matches!(what, AssocItemRender::DerefFor { .. })
1576 .then_some("</details>")
1577 .maybe_display(),
1578 )?;
1579 }
1580 }
1581
1582 if let Some((impl_, has_deref_mut)) = get_deref_impls(cx, &trait_impls, it, aliased_type) {
1583 render_deref_methods(&mut w, cx, impl_, containing_item, has_deref_mut, derefs)?;
1584 }
1585
1586 if !trait_impls.is_empty() {
1587 if let AssocItemRender::DerefFor { .. } = what {
1590 return Ok(());
1591 }
1592
1593 let (auto_trait_impls, trait_impls): (Vec<&Impl>, Vec<&Impl>) =
1594 trait_impls.into_iter().partition(|t| t.inner_impl().kind.is_auto());
1595 let (blanket_impls, concrete_impls): (Vec<&Impl>, _) =
1596 trait_impls.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
1597
1598 render_all_impls(w, cx, containing_item, concrete_impls, auto_trait_impls, blanket_impls)?;
1599 }
1600 Ok(())
1601}
1602
1603fn render_deref_methods(
1605 mut w: impl Write,
1606 cx: &Context<'_>,
1607 impl_: &Impl,
1608 container_item: &clean::Item,
1609 deref_mut: bool,
1610 derefs: &mut DefIdSet,
1611) -> fmt::Result {
1612 let cache = cx.cache();
1613 let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
1614 let (target, real_target) = impl_
1615 .inner_impl()
1616 .items
1617 .iter()
1618 .find_map(|item| match &item.kind {
1619 ItemKind::AssocType(clean::AssocType { type_: Some(type_), .. }) => {
1620 Some((type_.middle_type.as_ref().unwrap_or(&type_.type_), &type_.type_))
1621 }
1622 _ => None,
1623 })
1624 .expect("Expected associated type binding");
1625 debug!(
1626 "Render deref methods for {for_:#?}, target {target:#?}",
1627 for_ = impl_.inner_impl().for_
1628 );
1629 let what = AssocItemRender::DerefFor {
1630 trait_: deref_type,
1631 type_: real_target,
1632 resolved_type: target,
1633 deref_mut_: deref_mut,
1634 deref_impl_def_id: impl_.def_id(),
1635 };
1636 if let Some(did) = target.def_id(cache) {
1637 if let Some(type_did) = impl_.inner_impl().for_.def_id(cache) {
1638 if did == type_did || !derefs.insert(did) {
1640 return Ok(());
1642 }
1643 }
1644 render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs, None)?;
1645 } else if let Some(prim) = target.primitive_type()
1646 && let Some(&did) = cache.primitive_locations.get(&prim)
1647 {
1648 render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs, None)?;
1649 }
1650 Ok(())
1651}
1652
1653fn should_render_item_for_deref(
1654 item: &clean::Item,
1655 deref_mut_: bool,
1656 tcx: TyCtxt<'_>,
1657 target_is_copy: bool,
1658) -> bool {
1659 let ItemKind::AssocFunction(fn_) = &item.kind else { return false };
1660 let Some(self_ty) = fn_.decl.receiver_type() else { return false };
1661
1662 let (by_mut_ref, by_box, by_value) = match *self_ty {
1663 clean::Type::BorrowedRef { mutability, .. } => {
1664 (mutability == Mutability::Mut, false, false)
1665 }
1666 clean::Type::Path { ref path } => {
1667 (false, Some(path.def_id()) == tcx.lang_items().owned_box(), false)
1668 }
1669 clean::Type::SelfTy => (false, false, true),
1670 _ => (false, false, false),
1671 };
1672
1673 (deref_mut_ || !by_mut_ref) && !by_box && (!by_value || target_is_copy)
1674}
1675
1676fn is_notable_trait_passthrough(did: DefId, cx: &Context<'_>) -> bool {
1681 let lang_items = cx.tcx().lang_items();
1682 Some(did) == lang_items.owned_box() || Some(did) == lang_items.pin_type()
1683}
1684
1685fn notable_traits_button(ty: &clean::Type, cx: &Context<'_>) -> Option<impl fmt::Display> {
1686 if ty.is_unit() {
1687 return None;
1689 }
1690
1691 let did = ty.def_id(cx.cache())?;
1692
1693 if is_notable_trait_passthrough(did, cx) {
1694 return None;
1695 }
1696
1697 let impls = cx.cache().impls.get(&did)?;
1698 let has_notable_trait = impls
1699 .iter()
1700 .map(Impl::inner_impl)
1701 .filter(|impl_| {
1702 impl_.polarity == ty::ImplPolarity::Positive
1703 && ty.is_doc_subtype_of(&impl_.for_, cx)
1706 })
1707 .filter_map(|impl_| impl_.trait_.as_ref())
1708 .filter_map(|trait_| cx.cache().traits.get(&trait_.def_id()))
1709 .any(|t| t.is_notable_trait(cx.tcx()));
1710
1711 has_notable_trait.then(|| {
1712 cx.types_with_notable_traits.borrow_mut().insert(ty.clone());
1713 fmt::from_fn(|f| {
1714 write!(
1715 f,
1716 " <span tabindex=0 class=\"tooltip\" data-notable-ty=\"{ty}\">ⓘ</span>",
1717 ty = Escape(&format!("{:#}", print_type(ty, cx))),
1718 )
1719 })
1720 })
1721}
1722
1723fn notable_traits_decl_write_html<'cx>(
1724 notable_impls: impl Iterator<Item = (&'cx clean::Impl, DefId)>,
1725 f: &mut fmt::Formatter<'_>,
1726 cx: &Context<'_>,
1727) -> Result<(), fmt::Error> {
1728 let mut notable_impls = notable_impls.peekable();
1729 let code_tags_closing = if let Some((impl_, _)) = notable_impls.peek() {
1730 write!(
1731 f,
1732 "<h3>Notable traits for <code>{}</code></h3>\
1733 <pre><code>",
1734 print_type(&impl_.for_, cx),
1735 )?;
1736 "</code></pre>"
1737 } else {
1738 ""
1739 };
1740
1741 for (impl_, trait_did) in notable_impls {
1742 write!(f, "<div class=\"where\">{}</div>", print_impl(impl_, false, cx))?;
1743 for it in &impl_.items {
1744 let ItemKind::AssocType(ty @ clean::AssocType { type_: Some(_), .. }) = &it.kind else {
1745 continue;
1746 };
1747
1748 let empty_set = FxIndexSet::default();
1749 let src_link = AssocItemLink::GotoSource(trait_did.into(), &empty_set);
1750
1751 write!(
1752 f,
1753 "<div class=\"where\"> {};</div>",
1754 assoc_ty(it, ty, src_link, 0, Ending::Newline, cx)
1755 )?;
1756 }
1757 }
1758
1759 f.write_str(code_tags_closing)
1760}
1761
1762fn notable_traits_decl_for_type(ty: &clean::Type, cx: &Context<'_>) -> (String, String) {
1763 let did = ty.def_id(cx.cache()).expect("notable_traits_button already checked this");
1764
1765 let impls = cx.cache().impls.get(&did).expect("notable_traits_button already checked this");
1766
1767 let out = fmt::from_fn(|f| {
1768 let notable_impls = impls
1769 .iter()
1770 .map(|impl_| impl_.inner_impl())
1771 .filter(|impl_| impl_.polarity == ty::ImplPolarity::Positive)
1772 .filter(|impl_| {
1773 ty.is_doc_subtype_of(&impl_.for_, cx)
1775 })
1776 .filter_map(|impl_| {
1777 if let Some(trait_) = &impl_.trait_
1778 && let trait_did = trait_.def_id()
1779 && let Some(trait_) = cx.cache().traits.get(&trait_did)
1780 && trait_.is_notable_trait(cx.tcx())
1781 {
1782 Some((impl_, trait_did))
1783 } else {
1784 None
1785 }
1786 });
1787
1788 notable_traits_decl_write_html(notable_impls, f, cx)
1789 })
1790 .to_string();
1791
1792 (format!("{:#}", print_type(ty, cx)), out)
1793}
1794
1795fn notable_traits_decl_for_item(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
1796 let out = fmt::from_fn(|f| {
1797 let notable_impls = if let Some(def_id) = item.def_id()
1798 && !is_notable_trait_passthrough(def_id, cx)
1799 && let Some(impls) = cx.cache().impls.get(&def_id)
1800 {
1801 impls
1802 .iter()
1803 .map(Impl::inner_impl)
1804 .filter(|impl_| impl_.polarity == ty::ImplPolarity::Positive)
1805 .filter_map(|impl_| {
1806 if let Some(trait_) = &impl_.trait_
1807 && let trait_did = trait_.def_id()
1808 && let Some(trait_) = cx.cache().traits.get(&trait_did)
1809 && trait_.is_notable_trait(cx.tcx())
1810 {
1811 Some((impl_, trait_did))
1812 } else {
1813 None
1814 }
1815 })
1816 } else {
1817 return Ok(());
1818 };
1819 notable_traits_decl_write_html(notable_impls, f, cx)
1820 })
1821 .to_string();
1822
1823 Some((item.name?.to_string(), out))
1824}
1825
1826fn notable_traits_json<'a>(
1827 tys: impl Iterator<Item = &'a clean::Type>,
1828 item: &clean::Item,
1829 cx: &Context<'_>,
1830) -> String {
1831 let mut mp = tys.map(|ty| notable_traits_decl_for_type(ty, cx)).collect::<IndexMap<_, _>>();
1832 if let Some((item_name, item_decl)) = notable_traits_decl_for_item(item, cx)
1833 && !item_decl.is_empty()
1834 {
1835 mp.insert(item_name, item_decl);
1836 }
1837 mp.sort_unstable_keys();
1838 serde_json::to_string(&mp).expect("serialize (string, string) -> json object cannot fail")
1839}
1840
1841pub(crate) struct NotableTraitBadge {
1842 pub name: String,
1843 pub full_path: String,
1844 pub href: Option<String>,
1846 pub color: NotableTraitColor,
1848}
1849
1850pub(crate) fn notable_trait_badges(item: &clean::Item, cx: &Context<'_>) -> Vec<NotableTraitBadge> {
1853 let tcx = cx.tcx();
1854 if let Some(def_id) = item.def_id()
1855 && !is_notable_trait_passthrough(def_id, cx)
1856 && let Some(impls) = cx.cache().impls.get(&def_id)
1857 {
1858 impls
1859 .iter()
1860 .map(Impl::inner_impl)
1861 .filter(|impl_| impl_.polarity == ty::ImplPolarity::Positive)
1862 .filter_map(|impl_| {
1863 if let Some(trait_) = &impl_.trait_
1864 && let trait_did = trait_.def_id()
1865 && cx.cache().traits.contains_key(&trait_did)
1866 && let Some(&color) = tcx.doc_notable_trait(trait_did)
1867 {
1868 let name = tcx.item_name(trait_did).to_string();
1869 let (full_path, href) = match href(trait_did, cx) {
1870 Ok(info) => (join_path_syms(&info.rust_path), Some(info.url)),
1871 Err(_) => (tcx.def_path_str(trait_did), None),
1872 };
1873 Some((name.clone(), NotableTraitBadge { name, full_path, href, color }))
1874 } else {
1875 None
1876 }
1877 })
1878 .collect::<BTreeMap<String, NotableTraitBadge>>()
1879 .into_values()
1880 .collect()
1881 } else {
1882 Vec::new()
1883 }
1884}
1885
1886#[derive(Clone, Copy, Debug)]
1887struct ImplRenderingParameters {
1888 show_def_docs: bool,
1889 show_default_items: bool,
1890 show_non_assoc_items: bool,
1892 toggle_open_by_default: bool,
1893}
1894
1895fn render_impl(
1896 cx: &Context<'_>,
1897 i: &Impl,
1898 parent: &clean::Item,
1899 link: AssocItemLink<'_>,
1900 render_mode: RenderMode,
1901 use_absolute: Option<bool>,
1902 aliases: &[String],
1903 rendering_params: ImplRenderingParameters,
1904) -> impl fmt::Display {
1905 fmt::from_fn(move |w| {
1906 let cache = &cx.shared.cache;
1907 let traits = &cache.traits;
1908 let trait_ = i.trait_did().map(|did| &traits[&did]);
1909 let mut close_tags = <Vec<&str>>::with_capacity(2);
1910
1911 fn doc_impl_item(
1917 boring: impl fmt::Write,
1918 interesting: impl fmt::Write,
1919 cx: &Context<'_>,
1920 item: &clean::Item,
1921 parent: &clean::Item,
1922 link: AssocItemLink<'_>,
1923 render_mode: RenderMode,
1924 is_default_item: bool,
1925 trait_: Option<&clean::Trait>,
1926 rendering_params: ImplRenderingParameters,
1927 ) -> fmt::Result {
1928 let item_type = item.type_();
1929 let name = item.name.as_ref().unwrap();
1930
1931 let render_assoc_fn = rendering_params.show_non_assoc_items
1932 && match render_mode {
1933 RenderMode::Normal => true,
1934 RenderMode::ForDeref { mut_: deref_mut_, is_deref_target_copy } => {
1935 should_render_item_for_deref(
1936 item,
1937 deref_mut_,
1938 cx.tcx(),
1939 is_deref_target_copy,
1940 )
1941 }
1942 };
1943
1944 let in_trait_class = if trait_.is_some() { " trait-impl" } else { "" };
1945
1946 let mut doc_buffer = String::new();
1947 let mut info_buffer = String::new();
1948 let mut short_documented = true;
1949
1950 let mut trait_item_deprecated = false;
1951 if render_assoc_fn {
1952 if !is_default_item {
1953 if let Some(t) = trait_ {
1954 if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
1957 trait_item_deprecated = it.is_deprecated(cx.tcx());
1958 if !item.doc_value().is_empty() {
1961 document_item_info(cx, it, Some(parent))
1962 .render_into(&mut info_buffer)?;
1963 doc_buffer = document_full(item, cx, HeadingOffset::H5).to_string();
1964 short_documented = false;
1965 } else {
1966 doc_buffer = document_short(
1969 it,
1970 cx,
1971 link,
1972 parent,
1973 rendering_params.show_def_docs,
1974 )
1975 .to_string();
1976 }
1977 }
1978 } else {
1979 document_item_info(cx, item, Some(parent)).render_into(&mut info_buffer)?;
1980 if rendering_params.show_def_docs {
1981 doc_buffer = document_full(item, cx, HeadingOffset::H5).to_string();
1982 short_documented = false;
1983 }
1984 }
1985 } else {
1986 doc_buffer =
1987 document_short(item, cx, link, parent, rendering_params.show_def_docs)
1988 .to_string();
1989 }
1990 }
1991 let mut w = if short_documented && trait_.is_some() {
1992 Either::Left(interesting)
1993 } else {
1994 Either::Right(boring)
1995 };
1996
1997 let mut deprecation_class = if trait_item_deprecated || item.is_deprecated(cx.tcx()) {
1998 " deprecated"
1999 } else {
2000 ""
2001 };
2002
2003 let toggled = !doc_buffer.is_empty();
2004 if toggled {
2005 let method_toggle_class =
2006 if item_type.is_assoc_fn() { " method-toggle" } else { "" };
2007 write!(
2008 w,
2009 "<details class=\"toggle{method_toggle_class}{deprecation_class}\" open><summary>"
2010 )?;
2011 deprecation_class = "";
2012 }
2013 match &item.kind {
2014 ItemKind::AssocFunction(_) if !render_assoc_fn => {}
2015 ItemKind::AssocConstant(_) | ItemKind::AssocType(_)
2016 if let RenderMode::ForDeref { .. } = render_mode => {}
2017
2018 ItemKind::AssocFunction(_) => {
2019 let id = cx.derive_id(format!("{item_type}.{name}"));
2020 let source_id = trait_
2021 .and_then(|trait_| {
2022 trait_
2023 .items
2024 .iter()
2025 .find(|item| item.name.map(|n| n == *name).unwrap_or(false))
2026 })
2027 .map(|item| format!("{}.{name}", item.type_()));
2028 write!(
2029 w,
2030 "<section id=\"{id}\" class=\"{item_type}{in_trait_class}{deprecation_class}\">\
2031 {}",
2032 render_rightside(cx, item, render_mode)
2033 )?;
2034 if trait_.is_some() {
2035 write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>")?;
2037 }
2038 write!(
2039 w,
2040 "<h4 class=\"code-header\">{}</h4></section>",
2041 render_assoc_item(
2042 item,
2043 link.anchor(source_id.as_ref().unwrap_or(&id)),
2044 ItemType::Impl,
2045 0,
2046 Ending::Newline,
2047 render_mode,
2048 cx,
2049 ),
2050 )?;
2051 }
2052 ItemKind::AssocConstant(ct) => {
2053 let source_id = format!("{item_type}.{name}");
2054 let id = cx.derive_id(&source_id);
2055 write!(
2056 w,
2057 "<section id=\"{id}\" class=\"{item_type}{in_trait_class}{deprecation_class}\">\
2058 {}",
2059 render_rightside(cx, item, render_mode),
2060 )?;
2061 if trait_.is_some() {
2062 write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>")?;
2064 }
2065 write!(
2066 w,
2067 "<h4 class=\"code-header\">{}</h4></section>",
2068 assoc_const(
2069 item,
2070 ct,
2071 ItemType::Impl,
2072 link.anchor(if trait_.is_some() { &source_id } else { &id }),
2073 0,
2074 Ending::Newline,
2075 cx,
2076 ),
2077 )?;
2078 }
2079 ItemKind::AssocType(ty) => {
2080 let source_id = format!("{item_type}.{name}");
2081 let id = cx.derive_id(&source_id);
2082 write!(
2083 w,
2084 "<section id=\"{id}\" class=\"{item_type}{in_trait_class}{deprecation_class}\">\
2085 {}",
2086 render_rightside(cx, item, render_mode),
2087 )?;
2088 if trait_.is_some() {
2089 write!(w, "<a href=\"#{id}\" class=\"anchor\">§</a>")?;
2091 }
2092 write!(
2093 w,
2094 "<h4 class=\"code-header\">{}</h4></section>",
2095 assoc_ty(
2096 item,
2097 ty,
2098 link.anchor(if trait_.is_some() { &source_id } else { &id }),
2099 0,
2100 Ending::Newline,
2101 cx,
2102 ),
2103 )?;
2104 }
2105 ItemKind::Stripped(..) => return Ok(()),
2106 _ => panic!("can't make docs for trait item with name {:?}", item.name),
2107 }
2108
2109 w.write_str(&info_buffer)?;
2110 if toggled {
2111 write!(w, "</summary>{doc_buffer}</details>")?;
2112 }
2113 Ok(())
2114 }
2115
2116 let mut impl_items = String::new();
2117 let mut default_impl_items = String::new();
2118 let impl_ = i.inner_impl();
2119
2120 let mut assoc_tys = Vec::new();
2130 let mut assoc_fns = Vec::new();
2131
2132 if !impl_.is_negative_trait_impl() {
2133 for impl_item in &impl_.items {
2134 match impl_item.kind {
2135 ItemKind::AssocFunction(..) => assoc_fns.push(impl_item),
2136 ItemKind::AssocType(..) => assoc_tys.push(impl_item),
2137 ItemKind::AssocConstant(_) => {
2138 doc_impl_item(
2140 &mut default_impl_items,
2141 &mut impl_items,
2142 cx,
2143 impl_item,
2144 if trait_.is_some() { &i.impl_item } else { parent },
2145 link,
2146 render_mode,
2147 false,
2148 trait_,
2149 rendering_params,
2150 )?;
2151 }
2152 _ => {}
2153 }
2154 }
2155
2156 for assoc_ty in assoc_tys {
2157 doc_impl_item(
2158 &mut default_impl_items,
2159 &mut impl_items,
2160 cx,
2161 assoc_ty,
2162 if trait_.is_some() { &i.impl_item } else { parent },
2163 link,
2164 render_mode,
2165 false,
2166 trait_,
2167 rendering_params,
2168 )?;
2169 }
2170 for assoc_fn in assoc_fns {
2171 doc_impl_item(
2172 &mut default_impl_items,
2173 &mut impl_items,
2174 cx,
2175 assoc_fn,
2176 if trait_.is_some() { &i.impl_item } else { parent },
2177 link,
2178 render_mode,
2179 false,
2180 trait_,
2181 rendering_params,
2182 )?;
2183 }
2184 }
2185
2186 fn render_default_items(
2187 mut boring: impl fmt::Write,
2188 mut interesting: impl fmt::Write,
2189 cx: &Context<'_>,
2190 t: &clean::Trait,
2191 i: &clean::Impl,
2192 parent: &clean::Item,
2193 render_mode: RenderMode,
2194 rendering_params: ImplRenderingParameters,
2195 ) -> fmt::Result {
2196 for trait_item in &t.items {
2197 if let Some(impl_def_id) = parent.item_id.as_def_id()
2200 && let Some(trait_item_def_id) = trait_item.item_id.as_def_id()
2201 && cx.tcx().is_impossible_associated_item((impl_def_id, trait_item_def_id))
2202 {
2203 continue;
2204 }
2205
2206 let n = trait_item.name;
2207 if i.items.iter().any(|m| m.name == n) {
2208 continue;
2209 }
2210 let did = i.trait_.as_ref().unwrap().def_id();
2211 let provided_methods = i.provided_trait_methods(cx.tcx());
2212 let assoc_link = AssocItemLink::GotoSource(did.into(), &provided_methods);
2213
2214 doc_impl_item(
2215 &mut boring,
2216 &mut interesting,
2217 cx,
2218 trait_item,
2219 parent,
2220 assoc_link,
2221 render_mode,
2222 true,
2223 Some(t),
2224 rendering_params,
2225 )?;
2226 }
2227 Ok(())
2228 }
2229
2230 if rendering_params.show_default_items
2235 && let Some(t) = trait_
2236 && !impl_.is_negative_trait_impl()
2237 {
2238 render_default_items(
2239 &mut default_impl_items,
2240 &mut impl_items,
2241 cx,
2242 t,
2243 impl_,
2244 &i.impl_item,
2245 render_mode,
2246 rendering_params,
2247 )?;
2248 }
2249 if render_mode == RenderMode::Normal {
2250 let deprecation_attr = if impl_.is_deprecated
2251 || trait_.is_some_and(|trait_| trait_.is_deprecated(cx.tcx()))
2252 {
2253 " deprecated"
2254 } else {
2255 ""
2256 };
2257
2258 let (before_dox, after_dox) = i
2259 .impl_item
2260 .opt_doc_value()
2261 .map(|dox| {
2262 Markdown {
2263 content: &dox,
2264 links: &i.impl_item.links(cx),
2265 ids: &mut cx.id_map.borrow_mut(),
2266 error_codes: cx.shared.codes,
2267 edition: cx.shared.edition(),
2268 playground: &cx.shared.playground,
2269 heading_offset: HeadingOffset::H4,
2270 }
2271 .split_summary_and_content()
2272 })
2273 .unwrap_or((None, None));
2274
2275 let toggled =
2276 !(impl_items.is_empty() && default_impl_items.is_empty() && after_dox.is_none());
2277 if toggled {
2278 close_tags.push("</details>");
2279 write!(
2280 w,
2281 "<details class=\"toggle implementors-toggle{deprecation_attr}\"{}>\
2282 <summary>",
2283 if rendering_params.toggle_open_by_default { " open" } else { "" }
2284 )?;
2285 }
2286
2287 write!(
2288 w,
2289 "{}",
2290 render_impl_summary(
2291 cx,
2292 i,
2293 parent,
2294 rendering_params.show_def_docs,
2295 use_absolute,
2296 aliases,
2297 before_dox.as_deref(),
2298 trait_.is_none() && impl_.items.is_empty(),
2299 )
2300 )?;
2301 if toggled {
2302 w.write_str("</summary>")?;
2303 }
2304
2305 if before_dox.is_some()
2306 && let Some(after_dox) = after_dox
2307 {
2308 write!(w, "<div class=\"docblock\">{after_dox}</div>")?;
2309 }
2310
2311 if !default_impl_items.is_empty() || !impl_items.is_empty() {
2312 w.write_str("<div class=\"impl-items\">")?;
2313 close_tags.push("</div>");
2314 }
2315 }
2316 if !default_impl_items.is_empty() || !impl_items.is_empty() {
2317 w.write_str(&default_impl_items)?;
2318 w.write_str(&impl_items)?;
2319 }
2320 for tag in close_tags.into_iter().rev() {
2321 w.write_str(tag)?;
2322 }
2323 Ok(())
2324 })
2325}
2326
2327fn render_rightside(
2330 cx: &Context<'_>,
2331 item: &clean::Item,
2332 render_mode: RenderMode,
2333) -> impl fmt::Display {
2334 let tcx = cx.tcx();
2335
2336 fmt::from_fn(move |w| {
2337 let const_stability = match render_mode {
2340 RenderMode::Normal => item.const_stability(tcx),
2341 RenderMode::ForDeref { .. } => None,
2342 };
2343 let src_href = cx.src_href(item);
2344 let stability = render_stability_since_raw_with_extra(
2345 item.stable_since(tcx),
2346 const_stability,
2347 if src_href.is_some() { "" } else { " rightside" },
2348 );
2349
2350 match (stability, src_href) {
2351 (Some(stability), Some(link)) => {
2352 write!(
2353 w,
2354 "<span class=\"rightside\">{stability} · <a class=\"src\" href=\"{link}\">Source</a></span>",
2355 )
2356 }
2357 (Some(stability), None) => {
2358 write!(w, "{stability}")
2359 }
2360 (None, Some(link)) => {
2361 write!(w, "<a class=\"src rightside\" href=\"{link}\">Source</a>")
2362 }
2363 (None, None) => Ok(()),
2364 }
2365 })
2366}
2367
2368fn render_impl_summary(
2369 cx: &Context<'_>,
2370 i: &Impl,
2371 parent: &clean::Item,
2372 show_def_docs: bool,
2373 use_absolute: Option<bool>,
2374 aliases: &[String],
2377 doc: Option<&str>,
2378 impl_is_empty: bool,
2379) -> impl fmt::Display {
2380 fmt::from_fn(move |w| {
2381 let inner_impl = i.inner_impl();
2382 let id = cx.derive_id(get_id_for_impl(cx.tcx(), i.impl_item.item_id));
2383 let aliases = (!aliases.is_empty())
2384 .then_some(fmt::from_fn(|f| {
2385 write!(f, " data-aliases=\"{}\"", fmt::from_fn(|f| aliases.iter().joined(",", f)))
2386 }))
2387 .maybe_display();
2388 write!(
2389 w,
2390 "<section id=\"{id}\" class=\"impl\"{aliases}>\
2391 {}\
2392 <a href=\"#{id}\" class=\"anchor\">§</a>\
2393 <h3 class=\"code-header\">",
2394 render_rightside(cx, &i.impl_item, RenderMode::Normal)
2395 )?;
2396
2397 if let Some(use_absolute) = use_absolute {
2398 write!(w, "{}", print_impl(inner_impl, use_absolute, cx))?;
2399 if show_def_docs {
2400 for it in &inner_impl.items {
2401 if let ItemKind::AssocType(ty) = &it.kind {
2402 write!(
2403 w,
2404 "<div class=\"where\"> {};</div>",
2405 assoc_ty(it, ty, AssocItemLink::Anchor(None), 0, Ending::Newline, cx,)
2406 )?;
2407 }
2408 }
2409 }
2410 } else {
2411 write!(w, "{}", print_impl(inner_impl, false, cx))?;
2412 }
2413 w.write_str("</h3>")?;
2414
2415 let is_trait = inner_impl.trait_.is_some();
2416 if is_trait && let Some(portability) = portability(&i.impl_item, Some(parent)) {
2417 write!(
2418 w,
2419 "<span class=\"item-info\">\
2420 <div class=\"stab portability\">{portability}</div>\
2421 </span>",
2422 )?;
2423 }
2424
2425 if let Some(doc) = doc {
2426 if impl_is_empty {
2427 w.write_str(
2428 "\
2429<div class=\"item-info\">\
2430 <div class=\"stab empty-impl\">This impl block contains no public items.</div>\
2431</div>",
2432 )?;
2433 }
2434 write!(w, "<div class=\"docblock\">{doc}</div>")?;
2435 }
2436
2437 w.write_str("</section>")
2438 })
2439}
2440
2441pub(crate) fn small_url_encode(s: String) -> String {
2442 fn dont_escape(c: u8) -> bool {
2447 c.is_ascii_alphanumeric()
2448 || c == b'-'
2449 || c == b'_'
2450 || c == b'.'
2451 || c == b','
2452 || c == b'~'
2453 || c == b'!'
2454 || c == b'\''
2455 || c == b'('
2456 || c == b')'
2457 || c == b'*'
2458 || c == b'/'
2459 || c == b';'
2460 || c == b':'
2461 || c == b'?'
2462 || c == b'='
2466 }
2467 let mut st = String::new();
2468 let mut last_match = 0;
2469 for (idx, b) in s.bytes().enumerate() {
2470 if dont_escape(b) {
2471 continue;
2472 }
2473
2474 if last_match != idx {
2475 st += &s[last_match..idx];
2477 }
2478 if b == b' ' {
2479 st += "+";
2483 } else {
2484 write!(st, "%{b:02X}").unwrap();
2485 }
2486 last_match = idx + 1;
2492 }
2493
2494 if last_match != 0 {
2495 st += &s[last_match..];
2496 st
2497 } else {
2498 s
2499 }
2500}
2501
2502fn get_id_for_impl(tcx: TyCtxt<'_>, impl_id: ItemId) -> String {
2503 use rustc_middle::ty::print::with_forced_trimmed_paths;
2504 let (type_, trait_) = match impl_id {
2505 ItemId::Auto { trait_, for_ } => {
2506 let ty = tcx.type_of(for_).skip_binder();
2507 (ty, Some(ty::TraitRef::new(tcx, trait_, [ty])))
2508 }
2509 ItemId::Blanket { impl_id, .. } | ItemId::DefId(impl_id) => {
2510 if let Some(trait_ref) = tcx.impl_opt_trait_ref(impl_id) {
2511 let trait_ref = trait_ref.skip_binder();
2512 (trait_ref.self_ty(), Some(trait_ref))
2513 } else {
2514 (tcx.type_of(impl_id).skip_binder(), None)
2515 }
2516 }
2517 };
2518 with_forced_trimmed_paths!(small_url_encode(if let Some(trait_) = trait_ {
2519 format!("impl-{trait_}-for-{type_}", trait_ = trait_.print_only_trait_path())
2520 } else {
2521 format!("impl-{type_}")
2522 }))
2523}
2524
2525fn extract_for_impl_name(item: &clean::Item, cx: &Context<'_>) -> Option<(String, String)> {
2526 match item.kind {
2527 clean::ItemKind::Impl(ref i) if i.trait_.is_some() => {
2528 Some((
2531 format!("{:#}", print_type(&i.for_, cx)),
2532 get_id_for_impl(cx.tcx(), item.item_id),
2533 ))
2534 }
2535 _ => None,
2536 }
2537}
2538
2539pub(crate) fn get_filtered_impls_for_reference<'a>(
2543 shared: &'a SharedContext<'_>,
2544 it: &clean::Item,
2545) -> (Vec<&'a Impl>, Vec<&'a Impl>, Vec<&'a Impl>) {
2546 let def_id = it.item_id.expect_def_id();
2547 let Some(v) = shared.cache.impls.get(&def_id) else {
2549 return (Vec::new(), Vec::new(), Vec::new());
2550 };
2551 let traits = v.iter().filter(|i| i.inner_impl().trait_.is_some());
2554 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
2555 traits.partition(|t| t.inner_impl().kind.is_auto());
2556
2557 let (blanket_impl, concrete): (Vec<&Impl>, _) =
2558 concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
2559 let concrete: Vec<_> = concrete
2561 .into_iter()
2562 .filter(|t| match t.inner_impl().for_ {
2563 clean::Type::BorrowedRef { ref type_, .. } => type_.is_full_generic(),
2564 _ => false,
2565 })
2566 .collect();
2567
2568 (concrete, synthetic, blanket_impl)
2569}
2570
2571#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2572pub(crate) enum ItemSection {
2573 Reexports,
2574 PrimitiveTypes,
2575 Modules,
2576 Macros,
2577 Structs,
2578 Enums,
2579 Constants,
2580 Statics,
2581 Traits,
2582 Functions,
2583 TypeAliases,
2584 Unions,
2585 Implementations,
2586 AssocFnsWithoutBody,
2587 AssocFnsWithBody,
2588 StructFields,
2589 Variants,
2590 AssociatedTypes,
2591 AssociatedConstants,
2592 ForeignTypes,
2593 Keywords,
2594 Attributes,
2595 AttributeMacros,
2596 DeriveMacros,
2597 TraitAliases,
2598}
2599
2600impl ItemSection {
2601 const ALL: &'static [Self] = {
2602 use ItemSection::*;
2603 &[
2606 Reexports,
2607 PrimitiveTypes,
2608 Modules,
2609 Macros,
2610 Structs,
2611 Enums,
2612 Constants,
2613 Statics,
2614 Traits,
2615 Functions,
2616 TypeAliases,
2617 Unions,
2618 Implementations,
2619 AssocFnsWithoutBody,
2620 AssocFnsWithBody,
2621 StructFields,
2622 Variants,
2623 AssociatedTypes,
2624 AssociatedConstants,
2625 ForeignTypes,
2626 Keywords,
2627 Attributes,
2628 AttributeMacros,
2629 DeriveMacros,
2630 TraitAliases,
2631 ]
2632 };
2633
2634 fn id(self) -> &'static str {
2635 match self {
2636 Self::Reexports => "reexports",
2637 Self::Modules => "modules",
2638 Self::Structs => "structs",
2639 Self::Unions => "unions",
2640 Self::Enums => "enums",
2641 Self::Functions => "functions",
2642 Self::TypeAliases => "types",
2643 Self::Statics => "statics",
2644 Self::Constants => "constants",
2645 Self::Traits => "traits",
2646 Self::Implementations => "impls",
2647 Self::AssocFnsWithoutBody => "tymethods",
2648 Self::AssocFnsWithBody => "methods",
2649 Self::StructFields => "fields",
2650 Self::Variants => "variants",
2651 Self::Macros => "macros",
2652 Self::PrimitiveTypes => "primitives",
2653 Self::AssociatedTypes => "associated-types",
2654 Self::AssociatedConstants => "associated-consts",
2655 Self::ForeignTypes => "foreign-types",
2656 Self::Keywords => "keywords",
2657 Self::Attributes => "attribute-docs",
2658 Self::AttributeMacros => "attributes",
2659 Self::DeriveMacros => "derives",
2660 Self::TraitAliases => "trait-aliases",
2661 }
2662 }
2663
2664 fn name(self) -> &'static str {
2665 match self {
2666 Self::Reexports => "Re-exports",
2667 Self::Modules => "Modules",
2668 Self::Structs => "Structs",
2669 Self::Unions => "Unions",
2670 Self::Enums => "Enums",
2671 Self::Functions => "Functions",
2672 Self::TypeAliases => "Type Aliases",
2673 Self::Statics => "Statics",
2674 Self::Constants => "Constants",
2675 Self::Traits => "Traits",
2676 Self::Implementations => "Implementations",
2677 Self::AssocFnsWithoutBody => "Type Methods",
2678 Self::AssocFnsWithBody => "Methods",
2679 Self::StructFields => "Struct Fields",
2680 Self::Variants => "Variants",
2681 Self::Macros => "Macros",
2682 Self::PrimitiveTypes => "Primitive Types",
2683 Self::AssociatedTypes => "Associated Types",
2684 Self::AssociatedConstants => "Associated Constants",
2685 Self::ForeignTypes => "Foreign Types",
2686 Self::Keywords => "Keywords",
2687 Self::Attributes => "Attributes",
2688 Self::AttributeMacros => "Attribute Macros",
2689 Self::DeriveMacros => "Derive Macros",
2690 Self::TraitAliases => "Trait Aliases",
2691 }
2692 }
2693}
2694
2695fn item_ty_to_section(ty: ItemType) -> ItemSection {
2696 match ty {
2697 ItemType::ExternCrate | ItemType::Import => ItemSection::Reexports,
2698 ItemType::Module => ItemSection::Modules,
2699 ItemType::Struct => ItemSection::Structs,
2700 ItemType::Union => ItemSection::Unions,
2701 ItemType::Enum => ItemSection::Enums,
2702 ItemType::Function => ItemSection::Functions,
2703 ItemType::TypeAlias => ItemSection::TypeAliases,
2704 ItemType::Static => ItemSection::Statics,
2705 ItemType::Constant => ItemSection::Constants,
2706 ItemType::Trait => ItemSection::Traits,
2707 ItemType::Impl => ItemSection::Implementations,
2708 ItemType::AssocFnWithoutBody => ItemSection::AssocFnsWithoutBody,
2709 ItemType::AssocFnWithBody => ItemSection::AssocFnsWithBody,
2710 ItemType::StructField => ItemSection::StructFields,
2711 ItemType::Variant => ItemSection::Variants,
2712 ItemType::Macro => ItemSection::Macros,
2713 ItemType::Primitive => ItemSection::PrimitiveTypes,
2714 ItemType::AssocType => ItemSection::AssociatedTypes,
2715 ItemType::AssocConst => ItemSection::AssociatedConstants,
2716 ItemType::ForeignType => ItemSection::ForeignTypes,
2717 ItemType::Keyword => ItemSection::Keywords,
2718 ItemType::Attribute => ItemSection::Attributes,
2719 ItemType::ProcAttribute | ItemType::DeclMacroAttribute => ItemSection::AttributeMacros,
2720 ItemType::ProcDerive | ItemType::DeclMacroDerive => ItemSection::DeriveMacros,
2721 ItemType::TraitAlias => ItemSection::TraitAliases,
2722 }
2723}
2724
2725fn collect_paths_for_type(first_ty: &clean::Type, cache: &Cache) -> Vec<String> {
2732 let mut out = Vec::new();
2733 let mut visited = FxHashSet::default();
2734 let mut work = VecDeque::new();
2735
2736 let mut process_path = |did: DefId| {
2737 let get_extern = || cache.external_paths.get(&did).map(|s| &s.0);
2738 let fqp = cache.exact_paths.get(&did).or_else(get_extern);
2739
2740 if let Some(path) = fqp {
2741 out.push(join_path_syms(path));
2742 }
2743 };
2744
2745 work.push_back(first_ty);
2746
2747 while let Some(ty) = work.pop_front() {
2748 if !visited.insert(ty) {
2749 continue;
2750 }
2751
2752 match ty {
2753 clean::Type::Path { path } => process_path(path.def_id()),
2754 clean::Type::Tuple(tys) => {
2755 work.extend(tys.iter());
2756 }
2757 clean::Type::Slice(ty) => {
2758 work.push_back(ty);
2759 }
2760 clean::Type::Array(ty, _) => {
2761 work.push_back(ty);
2762 }
2763 clean::Type::RawPointer(_, ty) => {
2764 work.push_back(ty);
2765 }
2766 clean::Type::BorrowedRef { type_, .. } => {
2767 work.push_back(type_);
2768 }
2769 clean::Type::QPath(clean::QPathData { self_type, trait_, .. }) => {
2770 work.push_back(self_type);
2771 if let Some(trait_) = trait_ {
2772 process_path(trait_.def_id());
2773 }
2774 }
2775 _ => {}
2776 }
2777 }
2778 out
2779}
2780
2781const MAX_FULL_EXAMPLES: usize = 5;
2782const NUM_VISIBLE_LINES: usize = 10;
2783
2784fn render_call_locations<W: fmt::Write>(
2786 mut w: W,
2787 cx: &Context<'_>,
2788 item: &clean::Item,
2789) -> fmt::Result {
2790 let tcx = cx.tcx();
2791 let def_id = item.item_id.expect_def_id();
2792 let key = tcx.def_path_hash(def_id);
2793 let Some(call_locations) = cx.shared.call_locations.get(&key) else { return Ok(()) };
2794
2795 let id = cx.derive_id("scraped-examples");
2797 write!(
2798 &mut w,
2799 "<div class=\"docblock scraped-example-list\">\
2800 <span></span>\
2801 <h5 id=\"{id}\">\
2802 <a href=\"#{id}\">Examples found in repository</a>\
2803 <a class=\"scrape-help\" href=\"{root_path}scrape-examples-help.html\">?</a>\
2804 </h5>",
2805 root_path = cx.root_path(),
2806 id = id
2807 )?;
2808
2809 let link_to_loc = |call_data: &CallData, loc: &CallLocation| -> (String, String) {
2811 let (line_lo, line_hi) = loc.call_expr.line_span;
2812 let (anchor, title) = if line_lo == line_hi {
2813 ((line_lo + 1).to_string(), format!("line {}", line_lo + 1))
2814 } else {
2815 (
2816 format!("{}-{}", line_lo + 1, line_hi + 1),
2817 format!("lines {}-{}", line_lo + 1, line_hi + 1),
2818 )
2819 };
2820 let url = format!("{}{}#{anchor}", cx.root_path(), call_data.url);
2821 (url, title)
2822 };
2823
2824 let write_example = |w: &mut W, (path, call_data): (&PathBuf, &CallData)| -> bool {
2826 let contents = match fs::read_to_string(path) {
2827 Ok(contents) => contents,
2828 Err(err) => {
2829 let span = item.span(tcx).map_or(DUMMY_SP, |span| span.inner());
2830 tcx.dcx().span_err(span, format!("failed to read file {}: {err}", path.display()));
2831 return false;
2832 }
2833 };
2834
2835 assert!(!call_data.locations.is_empty());
2838 let min_loc =
2839 call_data.locations.iter().min_by_key(|loc| loc.enclosing_item.byte_span.0).unwrap();
2840 let byte_min = min_loc.enclosing_item.byte_span.0;
2841 let line_min = min_loc.enclosing_item.line_span.0;
2842 let max_loc =
2843 call_data.locations.iter().max_by_key(|loc| loc.enclosing_item.byte_span.1).unwrap();
2844 let byte_max = max_loc.enclosing_item.byte_span.1;
2845 let line_max = max_loc.enclosing_item.line_span.1;
2846
2847 let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
2849
2850 let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
2853 .locations
2854 .iter()
2855 .map(|loc| {
2856 let (byte_lo, byte_hi) = loc.call_ident.byte_span;
2857 let (line_lo, line_hi) = loc.call_expr.line_span;
2858 let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2859
2860 let line_range = (line_lo - line_min, line_hi - line_min);
2861 let (line_url, line_title) = link_to_loc(call_data, loc);
2862
2863 (byte_range, (line_range, line_url, line_title))
2864 })
2865 .unzip();
2866
2867 let (_, init_url, init_title) = &line_ranges[0];
2868 let needs_expansion = line_max - line_min > NUM_VISIBLE_LINES;
2869 let locations_encoded = serde_json::to_string(&line_ranges).unwrap();
2870
2871 let file_span = rustc_span::DUMMY_SP;
2877
2878 let mut decoration_info = FxIndexMap::default();
2879 decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2880 decoration_info.insert("highlight", byte_ranges);
2881
2882 sources::print_src(
2883 w,
2884 contents_subset,
2885 file_span,
2886 cx,
2887 cx.current.len(),
2888 &highlight::DecorationInfo(decoration_info),
2889 &sources::SourceContext::Embedded(sources::ScrapedInfo {
2890 needs_expansion,
2891 offset: line_min,
2892 name: &call_data.display_name,
2893 url: init_url,
2894 title: init_title,
2895 locations: locations_encoded,
2896 }),
2897 )
2898 .unwrap();
2899
2900 true
2901 };
2902
2903 let ordered_locations = {
2915 fn sort_criterion<'a>(
2916 (_, call_data): &(&PathBuf, &'a CallData),
2917 ) -> (bool, u32, &'a String) {
2918 let (lo, hi) = call_data.locations[0].enclosing_item.byte_span;
2920 (!call_data.is_bin, hi - lo, &call_data.display_name)
2921 }
2922
2923 let mut locs = call_locations.iter().collect::<Vec<_>>();
2924 locs.sort_by_key(sort_criterion);
2925 locs
2926 };
2927
2928 let mut it = ordered_locations.into_iter().peekable();
2929
2930 let write_and_skip_failure = |w: &mut W, it: &mut Peekable<_>| {
2933 for example in it.by_ref() {
2934 if write_example(&mut *w, example) {
2935 break;
2936 }
2937 }
2938 };
2939
2940 write_and_skip_failure(&mut w, &mut it);
2942
2943 if it.peek().is_some() {
2945 write!(
2946 w,
2947 "<details class=\"toggle more-examples-toggle\">\
2948 <summary class=\"hideme\">\
2949 <span>More examples</span>\
2950 </summary>\
2951 <div class=\"hide-more\">Hide additional examples</div>\
2952 <div class=\"more-scraped-examples\">\
2953 <div class=\"toggle-line\"><div class=\"toggle-line-inner\"></div></div>"
2954 )?;
2955
2956 for _ in 0..MAX_FULL_EXAMPLES {
2959 write_and_skip_failure(&mut w, &mut it);
2960 }
2961
2962 if it.peek().is_some() {
2964 w.write_str(
2965 r#"<div class="example-links">Additional examples can be found in:<br><ul>"#,
2966 )?;
2967 it.try_for_each(|(_, call_data)| {
2968 let (url, _) = link_to_loc(call_data, &call_data.locations[0]);
2969 write!(
2970 w,
2971 r#"<li><a href="{url}">{name}</a></li>"#,
2972 url = url,
2973 name = call_data.display_name
2974 )
2975 })?;
2976 w.write_str("</ul></div>")?;
2977 }
2978
2979 w.write_str("</div></details>")?;
2980 }
2981
2982 w.write_str("</div>")
2983}
2984
2985fn render_attributes_in_code(
2986 w: &mut impl fmt::Write,
2987 item: &clean::Item,
2988 prefix: impl fmt::Display,
2989 cx: &Context<'_>,
2990) -> fmt::Result {
2991 render_attributes_in_code_with_options(w, item, prefix, cx, true, "")
2992}
2993
2994pub(super) fn render_attributes_in_code_with_options(
2995 w: &mut impl fmt::Write,
2996 item: &clean::Item,
2997 prefix: impl fmt::Display,
2998 cx: &Context<'_>,
2999 render_doc_hidden: bool,
3000 open_tag: &str,
3001) -> fmt::Result {
3002 w.write_str(open_tag)?;
3003 if render_doc_hidden && item.is_doc_hidden() {
3004 render_code_attribute(&prefix, "#[doc(hidden)]", w)?;
3005 }
3006 for attr in &item.attrs.other_attrs {
3007 let rustc_attr_ir::Attribute::Parsed(kind) = attr else { continue };
3008 let attr = match kind {
3009 AttributeKind::LinkSection { name, .. } => {
3010 Cow::Owned(format!("#[unsafe(link_section = {})]", Escape(&format!("{name:?}"))))
3011 }
3012 AttributeKind::NoMangle(..) => Cow::Borrowed("#[unsafe(no_mangle)]"),
3013 AttributeKind::ExportName { name, .. } => {
3014 Cow::Owned(format!("#[unsafe(export_name = {})]", Escape(&format!("{name:?}"))))
3015 }
3016 AttributeKind::NonExhaustive(..) => Cow::Borrowed("#[non_exhaustive]"),
3017 _ => continue,
3018 };
3019 render_code_attribute(&prefix, attr.as_ref(), w)?;
3020 }
3021
3022 if let Some(def_id) = item.def_id()
3023 && let Some(repr) = repr_attribute(cx.tcx(), cx.cache(), def_id)
3024 {
3025 render_code_attribute(prefix, &repr, w)?;
3026 }
3027 Ok(())
3028}
3029
3030fn render_repr_attribute_in_code(
3031 w: &mut impl fmt::Write,
3032 cx: &Context<'_>,
3033 def_id: DefId,
3034) -> fmt::Result {
3035 if let Some(repr) = repr_attribute(cx.tcx(), cx.cache(), def_id) {
3036 render_code_attribute("", &repr, w)?;
3037 }
3038 Ok(())
3039}
3040
3041fn render_code_attribute(
3042 prefix: impl fmt::Display,
3043 attr: impl fmt::Display,
3044 w: &mut impl fmt::Write,
3045) -> fmt::Result {
3046 write!(w, "<div class=\"code-attribute\">{prefix}{attr}</div>")
3047}
3048
3049fn repr_attribute<'tcx>(
3054 tcx: TyCtxt<'tcx>,
3055 cache: &Cache,
3056 def_id: DefId,
3057) -> Option<Cow<'static, str>> {
3058 let adt = match tcx.def_kind(def_id) {
3059 DefKind::Struct | DefKind::Enum | DefKind::Union => tcx.adt_def(def_id),
3060 _ => return None,
3061 };
3062 let repr = adt.repr();
3063
3064 let is_visible = |def_id| cache.document_hidden || !tcx.is_doc_hidden(def_id);
3065 let is_public_field = |field: &ty::FieldDef| {
3066 (cache.document_private || field.vis.is_public()) && is_visible(field.did)
3067 };
3068
3069 if repr.transparent() {
3074 let is_public = 'is_public: {
3075 if find_attr!(tcx, def_id, RustcPubTransparent(_)) {
3076 break 'is_public true;
3077 }
3078
3079 let var = adt.variant(rustc_abi::FIRST_VARIANT); if !is_visible(var.def_id) {
3083 break 'is_public false;
3084 }
3085
3086 let non_1zst_field = var.fields.iter().find(|field| {
3088 let ty = ty::TypingEnv::post_analysis_no_rigid_aliases(tcx, field.did)
3089 .as_query_input(tcx.type_of(field.did).instantiate_identity().skip_norm_wip());
3090 tcx.layout_of(ty).is_ok_and(|layout| !layout.is_1zst())
3091 });
3092
3093 match non_1zst_field {
3094 Some(field) => is_public_field(field),
3095 None => var.fields.is_empty() || var.fields.iter().any(is_public_field),
3096 }
3097 };
3098
3099 return is_public.then(|| "#[repr(transparent)]".into());
3102 }
3103
3104 let is_public = adt
3106 .variants()
3107 .iter()
3108 .all(|variant| is_visible(variant.def_id) && variant.fields.iter().all(is_public_field));
3109 if !is_public {
3110 return None;
3111 }
3112
3113 let mut result = Vec::<Cow<'_, _>>::new();
3114
3115 if repr.c() {
3116 result.push("C".into());
3117 }
3118 if repr.simd() {
3119 result.push("simd".into());
3120 }
3121 if let Some(int) = repr.int {
3122 let prefix = if int.is_signed() { 'i' } else { 'u' };
3123 let int = match int {
3124 rustc_abi::IntegerType::Pointer(_) => format!("{prefix}size"),
3125 rustc_abi::IntegerType::Fixed(int, _) => {
3126 format!("{prefix}{}", int.size().bytes() * 8)
3127 }
3128 };
3129 result.push(int.into());
3130 }
3131
3132 if let Some(pack) = repr.pack {
3134 result.push(format!("packed({})", pack.bytes()).into());
3135 }
3136 if let Some(align) = repr.align {
3137 result.push(format!("align({})", align.bytes()).into());
3138 }
3139
3140 (!result.is_empty()).then(|| format!("#[repr({})]", result.join(", ")).into())
3141}
3142
3143pub(crate) fn compute_if_deref_target_implements_copy(tcx: TyCtxt<'_>, impl_def_id: DefId) -> bool {
3144 if let Some(impl_def_id) = impl_def_id.as_local()
3145 && let item = tcx.hir_expect_item(impl_def_id)
3146 && let rustc_hir::ItemKind::Impl(impl_item) = item.kind
3147 {
3148 for item in impl_item.items {
3149 let item = tcx.hir_impl_item(*item);
3150 if matches!(item.kind, rustc_hir::ImplItemKind::Type(_)) {
3151 let item_def_id = item.owner_id.to_def_id();
3152 let ty = tcx.type_of(item_def_id).instantiate_identity().skip_norm_wip();
3153 let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
3154 return tcx.type_is_copy_modulo_regions(typing_env, ty);
3155 }
3156 }
3157 }
3158 false
3159}