1use std::borrow::Cow;
2use std::cmp::Ordering;
3use std::fmt;
4
5use askama::Template;
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_hir::def::CtorKind;
8use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet};
9use tracing::debug;
10
11use super::{Context, ItemSection, impl_trait_key, item_ty_to_section};
12use crate::clean::{self, ItemKind};
13use crate::formats::Impl;
14use crate::formats::item_type::ItemType;
15use crate::html::format::{print_path, print_type};
16use crate::html::markdown::{IdMap, MarkdownWithToc};
17use crate::html::render::print_item::compare_names;
18
19#[derive(Clone, Copy)]
20pub(crate) enum ModuleLike {
21 Module,
22 Crate,
23}
24
25impl ModuleLike {
26 pub(crate) fn is_crate(self) -> bool {
27 matches!(self, ModuleLike::Crate)
28 }
29}
30impl<'a> From<&'a clean::Item> for ModuleLike {
31 fn from(it: &'a clean::Item) -> ModuleLike {
32 if it.is_crate() { ModuleLike::Crate } else { ModuleLike::Module }
33 }
34}
35
36#[derive(Template)]
37#[template(path = "sidebar.html")]
38pub(super) struct Sidebar<'a> {
39 pub(super) title_prefix: &'static str,
40 pub(super) title: &'a str,
41 pub(super) is_crate: bool,
42 pub(super) parent_is_crate: bool,
43 pub(super) is_mod: bool,
44 pub(super) blocks: Vec<LinkBlock<'a>>,
45 pub(super) path: String,
46}
47
48impl Sidebar<'_> {
49 pub fn should_render_blocks(&self) -> bool {
52 self.blocks.iter().any(LinkBlock::should_render)
53 }
54}
55
56pub(crate) struct LinkBlock<'a> {
58 heading: Link<'a>,
62 class: &'static str,
63 links: Vec<Link<'a>>,
64 force_render: bool,
66}
67
68impl<'a> LinkBlock<'a> {
69 pub fn new(heading: Link<'a>, class: &'static str, links: Vec<Link<'a>>) -> Self {
70 Self { heading, links, class, force_render: false }
71 }
72
73 pub fn forced(heading: Link<'a>, class: &'static str) -> Self {
74 Self { heading, links: vec![], class, force_render: true }
75 }
76
77 pub fn should_render(&self) -> bool {
78 self.force_render || !self.links.is_empty()
79 }
80}
81
82#[derive(PartialEq, Eq, Hash, Clone)]
84pub(crate) struct Link<'a> {
85 name: Cow<'a, str>,
87 name_html: Option<Cow<'a, str>>,
89 href: Cow<'a, str>,
91 children: Vec<Link<'a>>,
93}
94
95impl Ord for Link<'_> {
96 fn cmp(&self, other: &Self) -> Ordering {
97 match compare_names(&self.name, &other.name) {
98 Ordering::Equal => {}
99 result => return result,
100 }
101 (&self.name_html, &self.href, &self.children).cmp(&(
102 &other.name_html,
103 &other.href,
104 &other.children,
105 ))
106 }
107}
108
109impl PartialOrd for Link<'_> {
110 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
111 Some(self.cmp(other))
112 }
113}
114
115impl<'a> Link<'a> {
116 pub fn new(href: impl Into<Cow<'a, str>>, name: impl Into<Cow<'a, str>>) -> Self {
117 Self { href: href.into(), name: name.into(), children: vec![], name_html: None }
118 }
119 pub fn empty() -> Link<'static> {
120 Link::new("", "")
121 }
122}
123
124pub(crate) mod filters {
125 use std::fmt::{self, Display};
126
127 use askama::filters::Safe;
128
129 use crate::html::escape::EscapeBodyTextWithWbr;
130
131 #[askama::filter_fn]
132 pub(crate) fn wrapped(
133 v: impl Display,
134 _: &dyn askama::Values,
135 ) -> askama::Result<Safe<impl Display>> {
136 let string = v.to_string();
137 Ok(Safe(fmt::from_fn(move |f| EscapeBodyTextWithWbr(&string).fmt(f))))
138 }
139}
140
141pub(super) fn print_sidebar(
142 cx: &Context<'_>,
143 it: &clean::Item,
144 mut buffer: impl fmt::Write,
145) -> fmt::Result {
146 let mut ids = IdMap::new();
147 let mut blocks: Vec<LinkBlock<'_>> = docblock_toc(cx, it, &mut ids).into_iter().collect();
148 let deref_id_map = cx.deref_id_map.borrow();
149 match it.kind {
150 ItemKind::Struct(ref s) => sidebar_struct(cx, it, s, &mut blocks, &deref_id_map),
151 ItemKind::Trait(ref t) => sidebar_trait(cx, it, t, &mut blocks, &deref_id_map),
152 ItemKind::PrimitiveType(_) => sidebar_primitive(cx, it, &mut blocks, &deref_id_map),
153 ItemKind::Union(ref u) => sidebar_union(cx, it, u, &mut blocks, &deref_id_map),
154 ItemKind::Enum(ref e) => sidebar_enum(cx, it, e, &mut blocks, &deref_id_map),
155 ItemKind::TypeAlias(ref t) => sidebar_type_alias(cx, it, t, &mut blocks, &deref_id_map),
156 ItemKind::Module(ref m) => {
157 blocks.push(sidebar_module(&m.items, &mut ids, ModuleLike::from(it)))
158 }
159 ItemKind::ForeignType => sidebar_foreign_type(cx, it, &mut blocks, &deref_id_map),
160 _ => {}
161 }
162 let (title_prefix, title) = if !blocks.is_empty() && !it.is_crate() {
172 (
173 match it.kind {
174 ItemKind::Module(..) => "Module ",
175 _ => "",
176 },
177 it.name.as_ref().unwrap().as_str(),
178 )
179 } else {
180 ("", "")
181 };
182 let sidebar_path =
189 if it.is_mod() { &cx.current[..cx.current.len() - 1] } else { &cx.current[..] };
190 let path: String = if sidebar_path.len() > 1 || !title.is_empty() {
191 let path = sidebar_path.iter().map(|s| s.as_str()).intersperse("::").collect();
192 if sidebar_path.len() == 1 { format!("crate {path}") } else { path }
193 } else {
194 "".into()
195 };
196 let sidebar = Sidebar {
197 title_prefix,
198 title,
199 is_mod: it.is_mod(),
200 is_crate: it.is_crate(),
201 parent_is_crate: sidebar_path.len() == 1,
202 blocks,
203 path,
204 };
205 sidebar.render_into(&mut buffer)?;
206 Ok(())
207}
208
209fn get_struct_fields_name<'a>(fields: &'a [clean::Item]) -> Vec<Link<'a>> {
210 let mut fields = fields
211 .iter()
212 .filter(|f| matches!(f.kind, ItemKind::StructField(..)))
213 .filter_map(|f| {
214 f.name.as_ref().map(|name| Link::new(format!("structfield.{name}"), name.as_str()))
215 })
216 .collect::<Vec<Link<'a>>>();
217 fields.sort();
218 fields
219}
220
221fn docblock_toc<'a>(
222 cx: &'a Context<'_>,
223 it: &'a clean::Item,
224 ids: &mut IdMap,
225) -> Option<LinkBlock<'a>> {
226 let (toc, _) = MarkdownWithToc {
227 content: &it.doc_value(),
228 links: &it.links(cx),
229 ids,
230 error_codes: cx.shared.codes,
231 edition: cx.shared.edition(),
232 playground: &cx.shared.playground,
233 }
234 .into_parts();
235 let links: Vec<Link<'_>> = toc
236 .entries
237 .into_iter()
238 .map(|entry| {
239 Link {
240 name_html: if entry.html == entry.name { None } else { Some(entry.html.into()) },
241 name: entry.name.into(),
242 href: entry.id.into(),
243 children: entry
244 .children
245 .entries
246 .into_iter()
247 .map(|entry| Link {
248 name_html: if entry.html == entry.name {
249 None
250 } else {
251 Some(entry.html.into())
252 },
253 name: entry.name.into(),
254 href: entry.id.into(),
255 children: vec![],
259 })
260 .collect(),
261 }
262 })
263 .collect();
264 if links.is_empty() {
265 None
266 } else {
267 Some(LinkBlock::new(Link::new("", "Sections"), "top-toc", links))
268 }
269}
270
271fn sidebar_struct<'a>(
272 cx: &'a Context<'_>,
273 it: &'a clean::Item,
274 s: &'a clean::Struct,
275 items: &mut Vec<LinkBlock<'a>>,
276 deref_id_map: &'a DefIdMap<String>,
277) {
278 let fields = get_struct_fields_name(&s.fields);
279 let field_name = match s.ctor_kind {
280 Some(CtorKind::Fn) => Some("Tuple Fields"),
281 None => Some("Fields"),
282 _ => None,
283 };
284 if let Some(name) = field_name {
285 items.push(LinkBlock::new(Link::new("fields", name), "structfield", fields));
286 }
287 sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map);
288}
289
290fn sidebar_trait<'a>(
291 cx: &'a Context<'_>,
292 it: &'a clean::Item,
293 t: &'a clean::Trait,
294 blocks: &mut Vec<LinkBlock<'a>>,
295 deref_id_map: &'a DefIdMap<String>,
296) {
297 fn filter_items<'a>(
298 items: &'a [clean::Item],
299 filt: impl Fn(&clean::Item) -> bool,
300 ty: &str,
301 ) -> Vec<Link<'a>> {
302 let mut res = items
303 .iter()
304 .filter_map(|m: &clean::Item| match m.name {
305 Some(ref name) if filt(m) => Some(Link::new(format!("{ty}.{name}"), name.as_str())),
306 _ => None,
307 })
308 .collect::<Vec<Link<'a>>>();
309 res.sort();
310 res
311 }
312
313 let req_assoc_tys = filter_items(&t.items, |m| m.is_assoc_ty_without_body(), "associatedtype");
314 let prov_assoc_tys = filter_items(&t.items, |m| m.is_assoc_ty_with_body(), "associatedtype");
315 let req_assoc_consts =
316 filter_items(&t.items, |m| m.is_assoc_const_without_body(), "associatedconstant");
317 let prov_assoc_consts =
318 filter_items(&t.items, |m| m.is_assoc_const_with_body(), "associatedconstant");
319 let req_assoc_fns = filter_items(&t.items, |m| m.is_assoc_fn_without_body(), "tymethod");
320 let prov_assoc_fns = filter_items(&t.items, |m| m.is_assoc_fn_with_body(), "method");
321
322 let mut foreign_impls = vec![];
323 if let Some(implementors) = cx.cache().implementors.get(&it.item_id.expect_def_id()) {
324 foreign_impls.extend(
325 implementors
326 .iter()
327 .filter(|i| !i.is_on_local_type(cx))
328 .filter_map(|i| super::extract_for_impl_name(&i.impl_item, cx))
329 .map(|(name, id)| Link::new(id, name)),
330 );
331 foreign_impls.sort();
332 }
333
334 blocks.extend(
335 [
336 ("required-associated-consts", "Required Associated Constants", req_assoc_consts),
337 ("provided-associated-consts", "Provided Associated Constants", prov_assoc_consts),
338 ("required-associated-types", "Required Associated Types", req_assoc_tys),
339 ("provided-associated-types", "Provided Associated Types", prov_assoc_tys),
340 ]
341 .into_iter()
342 .map(|(id, title, items)| LinkBlock::new(Link::new(id, title), "", items)),
343 );
344
345 let tcx = cx.tcx();
346 let mut req_assoc_fns_link =
349 LinkBlock::new(Link::new("required-methods", "Required Methods"), "", req_assoc_fns);
350 let rustc_middle::ty::TraitDef { must_implement_one_of, .. } = tcx.trait_def(t.def_id);
351 req_assoc_fns_link.force_render = must_implement_one_of.is_some();
352 blocks.push(req_assoc_fns_link);
353
354 blocks.push(LinkBlock::new(
355 Link::new("provided-methods", "Provided Methods"),
356 "",
357 prov_assoc_fns,
358 ));
359
360 sidebar_assoc_items(cx, it.item_id.expect_def_id(), blocks, deref_id_map);
361
362 blocks.push(LinkBlock::forced(
363 Link::new("dyn-compatibility", "Dyn Compatibility"),
364 "dyn-compatibility-note",
365 ));
366
367 blocks.push(LinkBlock::new(
368 Link::new("foreign-impls", "Implementations on Foreign Types"),
369 "",
370 foreign_impls,
371 ));
372
373 blocks.push(LinkBlock::forced(Link::new("implementors", "Implementors"), "impl"));
374 if t.is_auto(tcx) {
375 blocks.push(LinkBlock::forced(
376 Link::new("synthetic-implementors", "Auto Implementors"),
377 "impl-auto",
378 ));
379 }
380}
381
382fn sidebar_primitive<'a>(
383 cx: &'a Context<'_>,
384 it: &'a clean::Item,
385 items: &mut Vec<LinkBlock<'a>>,
386 deref_id_map: &'a DefIdMap<String>,
387) {
388 if it.name.map(|n| n.as_str() != "reference").unwrap_or(false) {
389 sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map);
390 } else {
391 let (concrete, synthetic, blanket_impl) =
392 super::get_filtered_impls_for_reference(&cx.shared, it);
393
394 sidebar_render_assoc_items(cx, &mut IdMap::new(), concrete, synthetic, blanket_impl, items);
395 }
396}
397
398fn sidebar_type_alias<'a>(
399 cx: &'a Context<'_>,
400 it: &'a clean::Item,
401 t: &'a clean::TypeAlias,
402 items: &mut Vec<LinkBlock<'a>>,
403 deref_id_map: &'a DefIdMap<String>,
404) {
405 if let Some(inner_type) = &t.inner_type {
406 items.push(LinkBlock::forced(Link::new("aliased-type", "Aliased Type"), "type"));
407 match inner_type {
408 clean::TypeAliasInnerType::Enum { variants, is_non_exhaustive: _ } => {
409 let mut variants = variants
410 .iter()
411 .filter(|i| !i.is_stripped())
412 .filter_map(|v| v.name)
413 .map(|name| Link::new(format!("variant.{name}"), name.to_string()))
414 .collect::<Vec<_>>();
415 variants.sort_unstable();
416
417 items.push(LinkBlock::new(Link::new("variants", "Variants"), "variant", variants));
418 }
419 clean::TypeAliasInnerType::Union { fields }
420 | clean::TypeAliasInnerType::Struct { ctor_kind: _, fields } => {
421 let fields = get_struct_fields_name(fields);
422 items.push(LinkBlock::new(Link::new("fields", "Fields"), "field", fields));
423 }
424 }
425 }
426 let alias_def_id = it.item_id.expect_def_id();
427 let aliased_type = t.inner_type.as_ref().and_then(|_| {
428 cx.tcx().type_of(alias_def_id).instantiate_identity().skip_norm_wip().ty_adt_def()
429 });
430 sidebar_assoc_items_with_aliased_type(
431 cx,
432 alias_def_id,
433 items,
434 deref_id_map,
435 aliased_type.map(|adt| adt.did()),
436 );
437}
438
439fn sidebar_union<'a>(
440 cx: &'a Context<'_>,
441 it: &'a clean::Item,
442 u: &'a clean::Union,
443 items: &mut Vec<LinkBlock<'a>>,
444 deref_id_map: &'a DefIdMap<String>,
445) {
446 let fields = get_struct_fields_name(&u.fields);
447 items.push(LinkBlock::new(Link::new("fields", "Fields"), "structfield", fields));
448 sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map);
449}
450
451fn sidebar_assoc_items<'a>(
453 cx: &'a Context<'_>,
454 item_def_id: DefId,
455 links: &mut Vec<LinkBlock<'a>>,
456 deref_id_map: &'a DefIdMap<String>,
457) {
458 sidebar_assoc_items_with_aliased_type(cx, item_def_id, links, deref_id_map, None)
459}
460
461fn sidebar_assoc_items_with_aliased_type<'a>(
462 cx: &'a Context<'_>,
463 item_def_id: DefId,
464 links: &mut Vec<LinkBlock<'a>>,
465 deref_id_map: &'a DefIdMap<String>,
466 aliased_type: Option<DefId>,
467) {
468 let cache = cx.cache();
469
470 let v = match cache.impls.get(&item_def_id) {
471 Some(impls) => impls.as_slice(),
472 None if aliased_type.is_some() => &[],
473 None => return,
474 };
475 let mut assoc_consts = Vec::new();
476 let mut assoc_types = Vec::new();
477 let mut assoc_fns = Vec::new();
478 let mut methods = Vec::new();
479 let mut used_links = UsedLinks::default();
480 let mut id_map = IdMap::new();
481
482 {
483 let used_links_bor = &mut used_links;
484 for impl_ in v.iter().map(|i| i.inner_impl()).filter(|i| i.trait_.is_none()) {
485 assoc_consts.extend(get_associated_constants(impl_, used_links_bor));
486 assoc_types.extend(get_associated_types(impl_, used_links_bor));
487 methods.extend(get_methods(
488 impl_,
489 GetMethodsMode::AlsoCollectAssocFns { assoc_fns: &mut assoc_fns },
490 used_links_bor,
491 cx,
492 ));
493 }
494 assoc_consts.sort();
496 assoc_types.sort();
497 postprocess_method_list(&mut assoc_fns);
498 postprocess_method_list(&mut methods);
499 }
500
501 let mut blocks = vec![
502 LinkBlock::new(
503 Link::new("implementations", "Associated Constants"),
504 "associatedconstant",
505 assoc_consts,
506 ),
507 LinkBlock::new(
508 Link::new("implementations", "Associated Types"),
509 "associatedtype",
510 assoc_types,
511 ),
512 LinkBlock::new(Link::new("implementations", "Associated Functions"), "method", assoc_fns),
513 LinkBlock::new(Link::new("implementations", "Methods"), "method", methods),
514 ];
515
516 if let Some((impl_, deref_mut)) = super::get_deref_impls(cx, v, item_def_id, aliased_type) {
517 let mut derefs = DefIdSet::default();
518 derefs.insert(item_def_id);
519 derefs.extend(aliased_type);
520 sidebar_deref_methods(
521 cx,
522 &mut blocks,
523 impl_,
524 deref_mut,
525 &mut derefs,
526 &mut used_links,
527 deref_id_map,
528 );
529 }
530
531 if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
532 let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
533 v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_auto());
534 let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) =
535 concrete.into_iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_blanket());
536
537 sidebar_render_assoc_items(cx, &mut id_map, concrete, synthetic, blanket_impl, &mut blocks);
538 }
539
540 links.append(&mut blocks);
541}
542
543fn sidebar_deref_methods<'a>(
544 cx: &'a Context<'_>,
545 out: &mut Vec<LinkBlock<'a>>,
546 impl_: &Impl,
547 deref_mut: bool,
548 derefs: &mut DefIdSet,
549 used_links: &mut UsedLinks,
550 deref_id_map: &'a DefIdMap<String>,
551) {
552 let c = cx.cache();
553
554 debug!("found Deref: {impl_:?}");
555 if let Some((target, real_target)) =
556 impl_.inner_impl().items.iter().find_map(|item| match &item.kind {
557 ItemKind::AssocType(clean::AssocType { type_: Some(type_), .. }) => {
558 Some((type_.middle_type.as_ref().unwrap_or(&type_.type_), &type_.type_))
559 }
560 _ => None,
561 })
562 {
563 debug!("found target, real_target: {target:?} {real_target:?}");
564
565 if let Some(did) = target.def_id(c) &&
566 let Some(type_did) = impl_.inner_impl().for_.def_id(c) &&
567 (did == type_did || !derefs.insert(did))
569 {
570 return;
572 }
573 let tcx = cx.tcx();
574 let inner_impl = target
575 .def_id(c)
576 .or_else(|| {
577 target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned())
578 })
579 .and_then(|did| c.impls.get(&did));
580 if let Some(impls) = inner_impl {
581 debug!("found inner_impl: {impls:?}");
582 let is_deref_target_copy =
583 super::compute_if_deref_target_implements_copy(tcx, impl_.def_id());
584 let mut ret = impls
585 .iter()
586 .filter(|i| {
587 i.inner_impl().trait_.is_none()
588 && target.is_doc_subtype_of(&i.inner_impl().for_, cx)
589 })
590 .flat_map(|i| {
591 get_methods(
592 i.inner_impl(),
593 GetMethodsMode::Deref { deref_mut, is_deref_target_copy },
594 used_links,
595 cx,
596 )
597 .collect::<Vec<_>>()
598 })
599 .collect::<Vec<_>>();
600 if !ret.is_empty() {
601 let id = if let Some(target_def_id) = real_target.def_id(c) {
602 Cow::Borrowed(
603 deref_id_map
604 .get(&target_def_id)
605 .expect("Deref section without derived id")
606 .as_str(),
607 )
608 } else {
609 Cow::Borrowed("deref-methods")
610 };
611 let title = format!(
612 "Methods from {:#}<Target={:#}>",
613 print_path(impl_.inner_impl().trait_.as_ref().unwrap(), cx),
614 print_type(real_target, cx),
615 );
616
617 postprocess_method_list(&mut ret);
618 out.push(LinkBlock::new(Link::new(id, title), "deref-methods", ret));
619 }
620 }
621
622 if let Some(target_did) = target.def_id(c)
624 && let Some(target_impls) = c.impls.get(&target_did)
625 && let Some(target_deref_impl) = target_impls.iter().find(|i| {
626 i.inner_impl().trait_.as_ref().map(|t| t.is_deref_trait(tcx)).unwrap_or(false)
627 && !i.is_negative_trait_impl()
628 })
629 {
630 sidebar_deref_methods(
631 cx,
632 out,
633 target_deref_impl,
634 deref_mut,
635 derefs,
636 used_links,
637 deref_id_map,
638 );
639 }
640 }
641}
642
643fn sidebar_enum<'a>(
644 cx: &'a Context<'_>,
645 it: &'a clean::Item,
646 e: &'a clean::Enum,
647 items: &mut Vec<LinkBlock<'a>>,
648 deref_id_map: &'a DefIdMap<String>,
649) {
650 let mut variants = e
651 .non_stripped_variants()
652 .filter_map(|v| v.name)
653 .map(|name| Link::new(format!("variant.{name}"), name.to_string()))
654 .collect::<Vec<_>>();
655 variants.sort_unstable();
656
657 items.push(LinkBlock::new(Link::new("variants", "Variants"), "variant", variants));
658 sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map);
659}
660
661pub(crate) fn sidebar_module_like(
662 item_sections_in_use: FxHashSet<ItemSection>,
663 ids: &mut IdMap,
664 module_like: ModuleLike,
665) -> LinkBlock<'static> {
666 let item_sections: Vec<Link<'_>> = ItemSection::ALL
667 .iter()
668 .copied()
669 .filter(|sec| item_sections_in_use.contains(sec))
670 .map(|sec| Link::new(ids.derive(sec.id()), sec.name()))
671 .collect();
672 let header = if let Some(first_section) = item_sections.first() {
673 Link::new(
674 first_section.href.clone(),
675 if module_like.is_crate() { "Crate Items" } else { "Module Items" },
676 )
677 } else {
678 Link::empty()
679 };
680 LinkBlock::new(header, "", item_sections)
681}
682
683fn sidebar_module(
684 items: &[clean::Item],
685 ids: &mut IdMap,
686 module_like: ModuleLike,
687) -> LinkBlock<'static> {
688 let mut item_sections_in_use: FxHashSet<_> = Default::default();
689
690 for item in items.iter().filter(|it| {
691 !it.is_stripped()
692 && it
693 .name
694 .or_else(|| {
695 if let ItemKind::Import(ref i) = it.kind
696 && let clean::ImportKind::Simple(s) = i.kind
697 {
698 Some(s)
699 } else {
700 None
701 }
702 })
703 .is_some()
704 }) {
705 for type_ in item.types() {
706 item_sections_in_use.insert(item_ty_to_section(type_));
707 }
708 }
709
710 sidebar_module_like(item_sections_in_use, ids, module_like)
711}
712
713fn sidebar_foreign_type<'a>(
714 cx: &'a Context<'_>,
715 it: &'a clean::Item,
716 items: &mut Vec<LinkBlock<'a>>,
717 deref_id_map: &'a DefIdMap<String>,
718) {
719 sidebar_assoc_items(cx, it.item_id.expect_def_id(), items, deref_id_map);
720}
721
722fn sidebar_render_assoc_items(
724 cx: &Context<'_>,
725 id_map: &mut IdMap,
726 concrete: Vec<&Impl>,
727 synthetic: Vec<&Impl>,
728 blanket_impl: Vec<&Impl>,
729 items: &mut Vec<LinkBlock<'_>>,
730) {
731 let format_impls = |impls: Vec<&Impl>, id_map: &mut IdMap| {
732 let mut links = FxHashSet::default();
733
734 let mut ret = impls
735 .iter()
736 .filter_map(|i| {
737 let encoded = id_map.derive(super::get_id_for_impl(cx.tcx(), i.impl_item.item_id));
738 let generated = Link::new(encoded, impl_trait_key(cx, i)?);
739 if links.insert(generated.clone()) { Some(generated) } else { None }
740 })
741 .collect::<Vec<Link<'static>>>();
742 ret.sort();
743 ret
744 };
745
746 let concrete = format_impls(concrete, id_map);
747 let synthetic = format_impls(synthetic, id_map);
748 let blanket = format_impls(blanket_impl, id_map);
749 items.extend([
750 LinkBlock::new(
751 Link::new("trait-implementations", "Trait Implementations"),
752 "trait-implementation",
753 concrete,
754 ),
755 LinkBlock::new(
756 Link::new("synthetic-implementations", "Auto Trait Implementations"),
757 "synthetic-implementation",
758 synthetic,
759 ),
760 LinkBlock::new(
761 Link::new("blanket-implementations", "Blanket Implementations"),
762 "blanket-implementation",
763 blanket,
764 ),
765 ]);
766}
767
768type UsedLinks = FxHashMap<String, usize>;
770
771fn get_next_url(used_links: &mut UsedLinks, url: String) -> String {
772 let count = used_links.entry(url.clone()).or_insert(0);
773 let res = if *count == 0 { url } else { format!("{url}-{count}") };
774 *count += 1;
775 res
776}
777
778enum GetMethodsMode<'r, 'l> {
779 Deref { deref_mut: bool, is_deref_target_copy: bool },
780 AlsoCollectAssocFns { assoc_fns: &'r mut Vec<Link<'l>> },
781}
782
783fn get_methods<'a>(
784 i: &'a clean::Impl,
785 mut mode: GetMethodsMode<'_, 'a>,
786 used_links: &mut UsedLinks,
787 cx: &Context<'_>,
788) -> impl Iterator<Item = Link<'a>> {
789 i.items.iter().filter_map(move |item| {
790 if let Some(ref name) = item.name
791 && item.is_assoc_fn_with_body()
792 {
793 let mut build_link = || {
794 Link::new(
795 get_next_url(
796 used_links,
797 format!("{typ}.{name}", typ = ItemType::AssocFnWithBody),
798 ),
799 format!("{} ({:#})", name.as_str(), print_type(&i.for_, cx)),
800 )
801 };
802 match &mut mode {
803 &mut GetMethodsMode::Deref { deref_mut, is_deref_target_copy } => {
804 if super::should_render_item_for_deref(
805 item,
806 deref_mut,
807 cx.tcx(),
808 is_deref_target_copy,
809 ) {
810 Some(build_link())
811 } else {
812 None
813 }
814 }
815 GetMethodsMode::AlsoCollectAssocFns { assoc_fns } => {
816 if item.has_self_param() {
817 Some(build_link())
818 } else {
819 assoc_fns.push(build_link());
820 None
821 }
822 }
823 }
824 } else {
825 None
826 }
827 })
828}
829
830fn postprocess_method_list(methods: &mut [Link<'_>]) {
831 methods.sort();
833 let trunc_to = |dst: &mut Cow<'_, str>, len: usize| match dst {
834 Cow::Borrowed(s) => *s = &s[..len],
835 Cow::Owned(s) => s.truncate(len),
836 };
837 fn get_short_name<'a>(itm: Option<&'a Link<'a>>) -> Option<&'a str> {
838 Some(itm?.name.split_once(' ')?.0)
839 }
840 for i in 0..methods.len() {
841 let short_name = get_short_name(methods.get(i));
842 if get_short_name(methods.get(i.wrapping_sub(1))) != short_name
843 && short_name != get_short_name(methods.get(i + 1))
844 {
845 let shortened_len = short_name.unwrap().len();
846 trunc_to(&mut methods[i].name, shortened_len);
847 }
848 }
849}
850
851fn get_associated_constants<'a>(
852 i: &'a clean::Impl,
853 used_links: &mut UsedLinks,
854) -> impl Iterator<Item = Link<'a>> {
855 i.items.iter().filter_map(|item| {
856 if let Some(ref name) = item.name
857 && item.is_assoc_const_with_body()
858 {
859 Some(Link::new(
860 get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::AssocConst)),
861 name.as_str(),
862 ))
863 } else {
864 None
865 }
866 })
867}
868
869fn get_associated_types<'a>(
870 i: &'a clean::Impl,
871 used_links: &mut UsedLinks,
872) -> impl Iterator<Item = Link<'a>> {
873 i.items.iter().filter_map(|item| {
874 if let Some(ref name) = item.name
875 && item.is_assoc_ty_with_body()
876 {
877 Some(Link::new(
878 get_next_url(used_links, format!("{typ}.{name}", typ = ItemType::AssocType)),
879 name.as_str(),
880 ))
881 } else {
882 None
883 }
884 })
885}