1 //! HTML formatting module
3 //! This module contains a large number of `fmt::Display` implementations for
4 //! various types in `rustdoc::clean`. These implementations all currently
5 //! assume that HTML output is desired, although it may be possible to redesign
6 //! them in the future to instead emit any format desired.
11 use std::iter::{self, once};
14 use rustc_attr::{ConstStability, StabilityLevel};
15 use rustc_data_structures::captures::Captures;
16 use rustc_data_structures::fx::FxHashSet;
18 use rustc_hir::def::DefKind;
19 use rustc_hir::def_id::DefId;
20 use rustc_metadata::creader::{CStore, LoadedMacro};
22 use rustc_middle::ty::DefIdTree;
23 use rustc_middle::ty::TyCtxt;
24 use rustc_span::symbol::kw;
25 use rustc_span::{sym, Symbol};
26 use rustc_target::spec::abi::Abi;
28 use itertools::Itertools;
31 self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
34 use crate::formats::item_type::ItemType;
35 use crate::html::escape::Escape;
36 use crate::html::render::Context;
38 use super::url_parts_builder::estimate_item_path_byte_length;
39 use super::url_parts_builder::UrlPartsBuilder;
41 pub(crate) trait Print {
42 fn print(self, buffer: &mut Buffer);
47 F: FnOnce(&mut Buffer),
49 fn print(self, buffer: &mut Buffer) {
54 impl Print for String {
55 fn print(self, buffer: &mut Buffer) {
56 buffer.write_str(&self);
60 impl Print for &'_ str {
61 fn print(self, buffer: &mut Buffer) {
62 buffer.write_str(self);
66 #[derive(Debug, Clone)]
67 pub(crate) struct Buffer {
72 impl core::fmt::Write for Buffer {
74 fn write_str(&mut self, s: &str) -> fmt::Result {
75 self.buffer.write_str(s)
79 fn write_char(&mut self, c: char) -> fmt::Result {
80 self.buffer.write_char(c)
84 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
85 self.buffer.write_fmt(args)
90 pub(crate) fn empty_from(v: &Buffer) -> Buffer {
91 Buffer { for_html: v.for_html, buffer: String::new() }
94 pub(crate) fn html() -> Buffer {
95 Buffer { for_html: true, buffer: String::new() }
98 pub(crate) fn new() -> Buffer {
99 Buffer { for_html: false, buffer: String::new() }
102 pub(crate) fn is_empty(&self) -> bool {
103 self.buffer.is_empty()
106 pub(crate) fn into_inner(self) -> String {
110 pub(crate) fn push_str(&mut self, s: &str) {
111 self.buffer.push_str(s);
114 pub(crate) fn push_buffer(&mut self, other: Buffer) {
115 self.buffer.push_str(&other.buffer);
118 // Intended for consumption by write! and writeln! (std::fmt) but without
119 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
121 pub(crate) fn write_str(&mut self, s: &str) {
122 self.buffer.push_str(s);
125 // Intended for consumption by write! and writeln! (std::fmt) but without
126 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
128 pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
130 self.buffer.write_fmt(v).unwrap();
133 pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
138 pub(crate) fn is_for_html(&self) -> bool {
142 pub(crate) fn reserve(&mut self, additional: usize) {
143 self.buffer.reserve(additional)
146 pub(crate) fn len(&self) -> usize {
151 pub(crate) fn comma_sep<T: fmt::Display>(
152 items: impl Iterator<Item = T>,
153 space_after_comma: bool,
154 ) -> impl fmt::Display {
155 display_fn(move |f| {
156 for (i, item) in items.enumerate() {
158 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
160 fmt::Display::fmt(&item, f)?;
166 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
167 bounds: &'a [clean::GenericBound],
168 cx: &'a Context<'tcx>,
169 ) -> impl fmt::Display + 'a + Captures<'tcx> {
170 display_fn(move |f| {
171 let mut bounds_dup = FxHashSet::default();
173 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
177 fmt::Display::fmt(&bound.print(cx), f)?;
183 impl clean::GenericParamDef {
184 pub(crate) fn print<'a, 'tcx: 'a>(
186 cx: &'a Context<'tcx>,
187 ) -> impl fmt::Display + 'a + Captures<'tcx> {
188 display_fn(move |f| match &self.kind {
189 clean::GenericParamDefKind::Lifetime { outlives } => {
190 write!(f, "{}", self.name)?;
192 if !outlives.is_empty() {
194 for (i, lt) in outlives.iter().enumerate() {
198 write!(f, "{}", lt.print())?;
204 clean::GenericParamDefKind::Type { bounds, default, .. } => {
205 f.write_str(self.name.as_str())?;
207 if !bounds.is_empty() {
209 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
211 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
215 if let Some(ref ty) = default {
217 write!(f, " = {:#}", ty.print(cx))?;
219 write!(f, " = {}", ty.print(cx))?;
225 clean::GenericParamDefKind::Const { ty, default, .. } => {
227 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
229 write!(f, "const {}: {}", self.name, ty.print(cx))?;
232 if let Some(default) = default {
234 write!(f, " = {:#}", default)?;
236 write!(f, " = {}", default)?;
246 impl clean::Generics {
247 pub(crate) fn print<'a, 'tcx: 'a>(
249 cx: &'a Context<'tcx>,
250 ) -> impl fmt::Display + 'a + Captures<'tcx> {
251 display_fn(move |f| {
252 let mut real_params =
253 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
254 if real_params.peek().is_none() {
259 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
261 write!(f, "<{}>", comma_sep(real_params.map(|g| g.print(cx)), true))
267 #[derive(Clone, Copy, PartialEq, Eq)]
268 pub(crate) enum Ending {
273 /// * The Generics from which to emit a where-clause.
274 /// * The number of spaces to indent each line with.
275 /// * Whether the where-clause needs to add a comma and newline after the last bound.
276 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
277 gens: &'a clean::Generics,
278 cx: &'a Context<'tcx>,
281 ) -> impl fmt::Display + 'a + Captures<'tcx> {
284 display_fn(move |f| {
285 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
286 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
288 display_fn(move |f| {
292 f.write_str("<br>")?;
296 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
297 let ty_cx = ty.print(cx);
298 let generic_bounds = print_generic_bounds(bounds, cx);
300 if bound_params.is_empty() {
302 write!(f, "{ty_cx:#}: {generic_bounds:#}")
304 write!(f, "{ty_cx}: {generic_bounds}")
310 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
311 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
316 "for<{}> {ty_cx}: {generic_bounds}",
317 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
322 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
323 let mut bounds_display = String::new();
324 for bound in bounds.iter().map(|b| b.print(cx)) {
325 write!(bounds_display, "{bound} + ")?;
327 bounds_display.truncate(bounds_display.len() - " + ".len());
328 write!(f, "{}: {bounds_display}", lifetime.print())
330 // FIXME(fmease): Render bound params.
331 clean::WherePredicate::EqPredicate { lhs, rhs, bound_params: _ } => {
333 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
335 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
342 if where_predicates.peek().is_none() {
346 let where_preds = comma_sep(where_predicates, false);
347 let clause = if f.alternate() {
348 if ending == Ending::Newline {
349 format!(" where{where_preds},")
351 format!(" where{where_preds}")
354 let mut br_with_padding = String::with_capacity(6 * indent + 28);
355 br_with_padding.push_str("<br>");
356 for _ in 0..indent + 4 {
357 br_with_padding.push_str(" ");
359 let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
361 if ending == Ending::Newline {
362 let mut clause = " ".repeat(indent.saturating_sub(1));
363 write!(clause, "<span class=\"where fmt-newline\">where{where_preds},</span>")?;
366 // insert a <br> tag after a single space but before multiple spaces at the start
368 format!("<br><span class=\"where\">where{where_preds}</span>")
370 let mut clause = br_with_padding;
371 clause.truncate(clause.len() - 4 * " ".len());
372 write!(clause, "<span class=\"where\">where{where_preds}</span>")?;
377 write!(f, "{clause}")
381 impl clean::Lifetime {
382 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
387 impl clean::Constant {
388 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
389 let expr = self.expr(tcx);
392 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
398 impl clean::PolyTrait {
399 fn print<'a, 'tcx: 'a>(
401 cx: &'a Context<'tcx>,
402 ) -> impl fmt::Display + 'a + Captures<'tcx> {
403 display_fn(move |f| {
404 if !self.generic_params.is_empty() {
409 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
415 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
420 write!(f, "{:#}", self.trait_.print(cx))
422 write!(f, "{}", self.trait_.print(cx))
428 impl clean::GenericBound {
429 pub(crate) fn print<'a, 'tcx: 'a>(
431 cx: &'a Context<'tcx>,
432 ) -> impl fmt::Display + 'a + Captures<'tcx> {
433 display_fn(move |f| match self {
434 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
435 clean::GenericBound::TraitBound(ty, modifier) => {
436 let modifier_str = match modifier {
437 hir::TraitBoundModifier::None => "",
438 hir::TraitBoundModifier::Maybe => "?",
439 // ~const is experimental; do not display those bounds in rustdoc
440 hir::TraitBoundModifier::MaybeConst => "",
443 write!(f, "{}{:#}", modifier_str, ty.print(cx))
445 write!(f, "{}{}", modifier_str, ty.print(cx))
452 impl clean::GenericArgs {
453 fn print<'a, 'tcx: 'a>(
455 cx: &'a Context<'tcx>,
456 ) -> impl fmt::Display + 'a + Captures<'tcx> {
457 display_fn(move |f| {
459 clean::GenericArgs::AngleBracketed { args, bindings } => {
460 if !args.is_empty() || !bindings.is_empty() {
464 f.write_str("<")?;
466 let mut comma = false;
467 for arg in args.iter() {
473 write!(f, "{:#}", arg.print(cx))?;
475 write!(f, "{}", arg.print(cx))?;
478 for binding in bindings.iter() {
484 write!(f, "{:#}", binding.print(cx))?;
486 write!(f, "{}", binding.print(cx))?;
492 f.write_str(">")?;
496 clean::GenericArgs::Parenthesized { inputs, output } => {
498 let mut comma = false;
499 for ty in inputs.iter() {
505 write!(f, "{:#}", ty.print(cx))?;
507 write!(f, "{}", ty.print(cx))?;
511 if let Some(ref ty) = *output {
513 write!(f, " -> {:#}", ty.print(cx))?;
515 write!(f, " -> {}", ty.print(cx))?;
525 // Possible errors when computing href link source for a `DefId`
526 #[derive(PartialEq, Eq)]
527 pub(crate) enum HrefError {
528 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
530 /// This can only happen for non-local items.
534 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
535 /// implements it for a local type.
536 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
539 /// rustc a.rs --crate-type=lib
540 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
543 /// Now, the associated items in the trait impl want to link to the corresponding item in the
544 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
545 /// *documentation (was) not built*.
546 DocumentationNotBuilt,
547 /// This can only happen for non-local items when `--document-private-items` is not passed.
549 // Not in external cache, href link should be in same page
553 // Panics if `syms` is empty.
554 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
555 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
556 s.push_str(syms[0].as_str());
557 for sym in &syms[1..] {
559 s.push_str(sym.as_str());
564 /// This function is to get the external macro path because they are not in the cache used in
565 /// `href_with_root_path`.
566 fn generate_macro_def_id_path(
569 root_path: Option<&str>,
570 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
571 let tcx = cx.shared.tcx;
572 let crate_name = tcx.crate_name(def_id.krate).to_string();
573 let cache = cx.cache();
575 let fqp: Vec<Symbol> = tcx
580 // extern blocks (and a few others things) have an empty name.
581 match elem.data.get_opt_name() {
582 Some(s) if !s.is_empty() => Some(s),
587 let mut relative = fqp.iter().map(|elem| elem.to_string());
588 let cstore = CStore::from_tcx(tcx);
589 // We need this to prevent a `panic` when this function is used from intra doc links...
590 if !cstore.has_crate_data(def_id.krate) {
591 debug!("No data for crate {}", crate_name);
592 return Err(HrefError::NotInExternalCache);
594 // Check to see if it is a macro 2.0 or built-in macro.
595 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
596 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
597 LoadedMacro::MacroDef(def, _) => {
598 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
599 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
604 let mut path = if is_macro_2 {
605 once(crate_name.clone()).chain(relative).collect()
607 vec![crate_name.clone(), relative.next_back().unwrap()]
610 // The minimum we can have is the crate name followed by the macro name. If shorter, then
611 // it means that `relative` was empty, which is an error.
612 debug!("macro path cannot be empty!");
613 return Err(HrefError::NotInExternalCache);
616 if let Some(last) = path.last_mut() {
617 *last = format!("macro.{}.html", last);
620 let url = match cache.extern_locations[&def_id.krate] {
621 ExternalLocation::Remote(ref s) => {
622 // `ExternalLocation::Remote` always end with a `/`.
623 format!("{}{}", s, path.join("/"))
625 ExternalLocation::Local => {
626 // `root_path` always end with a `/`.
627 format!("{}{}/{}", root_path.unwrap_or(""), crate_name, path.join("/"))
629 ExternalLocation::Unknown => {
630 debug!("crate {} not in cache when linkifying macros", crate_name);
631 return Err(HrefError::NotInExternalCache);
634 Ok((url, ItemType::Macro, fqp))
637 pub(crate) fn href_with_root_path(
640 root_path: Option<&str>,
641 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
643 let def_kind = tcx.def_kind(did);
644 let did = match def_kind {
645 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
646 // documented on their parent's page
651 let cache = cx.cache();
652 let relative_to = &cx.current;
653 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
654 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
658 && !cache.effective_visibilities.is_directly_public(tcx, did)
659 && !cache.document_private
660 && !cache.primitive_locations.values().any(|&id| id == did)
662 return Err(HrefError::Private);
665 let mut is_remote = false;
666 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
667 Some(&(ref fqp, shortty)) => (fqp, shortty, {
668 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
669 debug!(?fqp, ?shortty, ?module_fqp);
670 href_relative_parts(module_fqp, relative_to).collect()
673 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
674 let module_fqp = to_module_fqp(shortty, fqp);
678 match cache.extern_locations[&did.krate] {
679 ExternalLocation::Remote(ref s) => {
681 let s = s.trim_end_matches('/');
682 let mut builder = UrlPartsBuilder::singleton(s);
683 builder.extend(module_fqp.iter().copied());
686 ExternalLocation::Local => {
687 href_relative_parts(module_fqp, relative_to).collect()
689 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
692 } else if matches!(def_kind, DefKind::Macro(_)) {
693 return generate_macro_def_id_path(did, cx, root_path);
695 return Err(HrefError::NotInExternalCache);
700 if let Some(root_path) = root_path {
701 let root = root_path.trim_end_matches('/');
702 url_parts.push_front(root);
707 ItemType::Module => {
708 url_parts.push("index.html");
711 let prefix = shortty.as_str();
712 let last = fqp.last().unwrap();
713 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
716 Ok((url_parts.finish(), shortty, fqp.to_vec()))
722 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
723 href_with_root_path(did, cx, None)
726 /// Both paths should only be modules.
727 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
728 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
729 pub(crate) fn href_relative_parts<'fqp>(
731 relative_to_fqp: &[Symbol],
732 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
733 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
734 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
736 let dissimilar_part_count = relative_to_fqp.len() - i;
737 let fqp_module = &fqp[i..fqp.len()];
739 iter::repeat(sym::dotdot)
740 .take(dissimilar_part_count)
741 .chain(fqp_module.iter().copied()),
745 // e.g. linking to std::sync::atomic from std::sync
746 if relative_to_fqp.len() < fqp.len() {
747 Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
748 // e.g. linking to std::sync from std::sync::atomic
749 } else if fqp.len() < relative_to_fqp.len() {
750 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
751 Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
752 // linking to the same module
754 Box::new(iter::empty())
758 /// Used to render a [`clean::Path`].
759 fn resolved_path<'cx>(
760 w: &mut fmt::Formatter<'_>,
765 cx: &'cx Context<'_>,
767 let last = path.segments.last().unwrap();
770 for seg in &path.segments[..path.segments.len() - 1] {
771 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
775 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
777 let path = if use_absolute {
778 if let Ok((_, _, fqp)) = href(did, cx) {
781 join_with_double_colon(&fqp[..fqp.len() - 1]),
782 anchor(did, *fqp.last().unwrap(), cx)
785 last.name.to_string()
788 anchor(did, last.name, cx).to_string()
790 write!(w, "{}{}", path, last.args.print(cx))?;
796 f: &mut fmt::Formatter<'_>,
797 prim: clean::PrimitiveType,
801 primitive_link_fragment(f, prim, name, "", cx)
804 fn primitive_link_fragment(
805 f: &mut fmt::Formatter<'_>,
806 prim: clean::PrimitiveType,
812 let mut needs_termination = false;
814 match m.primitive_locations.get(&prim) {
815 Some(&def_id) if def_id.is_local() => {
816 let len = cx.current.len();
817 let len = if len == 0 { 0 } else { len - 1 };
820 "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
824 needs_termination = true;
827 let loc = match m.extern_locations[&def_id.krate] {
828 ExternalLocation::Remote(ref s) => {
829 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
830 let builder: UrlPartsBuilder =
831 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
836 ExternalLocation::Local => {
837 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
838 Some(if cx.current.first() == Some(&cname_sym) {
839 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
841 iter::repeat(sym::dotdot)
842 .take(cx.current.len())
843 .chain(iter::once(cname_sym))
847 ExternalLocation::Unknown => None,
849 if let Some(mut loc) = loc {
850 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
851 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
852 needs_termination = true;
858 write!(f, "{}", name)?;
859 if needs_termination {
865 /// Helper to render type parameters
866 fn tybounds<'a, 'tcx: 'a>(
867 bounds: &'a [clean::PolyTrait],
868 lt: &'a Option<clean::Lifetime>,
869 cx: &'a Context<'tcx>,
870 ) -> impl fmt::Display + 'a + Captures<'tcx> {
871 display_fn(move |f| {
872 for (i, bound) in bounds.iter().enumerate() {
877 fmt::Display::fmt(&bound.print(cx), f)?;
880 if let Some(lt) = lt {
882 fmt::Display::fmt(<.print(), f)?;
888 pub(crate) fn anchor<'a, 'cx: 'a>(
891 cx: &'cx Context<'_>,
892 ) -> impl fmt::Display + 'a {
893 let parts = href(did, cx);
894 display_fn(move |f| {
895 if let Ok((url, short_ty, fqp)) = parts {
898 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
902 join_with_double_colon(&fqp),
906 write!(f, "{}", text)
913 f: &mut fmt::Formatter<'_>,
915 cx: &'cx Context<'_>,
917 trace!("fmt_type(t = {:?})", t);
920 clean::Generic(name) => write!(f, "{}", name),
921 clean::Type::Path { ref path } => {
922 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
923 let did = path.def_id();
924 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
926 clean::DynTrait(ref bounds, ref lt) => {
927 f.write_str("dyn ")?;
928 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
930 clean::Infer => write!(f, "_"),
931 clean::Primitive(clean::PrimitiveType::Never) => {
932 primitive_link(f, PrimitiveType::Never, "!", cx)
934 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
935 clean::BareFunction(ref decl) => {
940 decl.print_hrtb_with_space(cx),
941 decl.unsafety.print_with_space(),
942 print_abi_with_space(decl.abi),
949 decl.print_hrtb_with_space(cx),
950 decl.unsafety.print_with_space(),
951 print_abi_with_space(decl.abi)
953 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
954 write!(f, "{}", decl.decl.print(cx))
957 clean::Tuple(ref typs) => {
959 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
961 if let clean::Generic(name) = one {
962 primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
965 // Carry `f.alternate()` into this display w/o branching manually.
966 fmt::Display::fmt(&one.print(cx), f)?;
971 let generic_names: Vec<Symbol> = many
973 .filter_map(|t| match t {
974 clean::Generic(name) => Some(*name),
978 let is_generic = generic_names.len() == many.len();
982 PrimitiveType::Tuple,
983 &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
988 for (i, item) in many.iter().enumerate() {
992 // Carry `f.alternate()` into this display w/o branching manually.
993 fmt::Display::fmt(&item.print(cx), f)?;
1000 clean::Slice(ref t) => match **t {
1001 clean::Generic(name) => {
1002 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1006 fmt::Display::fmt(&t.print(cx), f)?;
1010 clean::Array(ref t, ref n) => match **t {
1011 clean::Generic(name) if !f.alternate() => primitive_link(
1013 PrimitiveType::Array,
1014 &format!("[{name}; {n}]", n = Escape(n)),
1019 fmt::Display::fmt(&t.print(cx), f)?;
1021 write!(f, "; {n}")?;
1024 primitive_link(f, PrimitiveType::Array, &format!("{n}", n = Escape(n)), cx)?;
1029 clean::RawPointer(m, ref t) => {
1031 hir::Mutability::Mut => "mut",
1032 hir::Mutability::Not => "const",
1035 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1036 let text = if f.alternate() {
1037 format!("*{} {:#}", m, t.print(cx))
1039 format!("*{} {}", m, t.print(cx))
1041 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1043 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1044 fmt::Display::fmt(&t.print(cx), f)
1047 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1049 Some(l) => format!("{} ", l.print()),
1052 let m = mutability.print_with_space();
1053 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
1055 clean::DynTrait(ref bounds, ref trait_lt)
1056 if bounds.len() > 1 || trait_lt.is_some() =>
1058 write!(f, "{}{}{}(", amp, lt, m)?;
1059 fmt_type(ty, f, use_absolute, cx)?;
1062 clean::Generic(..) => {
1065 PrimitiveType::Reference,
1066 &format!("{}{}{}", amp, lt, m),
1069 fmt_type(ty, f, use_absolute, cx)
1072 write!(f, "{}{}{}", amp, lt, m)?;
1073 fmt_type(ty, f, use_absolute, cx)
1077 clean::ImplTrait(ref bounds) => {
1079 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1081 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1084 clean::QPath(box clean::QPathData {
1091 if should_show_cast {
1092 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1094 write!(f, "{:#}::", self_type.print(cx))?
1097 if should_show_cast {
1098 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
1100 write!(f, "{}::", self_type.print(cx))?
1103 // It's pretty unsightly to look at `<A as B>::C` in output, and
1104 // we've got hyperlinking on our side, so try to avoid longer
1105 // notation as much as possible by making `C` a hyperlink to trait
1106 // `B` to disambiguate.
1108 // FIXME: this is still a lossy conversion and there should probably
1109 // be a better way of representing this in general? Most of
1110 // the ugliness comes from inlining across crates where
1111 // everything comes in as a fully resolved QPath (hard to
1113 match href(trait_.def_id(), cx) {
1114 Ok((ref url, _, ref path)) if !f.alternate() => {
1117 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1118 title=\"type {path}::{name}\">{name}</a>{args}",
1120 shortty = ItemType::AssocType,
1122 path = join_with_double_colon(path),
1123 args = assoc.args.print(cx),
1126 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1134 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1136 cx: &'a Context<'tcx>,
1137 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1138 display_fn(move |f| fmt_type(self, f, false, cx))
1143 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1145 cx: &'a Context<'tcx>,
1146 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1147 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1152 pub(crate) fn print<'a, 'tcx: 'a>(
1155 cx: &'a Context<'tcx>,
1156 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1157 display_fn(move |f| {
1159 write!(f, "impl{:#} ", self.generics.print(cx))?;
1161 write!(f, "impl{} ", self.generics.print(cx))?;
1164 if let Some(ref ty) = self.trait_ {
1165 match self.polarity {
1166 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1167 ty::ImplPolarity::Negative => write!(f, "!")?,
1169 fmt::Display::fmt(&ty.print(cx), f)?;
1170 write!(f, " for ")?;
1173 if let clean::Type::Tuple(types) = &self.for_ &&
1174 let [clean::Type::Generic(name)] = &types[..] &&
1175 (self.kind.is_fake_variadic() || self.kind.is_auto())
1177 // Hardcoded anchor library/core/src/primitive_docs.rs
1178 // Link should match `# Trait implementations`
1179 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1180 } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1181 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
1182 (self.kind.is_fake_variadic() || self.kind.is_auto())
1184 // Hardcoded anchor library/core/src/primitive_docs.rs
1185 // Link should match `# Trait implementations`
1187 let hrtb = bare_fn.print_hrtb_with_space(cx);
1188 let unsafety = bare_fn.unsafety.print_with_space();
1189 let abi = print_abi_with_space(bare_fn.abi);
1193 "{hrtb:#}{unsafety}{abi:#}",
1198 "{hrtb}{unsafety}{abi}",
1201 let ellipsis = if bare_fn.decl.c_variadic {
1206 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1208 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1210 fmt_type(ty, f, use_absolute, cx)?;
1212 } else if let Some(ty) = self.kind.as_blanket_ty() {
1213 fmt_type(ty, f, use_absolute, cx)?;
1215 fmt_type(&self.for_, f, use_absolute, cx)?;
1218 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1224 impl clean::Arguments {
1225 pub(crate) fn print<'a, 'tcx: 'a>(
1227 cx: &'a Context<'tcx>,
1228 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1229 display_fn(move |f| {
1230 for (i, input) in self.values.iter().enumerate() {
1231 write!(f, "{}: ", input.name)?;
1234 write!(f, "{:#}", input.type_.print(cx))?;
1236 write!(f, "{}", input.type_.print(cx))?;
1238 if i + 1 < self.values.len() {
1247 impl clean::FnRetTy {
1248 pub(crate) fn print<'a, 'tcx: 'a>(
1250 cx: &'a Context<'tcx>,
1251 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1252 display_fn(move |f| match self {
1253 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1254 clean::Return(ty) if f.alternate() => {
1255 write!(f, " -> {:#}", ty.print(cx))
1257 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1258 clean::DefaultReturn => Ok(()),
1263 impl clean::BareFunctionDecl {
1264 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1266 cx: &'a Context<'tcx>,
1267 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1268 display_fn(move |f| {
1269 if !self.generic_params.is_empty() {
1273 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1282 impl clean::FnDecl {
1283 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1285 cx: &'a Context<'tcx>,
1286 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1287 display_fn(move |f| {
1288 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1292 "({args:#}{ellipsis}){arrow:#}",
1293 args = self.inputs.print(cx),
1294 ellipsis = ellipsis,
1295 arrow = self.output.print(cx)
1300 "({args}{ellipsis}){arrow}",
1301 args = self.inputs.print(cx),
1302 ellipsis = ellipsis,
1303 arrow = self.output.print(cx)
1309 /// * `header_len`: The length of the function header and name. In other words, the number of
1310 /// characters in the function declaration up to but not including the parentheses.
1311 /// <br>Used to determine line-wrapping.
1312 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1314 pub(crate) fn full_print<'a, 'tcx: 'a>(
1318 cx: &'a Context<'tcx>,
1319 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1320 display_fn(move |f| self.inner_full_print(header_len, indent, f, cx))
1323 fn inner_full_print(
1327 f: &mut fmt::Formatter<'_>,
1330 let amp = if f.alternate() { "&" } else { "&" };
1331 let mut args = Buffer::html();
1332 let mut args_plain = Buffer::new();
1333 for (i, input) in self.inputs.values.iter().enumerate() {
1334 if let Some(selfty) = input.to_self() {
1336 clean::SelfValue => {
1337 args.push_str("self");
1338 args_plain.push_str("self");
1340 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1341 write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1342 write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1344 clean::SelfBorrowed(None, mtbl) => {
1345 write!(args, "{}{}self", amp, mtbl.print_with_space());
1346 write!(args_plain, "&{}self", mtbl.print_with_space());
1348 clean::SelfExplicit(ref typ) => {
1350 write!(args, "self: {:#}", typ.print(cx));
1352 write!(args, "self: {}", typ.print(cx));
1354 write!(args_plain, "self: {:#}", typ.print(cx));
1359 args.push_str("<br>");
1362 args.push_str("const ");
1363 args_plain.push_str("const ");
1365 write!(args, "{}: ", input.name);
1366 write!(args_plain, "{}: ", input.name);
1369 write!(args, "{:#}", input.type_.print(cx));
1371 write!(args, "{}", input.type_.print(cx));
1373 write!(args_plain, "{:#}", input.type_.print(cx));
1375 if i + 1 < self.inputs.values.len() {
1377 args_plain.push_str(",");
1381 let mut args_plain = format!("({})", args_plain.into_inner());
1382 let mut args = args.into_inner();
1384 if self.c_variadic {
1385 args.push_str(",<br> ...");
1386 args_plain.push_str(", ...");
1389 let arrow_plain = format!("{:#}", self.output.print(cx));
1391 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) };
1393 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1394 let output = if declaration_len > 80 {
1395 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1396 let close_pad = format!("<br>{}", " ".repeat(indent));
1398 "({pad}{args}{close}){arrow}",
1399 pad = if self.inputs.values.is_empty() { "" } else { &full_pad },
1400 args = args.replace("<br>", &full_pad),
1405 format!("({args}){arrow}", args = args.replace("<br>", " "), arrow = arrow)
1409 write!(f, "{}", output.replace("<br>", "\n"))
1411 write!(f, "{}", output)
1416 pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
1417 visibility: Option<ty::Visibility<DefId>>,
1419 cx: &'a Context<'tcx>,
1420 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1421 use std::fmt::Write as _;
1423 let to_print: Cow<'static, str> = match visibility {
1425 Some(ty::Visibility::Public) => "pub ".into(),
1426 Some(ty::Visibility::Restricted(vis_did)) => {
1427 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1428 // However, rustdoc currently never displays a module's
1429 // visibility, so it shouldn't matter.
1430 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1432 if vis_did.is_crate_root() {
1433 "pub(crate) ".into()
1434 } else if parent_module == Some(vis_did) {
1435 // `pub(in foo)` where `foo` is the parent module
1436 // is the same as no visibility modifier
1438 } else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1441 "pub(super) ".into()
1443 let path = cx.tcx().def_path(vis_did);
1444 debug!("path={:?}", path);
1445 // modified from `resolved_path()` to work with `DefPathData`
1446 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1447 let anchor = anchor(vis_did, last_name, cx).to_string();
1449 let mut s = "pub(in ".to_owned();
1450 for seg in &path.data[..path.data.len() - 1] {
1451 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1453 let _ = write!(s, "{}) ", anchor);
1458 display_fn(move |f| write!(f, "{}", to_print))
1461 /// This function is the same as print_with_space, except that it renders no links.
1462 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1464 pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
1465 visibility: Option<ty::Visibility<DefId>>,
1468 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1469 let to_print = match visibility {
1470 None => String::new(),
1471 Some(ty::Visibility::Public) => "pub ".to_owned(),
1472 Some(ty::Visibility::Restricted(vis_did)) => {
1473 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1474 // However, rustdoc currently never displays a module's
1475 // visibility, so it shouldn't matter.
1476 let parent_module = find_nearest_parent_module(tcx, item_did);
1478 if vis_did.is_crate_root() {
1479 "pub(crate) ".to_owned()
1480 } else if parent_module == Some(vis_did) {
1481 // `pub(in foo)` where `foo` is the parent module
1482 // is the same as no visibility modifier
1484 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1487 "pub(super) ".to_owned()
1489 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1493 display_fn(move |f| f.write_str(&to_print))
1496 pub(crate) trait PrintWithSpace {
1497 fn print_with_space(&self) -> &str;
1500 impl PrintWithSpace for hir::Unsafety {
1501 fn print_with_space(&self) -> &str {
1503 hir::Unsafety::Unsafe => "unsafe ",
1504 hir::Unsafety::Normal => "",
1509 impl PrintWithSpace for hir::IsAsync {
1510 fn print_with_space(&self) -> &str {
1512 hir::IsAsync::Async => "async ",
1513 hir::IsAsync::NotAsync => "",
1518 impl PrintWithSpace for hir::Mutability {
1519 fn print_with_space(&self) -> &str {
1521 hir::Mutability::Not => "",
1522 hir::Mutability::Mut => "mut ",
1527 pub(crate) fn print_constness_with_space(
1529 s: Option<ConstStability>,
1532 // const stable or when feature(staged_api) is not set
1534 hir::Constness::Const,
1535 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1537 | (hir::Constness::Const, None) => "const ",
1538 // const unstable or not const
1543 impl clean::Import {
1544 pub(crate) fn print<'a, 'tcx: 'a>(
1546 cx: &'a Context<'tcx>,
1547 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1548 display_fn(move |f| match self.kind {
1549 clean::ImportKind::Simple(name) => {
1550 if name == self.source.path.last() {
1551 write!(f, "use {};", self.source.print(cx))
1553 write!(f, "use {} as {};", self.source.print(cx), name)
1556 clean::ImportKind::Glob => {
1557 if self.source.path.segments.is_empty() {
1560 write!(f, "use {}::*;", self.source.print(cx))
1567 impl clean::ImportSource {
1568 pub(crate) fn print<'a, 'tcx: 'a>(
1570 cx: &'a Context<'tcx>,
1571 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1572 display_fn(move |f| match self.did {
1573 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1575 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1576 write!(f, "{}::", seg.name)?;
1578 let name = self.path.last();
1579 if let hir::def::Res::PrimTy(p) = self.path.res {
1580 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1582 write!(f, "{}", name)?;
1590 impl clean::TypeBinding {
1591 pub(crate) fn print<'a, 'tcx: 'a>(
1593 cx: &'a Context<'tcx>,
1594 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1595 display_fn(move |f| {
1596 f.write_str(self.assoc.name.as_str())?;
1598 write!(f, "{:#}", self.assoc.args.print(cx))?;
1600 write!(f, "{}", self.assoc.args.print(cx))?;
1603 clean::TypeBindingKind::Equality { ref term } => {
1605 write!(f, " = {:#}", term.print(cx))?;
1607 write!(f, " = {}", term.print(cx))?;
1610 clean::TypeBindingKind::Constraint { ref bounds } => {
1611 if !bounds.is_empty() {
1613 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1615 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1625 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1626 display_fn(move |f| {
1627 let quot = if f.alternate() { "\"" } else { """ };
1629 Abi::Rust => Ok(()),
1630 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1635 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1636 if v { "default " } else { "" }
1639 impl clean::GenericArg {
1640 pub(crate) fn print<'a, 'tcx: 'a>(
1642 cx: &'a Context<'tcx>,
1643 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1644 display_fn(move |f| match self {
1645 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1646 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1647 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1648 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1653 impl clean::types::Term {
1654 pub(crate) fn print<'a, 'tcx: 'a>(
1656 cx: &'a Context<'tcx>,
1657 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1658 display_fn(move |f| match self {
1659 clean::types::Term::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1660 clean::types::Term::Constant(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1665 pub(crate) fn display_fn(
1666 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1667 ) -> impl fmt::Display {
1668 struct WithFormatter<F>(Cell<Option<F>>);
1670 impl<F> fmt::Display for WithFormatter<F>
1672 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1675 (self.0.take()).unwrap()(f)
1679 WithFormatter(Cell::new(Some(f)))