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 insert_str(&mut self, idx: usize, s: &str) {
111 self.buffer.insert_str(idx, s);
114 pub(crate) fn push_str(&mut self, s: &str) {
115 self.buffer.push_str(s);
118 pub(crate) fn push_buffer(&mut self, other: Buffer) {
119 self.buffer.push_str(&other.buffer);
122 // Intended for consumption by write! and writeln! (std::fmt) but without
123 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
125 pub(crate) fn write_str(&mut self, s: &str) {
126 self.buffer.push_str(s);
129 // Intended for consumption by write! and writeln! (std::fmt) but without
130 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
132 pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
134 self.buffer.write_fmt(v).unwrap();
137 pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
142 pub(crate) fn is_for_html(&self) -> bool {
146 pub(crate) fn reserve(&mut self, additional: usize) {
147 self.buffer.reserve(additional)
151 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 /// * The Generics from which to emit a where-clause.
268 /// * The number of spaces to indent each line with.
269 /// * Whether the where-clause needs to add a comma and newline after the last bound.
270 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
271 gens: &'a clean::Generics,
272 cx: &'a Context<'tcx>,
275 ) -> impl fmt::Display + 'a + Captures<'tcx> {
278 display_fn(move |f| {
279 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
280 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
282 display_fn(move |f| {
286 f.write_str("<br>")?;
290 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
291 let ty_cx = ty.print(cx);
292 let generic_bounds = print_generic_bounds(bounds, cx);
294 if bound_params.is_empty() {
296 write!(f, "{ty_cx:#}: {generic_bounds:#}")
298 write!(f, "{ty_cx}: {generic_bounds}")
304 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
305 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
310 "for<{}> {ty_cx}: {generic_bounds}",
311 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
316 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
317 let mut bounds_display = String::new();
318 for bound in bounds.iter().map(|b| b.print(cx)) {
319 write!(bounds_display, "{bound} + ")?;
321 bounds_display.truncate(bounds_display.len() - " + ".len());
322 write!(f, "{}: {bounds_display}", lifetime.print())
324 clean::WherePredicate::EqPredicate { lhs, rhs } => {
326 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
328 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
335 if where_predicates.peek().is_none() {
339 let where_preds = comma_sep(where_predicates, false);
340 let clause = if f.alternate() {
342 // add a space so stripping <br> tags and breaking spaces still renders properly
343 format!(" where{where_preds}, ")
345 format!(" where{where_preds}")
348 let mut br_with_padding = String::with_capacity(6 * indent + 28);
349 br_with_padding.push_str("<br>");
350 for _ in 0..indent + 4 {
351 br_with_padding.push_str(" ");
353 let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
356 let mut clause = " ".repeat(indent.saturating_sub(1));
357 // add a space so stripping <br> tags and breaking spaces still renders properly
360 " <span class=\"where fmt-newline\">where{where_preds}, </span>"
364 // insert a <br> tag after a single space but before multiple spaces at the start
366 format!(" <br><span class=\"where\">where{where_preds}</span>")
368 let mut clause = br_with_padding;
369 clause.truncate(clause.len() - 5 * " ".len());
370 write!(clause, " <span class=\"where\">where{where_preds}</span>")?;
375 write!(f, "{clause}")
379 impl clean::Lifetime {
380 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
385 impl clean::Constant {
386 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
387 let expr = self.expr(tcx);
390 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
396 impl clean::PolyTrait {
397 fn print<'a, 'tcx: 'a>(
399 cx: &'a Context<'tcx>,
400 ) -> impl fmt::Display + 'a + Captures<'tcx> {
401 display_fn(move |f| {
402 if !self.generic_params.is_empty() {
407 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
413 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
418 write!(f, "{:#}", self.trait_.print(cx))
420 write!(f, "{}", self.trait_.print(cx))
426 impl clean::GenericBound {
427 pub(crate) fn print<'a, 'tcx: 'a>(
429 cx: &'a Context<'tcx>,
430 ) -> impl fmt::Display + 'a + Captures<'tcx> {
431 display_fn(move |f| match self {
432 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
433 clean::GenericBound::TraitBound(ty, modifier) => {
434 let modifier_str = match modifier {
435 hir::TraitBoundModifier::None => "",
436 hir::TraitBoundModifier::Maybe => "?",
437 // ~const is experimental; do not display those bounds in rustdoc
438 hir::TraitBoundModifier::MaybeConst => "",
441 write!(f, "{}{:#}", modifier_str, ty.print(cx))
443 write!(f, "{}{}", modifier_str, ty.print(cx))
450 impl clean::GenericArgs {
451 fn print<'a, 'tcx: 'a>(
453 cx: &'a Context<'tcx>,
454 ) -> impl fmt::Display + 'a + Captures<'tcx> {
455 display_fn(move |f| {
457 clean::GenericArgs::AngleBracketed { args, bindings } => {
458 if !args.is_empty() || !bindings.is_empty() {
462 f.write_str("<")?;
464 let mut comma = false;
465 for arg in args.iter() {
471 write!(f, "{:#}", arg.print(cx))?;
473 write!(f, "{}", arg.print(cx))?;
476 for binding in bindings.iter() {
482 write!(f, "{:#}", binding.print(cx))?;
484 write!(f, "{}", binding.print(cx))?;
490 f.write_str(">")?;
494 clean::GenericArgs::Parenthesized { inputs, output } => {
496 let mut comma = false;
497 for ty in inputs.iter() {
503 write!(f, "{:#}", ty.print(cx))?;
505 write!(f, "{}", ty.print(cx))?;
509 if let Some(ref ty) = *output {
511 write!(f, " -> {:#}", ty.print(cx))?;
513 write!(f, " -> {}", ty.print(cx))?;
523 // Possible errors when computing href link source for a `DefId`
524 #[derive(PartialEq, Eq)]
525 pub(crate) enum HrefError {
526 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
528 /// This can only happen for non-local items.
532 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
533 /// implements it for a local type.
534 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
537 /// rustc a.rs --crate-type=lib
538 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
541 /// Now, the associated items in the trait impl want to link to the corresponding item in the
542 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
543 /// *documentation (was) not built*.
544 DocumentationNotBuilt,
545 /// This can only happen for non-local items when `--document-private-items` is not passed.
547 // Not in external cache, href link should be in same page
551 // Panics if `syms` is empty.
552 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
553 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
554 s.push_str(syms[0].as_str());
555 for sym in &syms[1..] {
557 s.push_str(sym.as_str());
562 /// This function is to get the external macro path because they are not in the cache used in
563 /// `href_with_root_path`.
564 fn generate_macro_def_id_path(
567 root_path: Option<&str>,
568 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
569 let tcx = cx.shared.tcx;
570 let crate_name = tcx.crate_name(def_id.krate).to_string();
571 let cache = cx.cache();
573 let fqp: Vec<Symbol> = tcx
578 // extern blocks (and a few others things) have an empty name.
579 match elem.data.get_opt_name() {
580 Some(s) if !s.is_empty() => Some(s),
585 let relative = fqp.iter().map(|elem| elem.to_string());
586 let cstore = CStore::from_tcx(tcx);
587 // We need this to prevent a `panic` when this function is used from intra doc links...
588 if !cstore.has_crate_data(def_id.krate) {
589 debug!("No data for crate {}", crate_name);
590 return Err(HrefError::NotInExternalCache);
592 // Check to see if it is a macro 2.0 or built-in macro.
593 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
594 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
595 LoadedMacro::MacroDef(def, _) => {
596 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
597 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
602 let mut path = if is_macro_2 {
603 once(crate_name.clone()).chain(relative).collect()
605 vec![crate_name.clone(), relative.last().unwrap()]
608 // The minimum we can have is the crate name followed by the macro name. If shorter, then
609 // it means that that `relative` was empty, which is an error.
610 debug!("macro path cannot be empty!");
611 return Err(HrefError::NotInExternalCache);
614 if let Some(last) = path.last_mut() {
615 *last = format!("macro.{}.html", last);
618 let url = match cache.extern_locations[&def_id.krate] {
619 ExternalLocation::Remote(ref s) => {
620 // `ExternalLocation::Remote` always end with a `/`.
621 format!("{}{}", s, path.join("/"))
623 ExternalLocation::Local => {
624 // `root_path` always end with a `/`.
625 format!("{}{}/{}", root_path.unwrap_or(""), crate_name, path.join("/"))
627 ExternalLocation::Unknown => {
628 debug!("crate {} not in cache when linkifying macros", crate_name);
629 return Err(HrefError::NotInExternalCache);
632 Ok((url, ItemType::Macro, fqp))
635 pub(crate) fn href_with_root_path(
638 root_path: Option<&str>,
639 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
641 let def_kind = tcx.def_kind(did);
642 let did = match def_kind {
643 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
644 // documented on their parent's page
649 let cache = cx.cache();
650 let relative_to = &cx.current;
651 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
652 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
656 && !cache.access_levels.is_public(did)
657 && !cache.document_private
658 && !cache.primitive_locations.values().any(|&id| id == did)
660 return Err(HrefError::Private);
663 let mut is_remote = false;
664 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
665 Some(&(ref fqp, shortty)) => (fqp, shortty, {
666 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
667 debug!(?fqp, ?shortty, ?module_fqp);
668 href_relative_parts(module_fqp, relative_to).collect()
671 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
672 let module_fqp = to_module_fqp(shortty, fqp);
676 match cache.extern_locations[&did.krate] {
677 ExternalLocation::Remote(ref s) => {
679 let s = s.trim_end_matches('/');
680 let mut builder = UrlPartsBuilder::singleton(s);
681 builder.extend(module_fqp.iter().copied());
684 ExternalLocation::Local => {
685 href_relative_parts(module_fqp, relative_to).collect()
687 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
690 } else if matches!(def_kind, DefKind::Macro(_)) {
691 return generate_macro_def_id_path(did, cx, root_path);
693 return Err(HrefError::NotInExternalCache);
698 if let Some(root_path) = root_path {
699 let root = root_path.trim_end_matches('/');
700 url_parts.push_front(root);
705 ItemType::Module => {
706 url_parts.push("index.html");
709 let prefix = shortty.as_str();
710 let last = fqp.last().unwrap();
711 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
714 Ok((url_parts.finish(), shortty, fqp.to_vec()))
720 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
721 href_with_root_path(did, cx, None)
724 /// Both paths should only be modules.
725 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
726 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
727 pub(crate) fn href_relative_parts<'fqp>(
729 relative_to_fqp: &[Symbol],
730 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
731 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
732 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
734 let dissimilar_part_count = relative_to_fqp.len() - i;
735 let fqp_module = &fqp[i..fqp.len()];
736 return box iter::repeat(sym::dotdot)
737 .take(dissimilar_part_count)
738 .chain(fqp_module.iter().copied());
741 // e.g. linking to std::sync::atomic from std::sync
742 if relative_to_fqp.len() < fqp.len() {
743 box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
744 // e.g. linking to std::sync from std::sync::atomic
745 } else if fqp.len() < relative_to_fqp.len() {
746 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
747 box iter::repeat(sym::dotdot).take(dissimilar_part_count)
748 // linking to the same module
754 /// Used to render a [`clean::Path`].
755 fn resolved_path<'cx>(
756 w: &mut fmt::Formatter<'_>,
761 cx: &'cx Context<'_>,
763 let last = path.segments.last().unwrap();
766 for seg in &path.segments[..path.segments.len() - 1] {
767 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
771 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
773 let path = if use_absolute {
774 if let Ok((_, _, fqp)) = href(did, cx) {
777 join_with_double_colon(&fqp[..fqp.len() - 1]),
778 anchor(did, *fqp.last().unwrap(), cx)
781 last.name.to_string()
784 anchor(did, last.name, cx).to_string()
786 write!(w, "{}{}", path, last.args.print(cx))?;
792 f: &mut fmt::Formatter<'_>,
793 prim: clean::PrimitiveType,
797 primitive_link_fragment(f, prim, name, "", cx)
800 fn primitive_link_fragment(
801 f: &mut fmt::Formatter<'_>,
802 prim: clean::PrimitiveType,
808 let mut needs_termination = false;
810 match m.primitive_locations.get(&prim) {
811 Some(&def_id) if def_id.is_local() => {
812 let len = cx.current.len();
813 let len = if len == 0 { 0 } else { len - 1 };
816 "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
820 needs_termination = true;
823 let loc = match m.extern_locations[&def_id.krate] {
824 ExternalLocation::Remote(ref s) => {
825 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
826 let builder: UrlPartsBuilder =
827 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
832 ExternalLocation::Local => {
833 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
834 Some(if cx.current.first() == Some(&cname_sym) {
835 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
837 iter::repeat(sym::dotdot)
838 .take(cx.current.len())
839 .chain(iter::once(cname_sym))
843 ExternalLocation::Unknown => None,
845 if let Some(mut loc) = loc {
846 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
847 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
848 needs_termination = true;
854 write!(f, "{}", name)?;
855 if needs_termination {
861 /// Helper to render type parameters
862 fn tybounds<'a, 'tcx: 'a>(
863 bounds: &'a [clean::PolyTrait],
864 lt: &'a Option<clean::Lifetime>,
865 cx: &'a Context<'tcx>,
866 ) -> impl fmt::Display + 'a + Captures<'tcx> {
867 display_fn(move |f| {
868 for (i, bound) in bounds.iter().enumerate() {
873 fmt::Display::fmt(&bound.print(cx), f)?;
876 if let Some(lt) = lt {
878 fmt::Display::fmt(<.print(), f)?;
884 pub(crate) fn anchor<'a, 'cx: 'a>(
887 cx: &'cx Context<'_>,
888 ) -> impl fmt::Display + 'a {
889 let parts = href(did, cx);
890 display_fn(move |f| {
891 if let Ok((url, short_ty, fqp)) = parts {
894 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
898 join_with_double_colon(&fqp),
902 write!(f, "{}", text)
909 f: &mut fmt::Formatter<'_>,
911 cx: &'cx Context<'_>,
913 trace!("fmt_type(t = {:?})", t);
916 clean::Generic(name) => write!(f, "{}", name),
917 clean::Type::Path { ref path } => {
918 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
919 let did = path.def_id();
920 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
922 clean::DynTrait(ref bounds, ref lt) => {
923 f.write_str("dyn ")?;
924 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
926 clean::Infer => write!(f, "_"),
927 clean::Primitive(clean::PrimitiveType::Never) => {
928 primitive_link(f, PrimitiveType::Never, "!", cx)
930 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
931 clean::BareFunction(ref decl) => {
936 decl.print_hrtb_with_space(cx),
937 decl.unsafety.print_with_space(),
938 print_abi_with_space(decl.abi),
945 decl.print_hrtb_with_space(cx),
946 decl.unsafety.print_with_space(),
947 print_abi_with_space(decl.abi)
949 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
950 write!(f, "{}", decl.decl.print(cx))
953 clean::Tuple(ref typs) => {
955 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
957 if let clean::Generic(name) = one {
958 primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
961 // Carry `f.alternate()` into this display w/o branching manually.
962 fmt::Display::fmt(&one.print(cx), f)?;
967 let generic_names: Vec<Symbol> = many
969 .filter_map(|t| match t {
970 clean::Generic(name) => Some(*name),
974 let is_generic = generic_names.len() == many.len();
978 PrimitiveType::Tuple,
979 &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
984 for (i, item) in many.iter().enumerate() {
988 // Carry `f.alternate()` into this display w/o branching manually.
989 fmt::Display::fmt(&item.print(cx), f)?;
996 clean::Slice(ref t) => match **t {
997 clean::Generic(name) => {
998 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1002 fmt::Display::fmt(&t.print(cx), f)?;
1006 clean::Array(ref t, ref n) => {
1007 primitive_link(f, PrimitiveType::Array, "[", cx)?;
1008 fmt::Display::fmt(&t.print(cx), f)?;
1010 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
1012 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
1015 clean::RawPointer(m, ref t) => {
1017 hir::Mutability::Mut => "mut",
1018 hir::Mutability::Not => "const",
1021 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1022 let text = if f.alternate() {
1023 format!("*{} {:#}", m, t.print(cx))
1025 format!("*{} {}", m, t.print(cx))
1027 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1029 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1030 fmt::Display::fmt(&t.print(cx), f)
1033 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1035 Some(l) => format!("{} ", l.print()),
1038 let m = mutability.print_with_space();
1039 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
1041 clean::DynTrait(ref bounds, ref trait_lt)
1042 if bounds.len() > 1 || trait_lt.is_some() =>
1044 write!(f, "{}{}{}(", amp, lt, m)?;
1045 fmt_type(ty, f, use_absolute, cx)?;
1048 clean::Generic(..) => {
1051 PrimitiveType::Reference,
1052 &format!("{}{}{}", amp, lt, m),
1055 fmt_type(ty, f, use_absolute, cx)
1058 write!(f, "{}{}{}", amp, lt, m)?;
1059 fmt_type(ty, f, use_absolute, cx)
1063 clean::ImplTrait(ref bounds) => {
1065 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1067 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1070 clean::QPath { ref assoc, ref self_type, ref trait_, should_show_cast } => {
1072 if should_show_cast {
1073 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1075 write!(f, "{:#}::", self_type.print(cx))?
1078 if should_show_cast {
1079 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
1081 write!(f, "{}::", self_type.print(cx))?
1084 // It's pretty unsightly to look at `<A as B>::C` in output, and
1085 // we've got hyperlinking on our side, so try to avoid longer
1086 // notation as much as possible by making `C` a hyperlink to trait
1087 // `B` to disambiguate.
1089 // FIXME: this is still a lossy conversion and there should probably
1090 // be a better way of representing this in general? Most of
1091 // the ugliness comes from inlining across crates where
1092 // everything comes in as a fully resolved QPath (hard to
1094 match href(trait_.def_id(), cx) {
1095 Ok((ref url, _, ref path)) if !f.alternate() => {
1098 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1099 title=\"type {path}::{name}\">{name}</a>{args}",
1101 shortty = ItemType::AssocType,
1103 path = join_with_double_colon(path),
1104 args = assoc.args.print(cx),
1107 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1115 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1117 cx: &'a Context<'tcx>,
1118 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1119 display_fn(move |f| fmt_type(self, f, false, cx))
1124 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1126 cx: &'a Context<'tcx>,
1127 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1128 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1133 pub(crate) fn print<'a, 'tcx: 'a>(
1136 cx: &'a Context<'tcx>,
1137 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1138 display_fn(move |f| {
1140 write!(f, "impl{:#} ", self.generics.print(cx))?;
1142 write!(f, "impl{} ", self.generics.print(cx))?;
1145 if let Some(ref ty) = self.trait_ {
1146 match self.polarity {
1147 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1148 ty::ImplPolarity::Negative => write!(f, "!")?,
1150 fmt::Display::fmt(&ty.print(cx), f)?;
1151 write!(f, " for ")?;
1154 if let clean::Type::Tuple(types) = &self.for_ &&
1155 let [clean::Type::Generic(name)] = &types[..] &&
1156 (self.kind.is_tuple_variadic() || self.kind.is_auto()) {
1157 // Hardcoded anchor library/core/src/primitive_docs.rs
1158 // Link should match `# Trait implementations`
1159 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1160 } else if let Some(ty) = self.kind.as_blanket_ty() {
1161 fmt_type(ty, f, use_absolute, cx)?;
1163 fmt_type(&self.for_, f, use_absolute, cx)?;
1166 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1172 impl clean::Arguments {
1173 pub(crate) fn print<'a, 'tcx: 'a>(
1175 cx: &'a Context<'tcx>,
1176 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1177 display_fn(move |f| {
1178 for (i, input) in self.values.iter().enumerate() {
1179 if !input.name.is_empty() {
1180 write!(f, "{}: ", input.name)?;
1183 write!(f, "{:#}", input.type_.print(cx))?;
1185 write!(f, "{}", input.type_.print(cx))?;
1187 if i + 1 < self.values.len() {
1196 impl clean::FnRetTy {
1197 pub(crate) fn print<'a, 'tcx: 'a>(
1199 cx: &'a Context<'tcx>,
1200 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1201 display_fn(move |f| match self {
1202 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1203 clean::Return(ty) if f.alternate() => {
1204 write!(f, " -> {:#}", ty.print(cx))
1206 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1207 clean::DefaultReturn => Ok(()),
1212 impl clean::BareFunctionDecl {
1213 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1215 cx: &'a Context<'tcx>,
1216 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1217 display_fn(move |f| {
1218 if !self.generic_params.is_empty() {
1222 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1231 impl clean::FnDecl {
1232 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1234 cx: &'a Context<'tcx>,
1235 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1236 display_fn(move |f| {
1237 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1241 "({args:#}{ellipsis}){arrow:#}",
1242 args = self.inputs.print(cx),
1243 ellipsis = ellipsis,
1244 arrow = self.output.print(cx)
1249 "({args}{ellipsis}){arrow}",
1250 args = self.inputs.print(cx),
1251 ellipsis = ellipsis,
1252 arrow = self.output.print(cx)
1258 /// * `header_len`: The length of the function header and name. In other words, the number of
1259 /// characters in the function declaration up to but not including the parentheses.
1260 /// <br>Used to determine line-wrapping.
1261 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1263 /// * `asyncness`: Whether the function is async or not.
1264 pub(crate) fn full_print<'a, 'tcx: 'a>(
1268 asyncness: hir::IsAsync,
1269 cx: &'a Context<'tcx>,
1270 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1271 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1274 fn inner_full_print(
1278 asyncness: hir::IsAsync,
1279 f: &mut fmt::Formatter<'_>,
1282 let amp = if f.alternate() { "&" } else { "&" };
1283 let mut args = Buffer::html();
1284 let mut args_plain = Buffer::new();
1285 for (i, input) in self.inputs.values.iter().enumerate() {
1287 args.push_str("<br>");
1290 if let Some(selfty) = input.to_self() {
1292 clean::SelfValue => {
1293 args.push_str("self");
1294 args_plain.push_str("self");
1296 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1297 write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1298 write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1300 clean::SelfBorrowed(None, mtbl) => {
1301 write!(args, "{}{}self", amp, mtbl.print_with_space());
1302 write!(args_plain, "&{}self", mtbl.print_with_space());
1304 clean::SelfExplicit(ref typ) => {
1306 write!(args, "self: {:#}", typ.print(cx));
1308 write!(args, "self: {}", typ.print(cx));
1310 write!(args_plain, "self: {:#}", typ.print(cx));
1315 args.push_str(" <br>");
1316 args_plain.push_str(" ");
1319 args.push_str("const ");
1320 args_plain.push_str("const ");
1322 if !input.name.is_empty() {
1323 write!(args, "{}: ", input.name);
1324 write!(args_plain, "{}: ", input.name);
1328 write!(args, "{:#}", input.type_.print(cx));
1330 write!(args, "{}", input.type_.print(cx));
1332 write!(args_plain, "{:#}", input.type_.print(cx));
1334 if i + 1 < self.inputs.values.len() {
1336 args_plain.push_str(",");
1340 let mut args_plain = format!("({})", args_plain.into_inner());
1341 let mut args = args.into_inner();
1343 if self.c_variadic {
1344 args.push_str(",<br> ...");
1345 args_plain.push_str(", ...");
1349 let arrow = if let hir::IsAsync::Async = asyncness {
1350 let output = self.sugared_async_return_type();
1351 arrow_plain = format!("{:#}", output.print(cx));
1352 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1354 arrow_plain = format!("{:#}", self.output.print(cx));
1355 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1358 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1359 let output = if declaration_len > 80 {
1360 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1361 let close_pad = format!("<br>{}", " ".repeat(indent));
1363 "({args}{close}){arrow}",
1364 args = args.replace("<br>", &full_pad),
1369 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1373 write!(f, "{}", output.replace("<br>", "\n"))
1375 write!(f, "{}", output)
1380 impl clean::Visibility {
1381 pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1384 cx: &'a Context<'tcx>,
1385 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1386 use std::fmt::Write as _;
1388 let to_print: Cow<'static, str> = match self {
1389 clean::Public => "pub ".into(),
1390 clean::Inherited => "".into(),
1391 clean::Visibility::Restricted(vis_did) => {
1392 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1393 // However, rustdoc currently never displays a module's
1394 // visibility, so it shouldn't matter.
1395 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1397 if vis_did.is_crate_root() {
1398 "pub(crate) ".into()
1399 } else if parent_module == Some(vis_did) {
1400 // `pub(in foo)` where `foo` is the parent module
1401 // is the same as no visibility modifier
1403 } else if parent_module
1404 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1407 "pub(super) ".into()
1409 let path = cx.tcx().def_path(vis_did);
1410 debug!("path={:?}", path);
1411 // modified from `resolved_path()` to work with `DefPathData`
1412 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1413 let anchor = anchor(vis_did, last_name, cx).to_string();
1415 let mut s = "pub(in ".to_owned();
1416 for seg in &path.data[..path.data.len() - 1] {
1417 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1419 let _ = write!(s, "{}) ", anchor);
1424 display_fn(move |f| write!(f, "{}", to_print))
1427 /// This function is the same as print_with_space, except that it renders no links.
1428 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1430 pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1434 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1435 let to_print = match self {
1436 clean::Public => "pub ".to_owned(),
1437 clean::Inherited => String::new(),
1438 clean::Visibility::Restricted(vis_did) => {
1439 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1440 // However, rustdoc currently never displays a module's
1441 // visibility, so it shouldn't matter.
1442 let parent_module = find_nearest_parent_module(tcx, item_did);
1444 if vis_did.is_crate_root() {
1445 "pub(crate) ".to_owned()
1446 } else if parent_module == Some(vis_did) {
1447 // `pub(in foo)` where `foo` is the parent module
1448 // is the same as no visibility modifier
1450 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1453 "pub(super) ".to_owned()
1455 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1459 display_fn(move |f| f.write_str(&to_print))
1463 pub(crate) trait PrintWithSpace {
1464 fn print_with_space(&self) -> &str;
1467 impl PrintWithSpace for hir::Unsafety {
1468 fn print_with_space(&self) -> &str {
1470 hir::Unsafety::Unsafe => "unsafe ",
1471 hir::Unsafety::Normal => "",
1476 impl PrintWithSpace for hir::IsAsync {
1477 fn print_with_space(&self) -> &str {
1479 hir::IsAsync::Async => "async ",
1480 hir::IsAsync::NotAsync => "",
1485 impl PrintWithSpace for hir::Mutability {
1486 fn print_with_space(&self) -> &str {
1488 hir::Mutability::Not => "",
1489 hir::Mutability::Mut => "mut ",
1494 pub(crate) fn print_constness_with_space(
1496 s: Option<ConstStability>,
1499 // const stable or when feature(staged_api) is not set
1501 hir::Constness::Const,
1502 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1504 | (hir::Constness::Const, None) => "const ",
1505 // const unstable or not const
1510 impl clean::Import {
1511 pub(crate) fn print<'a, 'tcx: 'a>(
1513 cx: &'a Context<'tcx>,
1514 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1515 display_fn(move |f| match self.kind {
1516 clean::ImportKind::Simple(name) => {
1517 if name == self.source.path.last() {
1518 write!(f, "use {};", self.source.print(cx))
1520 write!(f, "use {} as {};", self.source.print(cx), name)
1523 clean::ImportKind::Glob => {
1524 if self.source.path.segments.is_empty() {
1527 write!(f, "use {}::*;", self.source.print(cx))
1534 impl clean::ImportSource {
1535 pub(crate) fn print<'a, 'tcx: 'a>(
1537 cx: &'a Context<'tcx>,
1538 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1539 display_fn(move |f| match self.did {
1540 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1542 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1543 write!(f, "{}::", seg.name)?;
1545 let name = self.path.last();
1546 if let hir::def::Res::PrimTy(p) = self.path.res {
1547 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1549 write!(f, "{}", name)?;
1557 impl clean::TypeBinding {
1558 pub(crate) fn print<'a, 'tcx: 'a>(
1560 cx: &'a Context<'tcx>,
1561 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1562 display_fn(move |f| {
1563 f.write_str(self.assoc.name.as_str())?;
1565 write!(f, "{:#}", self.assoc.args.print(cx))?;
1567 write!(f, "{}", self.assoc.args.print(cx))?;
1570 clean::TypeBindingKind::Equality { ref term } => {
1572 write!(f, " = {:#}", term.print(cx))?;
1574 write!(f, " = {}", term.print(cx))?;
1577 clean::TypeBindingKind::Constraint { ref bounds } => {
1578 if !bounds.is_empty() {
1580 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1582 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1592 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1593 display_fn(move |f| {
1594 let quot = if f.alternate() { "\"" } else { """ };
1596 Abi::Rust => Ok(()),
1597 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1602 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1603 if v { "default " } else { "" }
1606 impl clean::GenericArg {
1607 pub(crate) fn print<'a, 'tcx: 'a>(
1609 cx: &'a Context<'tcx>,
1610 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1611 display_fn(move |f| match self {
1612 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1613 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1614 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1615 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1620 impl clean::types::Term {
1621 pub(crate) fn print<'a, 'tcx: 'a>(
1623 cx: &'a Context<'tcx>,
1624 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1626 clean::types::Term::Type(ty) => ty.print(cx),
1632 pub(crate) fn display_fn(
1633 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1634 ) -> impl fmt::Display {
1635 struct WithFormatter<F>(Cell<Option<F>>);
1637 impl<F> fmt::Display for WithFormatter<F>
1639 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1642 (self.0.take()).unwrap()(f)
1646 WithFormatter(Cell::new(Some(f)))