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)
150 pub(crate) fn len(&self) -> usize {
155 fn comma_sep<T: fmt::Display>(
156 items: impl Iterator<Item = T>,
157 space_after_comma: bool,
158 ) -> impl fmt::Display {
159 display_fn(move |f| {
160 for (i, item) in items.enumerate() {
162 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
164 fmt::Display::fmt(&item, f)?;
170 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
171 bounds: &'a [clean::GenericBound],
172 cx: &'a Context<'tcx>,
173 ) -> impl fmt::Display + 'a + Captures<'tcx> {
174 display_fn(move |f| {
175 let mut bounds_dup = FxHashSet::default();
177 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
181 fmt::Display::fmt(&bound.print(cx), f)?;
187 impl clean::GenericParamDef {
188 pub(crate) fn print<'a, 'tcx: 'a>(
190 cx: &'a Context<'tcx>,
191 ) -> impl fmt::Display + 'a + Captures<'tcx> {
192 display_fn(move |f| match &self.kind {
193 clean::GenericParamDefKind::Lifetime { outlives } => {
194 write!(f, "{}", self.name)?;
196 if !outlives.is_empty() {
198 for (i, lt) in outlives.iter().enumerate() {
202 write!(f, "{}", lt.print())?;
208 clean::GenericParamDefKind::Type { bounds, default, .. } => {
209 f.write_str(self.name.as_str())?;
211 if !bounds.is_empty() {
213 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
215 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
219 if let Some(ref ty) = default {
221 write!(f, " = {:#}", ty.print(cx))?;
223 write!(f, " = {}", ty.print(cx))?;
229 clean::GenericParamDefKind::Const { ty, default, .. } => {
231 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
233 write!(f, "const {}: {}", self.name, ty.print(cx))?;
236 if let Some(default) = default {
238 write!(f, " = {:#}", default)?;
240 write!(f, " = {}", default)?;
250 impl clean::Generics {
251 pub(crate) fn print<'a, 'tcx: 'a>(
253 cx: &'a Context<'tcx>,
254 ) -> impl fmt::Display + 'a + Captures<'tcx> {
255 display_fn(move |f| {
256 let mut real_params =
257 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
258 if real_params.peek().is_none() {
263 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
265 write!(f, "<{}>", comma_sep(real_params.map(|g| g.print(cx)), true))
271 #[derive(Clone, Copy, PartialEq, Eq)]
272 pub(crate) enum Ending {
277 /// * The Generics from which to emit a where-clause.
278 /// * The number of spaces to indent each line with.
279 /// * Whether the where-clause needs to add a comma and newline after the last bound.
280 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
281 gens: &'a clean::Generics,
282 cx: &'a Context<'tcx>,
285 ) -> impl fmt::Display + 'a + Captures<'tcx> {
288 display_fn(move |f| {
289 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
290 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
292 display_fn(move |f| {
296 f.write_str("<br>")?;
300 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
301 let ty_cx = ty.print(cx);
302 let generic_bounds = print_generic_bounds(bounds, cx);
304 if bound_params.is_empty() {
306 write!(f, "{ty_cx:#}: {generic_bounds:#}")
308 write!(f, "{ty_cx}: {generic_bounds}")
314 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
315 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
320 "for<{}> {ty_cx}: {generic_bounds}",
321 comma_sep(bound_params.iter().map(|lt| lt.print()), true)
326 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
327 let mut bounds_display = String::new();
328 for bound in bounds.iter().map(|b| b.print(cx)) {
329 write!(bounds_display, "{bound} + ")?;
331 bounds_display.truncate(bounds_display.len() - " + ".len());
332 write!(f, "{}: {bounds_display}", lifetime.print())
334 clean::WherePredicate::EqPredicate { lhs, rhs } => {
336 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
338 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
345 if where_predicates.peek().is_none() {
349 let where_preds = comma_sep(where_predicates, false);
350 let clause = if f.alternate() {
351 if ending == Ending::Newline {
352 // add a space so stripping <br> tags and breaking spaces still renders properly
353 format!(" where{where_preds}, ")
355 format!(" where{where_preds}")
358 let mut br_with_padding = String::with_capacity(6 * indent + 28);
359 br_with_padding.push_str("<br>");
360 for _ in 0..indent + 4 {
361 br_with_padding.push_str(" ");
363 let where_preds = where_preds.to_string().replace("<br>", &br_with_padding);
365 if ending == Ending::Newline {
366 let mut clause = " ".repeat(indent.saturating_sub(1));
367 // add a space so stripping <br> tags and breaking spaces still renders properly
370 " <span class=\"where fmt-newline\">where{where_preds}, </span>"
374 // insert a <br> tag after a single space but before multiple spaces at the start
376 format!(" <br><span class=\"where\">where{where_preds}</span>")
378 let mut clause = br_with_padding;
379 clause.truncate(clause.len() - 5 * " ".len());
380 write!(clause, " <span class=\"where\">where{where_preds}</span>")?;
385 write!(f, "{clause}")
389 impl clean::Lifetime {
390 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
395 impl clean::Constant {
396 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
397 let expr = self.expr(tcx);
400 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
406 impl clean::PolyTrait {
407 fn print<'a, 'tcx: 'a>(
409 cx: &'a Context<'tcx>,
410 ) -> impl fmt::Display + 'a + Captures<'tcx> {
411 display_fn(move |f| {
412 if !self.generic_params.is_empty() {
417 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
423 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
428 write!(f, "{:#}", self.trait_.print(cx))
430 write!(f, "{}", self.trait_.print(cx))
436 impl clean::GenericBound {
437 pub(crate) fn print<'a, 'tcx: 'a>(
439 cx: &'a Context<'tcx>,
440 ) -> impl fmt::Display + 'a + Captures<'tcx> {
441 display_fn(move |f| match self {
442 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
443 clean::GenericBound::TraitBound(ty, modifier) => {
444 let modifier_str = match modifier {
445 hir::TraitBoundModifier::None => "",
446 hir::TraitBoundModifier::Maybe => "?",
447 // ~const is experimental; do not display those bounds in rustdoc
448 hir::TraitBoundModifier::MaybeConst => "",
451 write!(f, "{}{:#}", modifier_str, ty.print(cx))
453 write!(f, "{}{}", modifier_str, ty.print(cx))
460 impl clean::GenericArgs {
461 fn print<'a, 'tcx: 'a>(
463 cx: &'a Context<'tcx>,
464 ) -> impl fmt::Display + 'a + Captures<'tcx> {
465 display_fn(move |f| {
467 clean::GenericArgs::AngleBracketed { args, bindings } => {
468 if !args.is_empty() || !bindings.is_empty() {
472 f.write_str("<")?;
474 let mut comma = false;
475 for arg in args.iter() {
481 write!(f, "{:#}", arg.print(cx))?;
483 write!(f, "{}", arg.print(cx))?;
486 for binding in bindings.iter() {
492 write!(f, "{:#}", binding.print(cx))?;
494 write!(f, "{}", binding.print(cx))?;
500 f.write_str(">")?;
504 clean::GenericArgs::Parenthesized { inputs, output } => {
506 let mut comma = false;
507 for ty in inputs.iter() {
513 write!(f, "{:#}", ty.print(cx))?;
515 write!(f, "{}", ty.print(cx))?;
519 if let Some(ref ty) = *output {
521 write!(f, " -> {:#}", ty.print(cx))?;
523 write!(f, " -> {}", ty.print(cx))?;
533 // Possible errors when computing href link source for a `DefId`
534 #[derive(PartialEq, Eq)]
535 pub(crate) enum HrefError {
536 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
538 /// This can only happen for non-local items.
542 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
543 /// implements it for a local type.
544 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
547 /// rustc a.rs --crate-type=lib
548 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
551 /// Now, the associated items in the trait impl want to link to the corresponding item in the
552 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
553 /// *documentation (was) not built*.
554 DocumentationNotBuilt,
555 /// This can only happen for non-local items when `--document-private-items` is not passed.
557 // Not in external cache, href link should be in same page
561 // Panics if `syms` is empty.
562 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
563 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
564 s.push_str(syms[0].as_str());
565 for sym in &syms[1..] {
567 s.push_str(sym.as_str());
572 /// This function is to get the external macro path because they are not in the cache used in
573 /// `href_with_root_path`.
574 fn generate_macro_def_id_path(
577 root_path: Option<&str>,
578 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
579 let tcx = cx.shared.tcx;
580 let crate_name = tcx.crate_name(def_id.krate).to_string();
581 let cache = cx.cache();
583 let fqp: Vec<Symbol> = tcx
588 // extern blocks (and a few others things) have an empty name.
589 match elem.data.get_opt_name() {
590 Some(s) if !s.is_empty() => Some(s),
595 let relative = fqp.iter().map(|elem| elem.to_string());
596 let cstore = CStore::from_tcx(tcx);
597 // We need this to prevent a `panic` when this function is used from intra doc links...
598 if !cstore.has_crate_data(def_id.krate) {
599 debug!("No data for crate {}", crate_name);
600 return Err(HrefError::NotInExternalCache);
602 // Check to see if it is a macro 2.0 or built-in macro.
603 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
604 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
605 LoadedMacro::MacroDef(def, _) => {
606 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
607 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
612 let mut path = if is_macro_2 {
613 once(crate_name.clone()).chain(relative).collect()
615 vec![crate_name.clone(), relative.last().unwrap()]
618 // The minimum we can have is the crate name followed by the macro name. If shorter, then
619 // it means that that `relative` was empty, which is an error.
620 debug!("macro path cannot be empty!");
621 return Err(HrefError::NotInExternalCache);
624 if let Some(last) = path.last_mut() {
625 *last = format!("macro.{}.html", last);
628 let url = match cache.extern_locations[&def_id.krate] {
629 ExternalLocation::Remote(ref s) => {
630 // `ExternalLocation::Remote` always end with a `/`.
631 format!("{}{}", s, path.join("/"))
633 ExternalLocation::Local => {
634 // `root_path` always end with a `/`.
635 format!("{}{}/{}", root_path.unwrap_or(""), crate_name, path.join("/"))
637 ExternalLocation::Unknown => {
638 debug!("crate {} not in cache when linkifying macros", crate_name);
639 return Err(HrefError::NotInExternalCache);
642 Ok((url, ItemType::Macro, fqp))
645 pub(crate) fn href_with_root_path(
648 root_path: Option<&str>,
649 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
651 let def_kind = tcx.def_kind(did);
652 let did = match def_kind {
653 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
654 // documented on their parent's page
659 let cache = cx.cache();
660 let relative_to = &cx.current;
661 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
662 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
666 && !cache.access_levels.is_public(did)
667 && !cache.document_private
668 && !cache.primitive_locations.values().any(|&id| id == did)
670 return Err(HrefError::Private);
673 let mut is_remote = false;
674 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
675 Some(&(ref fqp, shortty)) => (fqp, shortty, {
676 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
677 debug!(?fqp, ?shortty, ?module_fqp);
678 href_relative_parts(module_fqp, relative_to).collect()
681 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
682 let module_fqp = to_module_fqp(shortty, fqp);
686 match cache.extern_locations[&did.krate] {
687 ExternalLocation::Remote(ref s) => {
689 let s = s.trim_end_matches('/');
690 let mut builder = UrlPartsBuilder::singleton(s);
691 builder.extend(module_fqp.iter().copied());
694 ExternalLocation::Local => {
695 href_relative_parts(module_fqp, relative_to).collect()
697 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
700 } else if matches!(def_kind, DefKind::Macro(_)) {
701 return generate_macro_def_id_path(did, cx, root_path);
703 return Err(HrefError::NotInExternalCache);
708 if let Some(root_path) = root_path {
709 let root = root_path.trim_end_matches('/');
710 url_parts.push_front(root);
715 ItemType::Module => {
716 url_parts.push("index.html");
719 let prefix = shortty.as_str();
720 let last = fqp.last().unwrap();
721 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
724 Ok((url_parts.finish(), shortty, fqp.to_vec()))
730 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
731 href_with_root_path(did, cx, None)
734 /// Both paths should only be modules.
735 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
736 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
737 pub(crate) fn href_relative_parts<'fqp>(
739 relative_to_fqp: &[Symbol],
740 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
741 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
742 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
744 let dissimilar_part_count = relative_to_fqp.len() - i;
745 let fqp_module = &fqp[i..fqp.len()];
746 return box iter::repeat(sym::dotdot)
747 .take(dissimilar_part_count)
748 .chain(fqp_module.iter().copied());
751 // e.g. linking to std::sync::atomic from std::sync
752 if relative_to_fqp.len() < fqp.len() {
753 box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
754 // e.g. linking to std::sync from std::sync::atomic
755 } else if fqp.len() < relative_to_fqp.len() {
756 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
757 box iter::repeat(sym::dotdot).take(dissimilar_part_count)
758 // linking to the same module
764 /// Used to render a [`clean::Path`].
765 fn resolved_path<'cx>(
766 w: &mut fmt::Formatter<'_>,
771 cx: &'cx Context<'_>,
773 let last = path.segments.last().unwrap();
776 for seg in &path.segments[..path.segments.len() - 1] {
777 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
781 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
783 let path = if use_absolute {
784 if let Ok((_, _, fqp)) = href(did, cx) {
787 join_with_double_colon(&fqp[..fqp.len() - 1]),
788 anchor(did, *fqp.last().unwrap(), cx)
791 last.name.to_string()
794 anchor(did, last.name, cx).to_string()
796 write!(w, "{}{}", path, last.args.print(cx))?;
802 f: &mut fmt::Formatter<'_>,
803 prim: clean::PrimitiveType,
807 primitive_link_fragment(f, prim, name, "", cx)
810 fn primitive_link_fragment(
811 f: &mut fmt::Formatter<'_>,
812 prim: clean::PrimitiveType,
818 let mut needs_termination = false;
820 match m.primitive_locations.get(&prim) {
821 Some(&def_id) if def_id.is_local() => {
822 let len = cx.current.len();
823 let len = if len == 0 { 0 } else { len - 1 };
826 "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
830 needs_termination = true;
833 let loc = match m.extern_locations[&def_id.krate] {
834 ExternalLocation::Remote(ref s) => {
835 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
836 let builder: UrlPartsBuilder =
837 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
842 ExternalLocation::Local => {
843 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
844 Some(if cx.current.first() == Some(&cname_sym) {
845 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
847 iter::repeat(sym::dotdot)
848 .take(cx.current.len())
849 .chain(iter::once(cname_sym))
853 ExternalLocation::Unknown => None,
855 if let Some(mut loc) = loc {
856 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
857 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
858 needs_termination = true;
864 write!(f, "{}", name)?;
865 if needs_termination {
871 /// Helper to render type parameters
872 fn tybounds<'a, 'tcx: 'a>(
873 bounds: &'a [clean::PolyTrait],
874 lt: &'a Option<clean::Lifetime>,
875 cx: &'a Context<'tcx>,
876 ) -> impl fmt::Display + 'a + Captures<'tcx> {
877 display_fn(move |f| {
878 for (i, bound) in bounds.iter().enumerate() {
883 fmt::Display::fmt(&bound.print(cx), f)?;
886 if let Some(lt) = lt {
888 fmt::Display::fmt(<.print(), f)?;
894 pub(crate) fn anchor<'a, 'cx: 'a>(
897 cx: &'cx Context<'_>,
898 ) -> impl fmt::Display + 'a {
899 let parts = href(did, cx);
900 display_fn(move |f| {
901 if let Ok((url, short_ty, fqp)) = parts {
904 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
908 join_with_double_colon(&fqp),
912 write!(f, "{}", text)
919 f: &mut fmt::Formatter<'_>,
921 cx: &'cx Context<'_>,
923 trace!("fmt_type(t = {:?})", t);
926 clean::Generic(name) => write!(f, "{}", name),
927 clean::Type::Path { ref path } => {
928 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
929 let did = path.def_id();
930 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
932 clean::DynTrait(ref bounds, ref lt) => {
933 f.write_str("dyn ")?;
934 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
936 clean::Infer => write!(f, "_"),
937 clean::Primitive(clean::PrimitiveType::Never) => {
938 primitive_link(f, PrimitiveType::Never, "!", cx)
940 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
941 clean::BareFunction(ref decl) => {
946 decl.print_hrtb_with_space(cx),
947 decl.unsafety.print_with_space(),
948 print_abi_with_space(decl.abi),
955 decl.print_hrtb_with_space(cx),
956 decl.unsafety.print_with_space(),
957 print_abi_with_space(decl.abi)
959 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
960 write!(f, "{}", decl.decl.print(cx))
963 clean::Tuple(ref typs) => {
965 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
967 if let clean::Generic(name) = one {
968 primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
971 // Carry `f.alternate()` into this display w/o branching manually.
972 fmt::Display::fmt(&one.print(cx), f)?;
977 let generic_names: Vec<Symbol> = many
979 .filter_map(|t| match t {
980 clean::Generic(name) => Some(*name),
984 let is_generic = generic_names.len() == many.len();
988 PrimitiveType::Tuple,
989 &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
994 for (i, item) in many.iter().enumerate() {
998 // Carry `f.alternate()` into this display w/o branching manually.
999 fmt::Display::fmt(&item.print(cx), f)?;
1006 clean::Slice(ref t) => match **t {
1007 clean::Generic(name) => {
1008 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1012 fmt::Display::fmt(&t.print(cx), f)?;
1016 clean::Array(ref t, ref n) => {
1017 primitive_link(f, PrimitiveType::Array, "[", cx)?;
1018 fmt::Display::fmt(&t.print(cx), f)?;
1020 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
1022 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
1025 clean::RawPointer(m, ref t) => {
1027 hir::Mutability::Mut => "mut",
1028 hir::Mutability::Not => "const",
1031 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1032 let text = if f.alternate() {
1033 format!("*{} {:#}", m, t.print(cx))
1035 format!("*{} {}", m, t.print(cx))
1037 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1039 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1040 fmt::Display::fmt(&t.print(cx), f)
1043 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1045 Some(l) => format!("{} ", l.print()),
1048 let m = mutability.print_with_space();
1049 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
1051 clean::DynTrait(ref bounds, ref trait_lt)
1052 if bounds.len() > 1 || trait_lt.is_some() =>
1054 write!(f, "{}{}{}(", amp, lt, m)?;
1055 fmt_type(ty, f, use_absolute, cx)?;
1058 clean::Generic(..) => {
1061 PrimitiveType::Reference,
1062 &format!("{}{}{}", amp, lt, m),
1065 fmt_type(ty, f, use_absolute, cx)
1068 write!(f, "{}{}{}", amp, lt, m)?;
1069 fmt_type(ty, f, use_absolute, cx)
1073 clean::ImplTrait(ref bounds) => {
1075 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1077 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1080 clean::QPath { ref assoc, ref self_type, ref trait_, should_show_cast } => {
1082 if should_show_cast {
1083 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1085 write!(f, "{:#}::", self_type.print(cx))?
1088 if should_show_cast {
1089 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
1091 write!(f, "{}::", self_type.print(cx))?
1094 // It's pretty unsightly to look at `<A as B>::C` in output, and
1095 // we've got hyperlinking on our side, so try to avoid longer
1096 // notation as much as possible by making `C` a hyperlink to trait
1097 // `B` to disambiguate.
1099 // FIXME: this is still a lossy conversion and there should probably
1100 // be a better way of representing this in general? Most of
1101 // the ugliness comes from inlining across crates where
1102 // everything comes in as a fully resolved QPath (hard to
1104 match href(trait_.def_id(), cx) {
1105 Ok((ref url, _, ref path)) if !f.alternate() => {
1108 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1109 title=\"type {path}::{name}\">{name}</a>{args}",
1111 shortty = ItemType::AssocType,
1113 path = join_with_double_colon(path),
1114 args = assoc.args.print(cx),
1117 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1125 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1127 cx: &'a Context<'tcx>,
1128 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1129 display_fn(move |f| fmt_type(self, f, false, 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| resolved_path(f, self.def_id(), self, false, false, cx))
1143 pub(crate) fn print<'a, 'tcx: 'a>(
1146 cx: &'a Context<'tcx>,
1147 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1148 display_fn(move |f| {
1150 write!(f, "impl{:#} ", self.generics.print(cx))?;
1152 write!(f, "impl{} ", self.generics.print(cx))?;
1155 if let Some(ref ty) = self.trait_ {
1156 match self.polarity {
1157 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1158 ty::ImplPolarity::Negative => write!(f, "!")?,
1160 fmt::Display::fmt(&ty.print(cx), f)?;
1161 write!(f, " for ")?;
1164 if let clean::Type::Tuple(types) = &self.for_ &&
1165 let [clean::Type::Generic(name)] = &types[..] &&
1166 (self.kind.is_tuple_variadic() || self.kind.is_auto()) {
1167 // Hardcoded anchor library/core/src/primitive_docs.rs
1168 // Link should match `# Trait implementations`
1169 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1170 } else if let Some(ty) = self.kind.as_blanket_ty() {
1171 fmt_type(ty, f, use_absolute, cx)?;
1173 fmt_type(&self.for_, f, use_absolute, cx)?;
1176 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1182 impl clean::Arguments {
1183 pub(crate) fn print<'a, 'tcx: 'a>(
1185 cx: &'a Context<'tcx>,
1186 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1187 display_fn(move |f| {
1188 for (i, input) in self.values.iter().enumerate() {
1189 if !input.name.is_empty() {
1190 write!(f, "{}: ", input.name)?;
1193 write!(f, "{:#}", input.type_.print(cx))?;
1195 write!(f, "{}", input.type_.print(cx))?;
1197 if i + 1 < self.values.len() {
1206 impl clean::FnRetTy {
1207 pub(crate) fn print<'a, 'tcx: 'a>(
1209 cx: &'a Context<'tcx>,
1210 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1211 display_fn(move |f| match self {
1212 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1213 clean::Return(ty) if f.alternate() => {
1214 write!(f, " -> {:#}", ty.print(cx))
1216 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1217 clean::DefaultReturn => Ok(()),
1222 impl clean::BareFunctionDecl {
1223 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1225 cx: &'a Context<'tcx>,
1226 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1227 display_fn(move |f| {
1228 if !self.generic_params.is_empty() {
1232 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1241 impl clean::FnDecl {
1242 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1244 cx: &'a Context<'tcx>,
1245 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1246 display_fn(move |f| {
1247 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1251 "({args:#}{ellipsis}){arrow:#}",
1252 args = self.inputs.print(cx),
1253 ellipsis = ellipsis,
1254 arrow = self.output.print(cx)
1259 "({args}{ellipsis}){arrow}",
1260 args = self.inputs.print(cx),
1261 ellipsis = ellipsis,
1262 arrow = self.output.print(cx)
1268 /// * `header_len`: The length of the function header and name. In other words, the number of
1269 /// characters in the function declaration up to but not including the parentheses.
1270 /// <br>Used to determine line-wrapping.
1271 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1273 /// * `asyncness`: Whether the function is async or not.
1274 pub(crate) fn full_print<'a, 'tcx: 'a>(
1278 asyncness: hir::IsAsync,
1279 cx: &'a Context<'tcx>,
1280 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1281 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1284 fn inner_full_print(
1288 asyncness: hir::IsAsync,
1289 f: &mut fmt::Formatter<'_>,
1292 let amp = if f.alternate() { "&" } else { "&" };
1293 let mut args = Buffer::html();
1294 let mut args_plain = Buffer::new();
1295 for (i, input) in self.inputs.values.iter().enumerate() {
1296 if let Some(selfty) = input.to_self() {
1298 clean::SelfValue => {
1299 args.push_str("self");
1300 args_plain.push_str("self");
1302 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1303 write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1304 write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1306 clean::SelfBorrowed(None, mtbl) => {
1307 write!(args, "{}{}self", amp, mtbl.print_with_space());
1308 write!(args_plain, "&{}self", mtbl.print_with_space());
1310 clean::SelfExplicit(ref typ) => {
1312 write!(args, "self: {:#}", typ.print(cx));
1314 write!(args, "self: {}", typ.print(cx));
1316 write!(args_plain, "self: {:#}", typ.print(cx));
1321 args.push_str("<br>");
1324 args.push_str("const ");
1325 args_plain.push_str("const ");
1327 if !input.name.is_empty() {
1328 write!(args, "{}: ", input.name);
1329 write!(args_plain, "{}: ", input.name);
1333 write!(args, "{:#}", input.type_.print(cx));
1335 write!(args, "{}", input.type_.print(cx));
1337 write!(args_plain, "{:#}", input.type_.print(cx));
1339 if i + 1 < self.inputs.values.len() {
1341 args_plain.push_str(",");
1345 let mut args_plain = format!("({})", args_plain.into_inner());
1346 let mut args = args.into_inner();
1348 if self.c_variadic {
1349 args.push_str(",<br> ...");
1350 args_plain.push_str(", ...");
1354 let arrow = if let hir::IsAsync::Async = asyncness {
1355 let output = self.sugared_async_return_type();
1356 arrow_plain = format!("{:#}", output.print(cx));
1357 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1359 arrow_plain = format!("{:#}", self.output.print(cx));
1360 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1363 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1364 let output = if declaration_len > 80 {
1365 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1366 let close_pad = format!("<br>{}", " ".repeat(indent));
1368 "({pad}{args}{close}){arrow}",
1369 pad = if self.inputs.values.is_empty() { "" } else { &full_pad },
1370 args = args.replace("<br>", &full_pad),
1375 format!("({args}){arrow}", args = args.replace("<br>", " "), arrow = arrow)
1379 write!(f, "{}", output.replace("<br>", "\n"))
1381 write!(f, "{}", output)
1386 impl clean::Visibility {
1387 pub(crate) fn print_with_space<'a, 'tcx: 'a>(
1390 cx: &'a Context<'tcx>,
1391 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1392 use std::fmt::Write as _;
1394 let to_print: Cow<'static, str> = match self {
1395 clean::Public => "pub ".into(),
1396 clean::Inherited => "".into(),
1397 clean::Visibility::Restricted(vis_did) => {
1398 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1399 // However, rustdoc currently never displays a module's
1400 // visibility, so it shouldn't matter.
1401 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1403 if vis_did.is_crate_root() {
1404 "pub(crate) ".into()
1405 } else if parent_module == Some(vis_did) {
1406 // `pub(in foo)` where `foo` is the parent module
1407 // is the same as no visibility modifier
1409 } else if parent_module
1410 .and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1413 "pub(super) ".into()
1415 let path = cx.tcx().def_path(vis_did);
1416 debug!("path={:?}", path);
1417 // modified from `resolved_path()` to work with `DefPathData`
1418 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1419 let anchor = anchor(vis_did, last_name, cx).to_string();
1421 let mut s = "pub(in ".to_owned();
1422 for seg in &path.data[..path.data.len() - 1] {
1423 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1425 let _ = write!(s, "{}) ", anchor);
1430 display_fn(move |f| write!(f, "{}", to_print))
1433 /// This function is the same as print_with_space, except that it renders no links.
1434 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1436 pub(crate) fn to_src_with_space<'a, 'tcx: 'a>(
1440 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1441 let to_print = match self {
1442 clean::Public => "pub ".to_owned(),
1443 clean::Inherited => String::new(),
1444 clean::Visibility::Restricted(vis_did) => {
1445 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1446 // However, rustdoc currently never displays a module's
1447 // visibility, so it shouldn't matter.
1448 let parent_module = find_nearest_parent_module(tcx, item_did);
1450 if vis_did.is_crate_root() {
1451 "pub(crate) ".to_owned()
1452 } else if parent_module == Some(vis_did) {
1453 // `pub(in foo)` where `foo` is the parent module
1454 // is the same as no visibility modifier
1456 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1459 "pub(super) ".to_owned()
1461 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1465 display_fn(move |f| f.write_str(&to_print))
1469 pub(crate) trait PrintWithSpace {
1470 fn print_with_space(&self) -> &str;
1473 impl PrintWithSpace for hir::Unsafety {
1474 fn print_with_space(&self) -> &str {
1476 hir::Unsafety::Unsafe => "unsafe ",
1477 hir::Unsafety::Normal => "",
1482 impl PrintWithSpace for hir::IsAsync {
1483 fn print_with_space(&self) -> &str {
1485 hir::IsAsync::Async => "async ",
1486 hir::IsAsync::NotAsync => "",
1491 impl PrintWithSpace for hir::Mutability {
1492 fn print_with_space(&self) -> &str {
1494 hir::Mutability::Not => "",
1495 hir::Mutability::Mut => "mut ",
1500 pub(crate) fn print_constness_with_space(
1502 s: Option<ConstStability>,
1505 // const stable or when feature(staged_api) is not set
1507 hir::Constness::Const,
1508 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1510 | (hir::Constness::Const, None) => "const ",
1511 // const unstable or not const
1516 impl clean::Import {
1517 pub(crate) fn print<'a, 'tcx: 'a>(
1519 cx: &'a Context<'tcx>,
1520 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1521 display_fn(move |f| match self.kind {
1522 clean::ImportKind::Simple(name) => {
1523 if name == self.source.path.last() {
1524 write!(f, "use {};", self.source.print(cx))
1526 write!(f, "use {} as {};", self.source.print(cx), name)
1529 clean::ImportKind::Glob => {
1530 if self.source.path.segments.is_empty() {
1533 write!(f, "use {}::*;", self.source.print(cx))
1540 impl clean::ImportSource {
1541 pub(crate) fn print<'a, 'tcx: 'a>(
1543 cx: &'a Context<'tcx>,
1544 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1545 display_fn(move |f| match self.did {
1546 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1548 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1549 write!(f, "{}::", seg.name)?;
1551 let name = self.path.last();
1552 if let hir::def::Res::PrimTy(p) = self.path.res {
1553 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1555 write!(f, "{}", name)?;
1563 impl clean::TypeBinding {
1564 pub(crate) fn print<'a, 'tcx: 'a>(
1566 cx: &'a Context<'tcx>,
1567 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1568 display_fn(move |f| {
1569 f.write_str(self.assoc.name.as_str())?;
1571 write!(f, "{:#}", self.assoc.args.print(cx))?;
1573 write!(f, "{}", self.assoc.args.print(cx))?;
1576 clean::TypeBindingKind::Equality { ref term } => {
1578 write!(f, " = {:#}", term.print(cx))?;
1580 write!(f, " = {}", term.print(cx))?;
1583 clean::TypeBindingKind::Constraint { ref bounds } => {
1584 if !bounds.is_empty() {
1586 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1588 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1598 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1599 display_fn(move |f| {
1600 let quot = if f.alternate() { "\"" } else { """ };
1602 Abi::Rust => Ok(()),
1603 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1608 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1609 if v { "default " } else { "" }
1612 impl clean::GenericArg {
1613 pub(crate) fn print<'a, 'tcx: 'a>(
1615 cx: &'a Context<'tcx>,
1616 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1617 display_fn(move |f| match self {
1618 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1619 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1620 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1621 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1626 impl clean::types::Term {
1627 pub(crate) fn print<'a, 'tcx: 'a>(
1629 cx: &'a Context<'tcx>,
1630 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1632 clean::types::Term::Type(ty) => ty.print(cx),
1638 pub(crate) fn display_fn(
1639 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1640 ) -> impl fmt::Display {
1641 struct WithFormatter<F>(Cell<Option<F>>);
1643 impl<F> fmt::Display for WithFormatter<F>
1645 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1648 (self.0.take()).unwrap()(f)
1652 WithFormatter(Cell::new(Some(f)))