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.
12 use rustc_attr
::{ConstStability, StabilityLevel}
;
13 use rustc_data_structures
::captures
::Captures
;
14 use rustc_data_structures
::fx
::FxHashSet
;
16 use rustc_hir
::def
::DefKind
;
17 use rustc_hir
::def_id
::DefId
;
19 use rustc_middle
::ty
::DefIdTree
;
20 use rustc_middle
::ty
::TyCtxt
;
21 use rustc_span
::symbol
::kw
;
22 use rustc_span
::{sym, Symbol}
;
23 use rustc_target
::spec
::abi
::Abi
;
26 self, types
::ExternalLocation
, utils
::find_nearest_parent_module
, ExternalCrate
, ItemId
,
29 use crate::formats
::item_type
::ItemType
;
30 use crate::html
::escape
::Escape
;
31 use crate::html
::render
::Context
;
33 use super::url_parts_builder
::estimate_item_path_byte_length
;
34 use super::url_parts_builder
::UrlPartsBuilder
;
37 fn print(self, buffer
: &mut Buffer
);
42 F
: FnOnce(&mut Buffer
),
44 fn print(self, buffer
: &mut Buffer
) {
49 impl Print
for String
{
50 fn print(self, buffer
: &mut Buffer
) {
51 buffer
.write_str(&self);
55 impl Print
for &'_
str {
56 fn print(self, buffer
: &mut Buffer
) {
57 buffer
.write_str(self);
61 #[derive(Debug, Clone)]
67 impl core
::fmt
::Write
for Buffer
{
69 fn write_str(&mut self, s
: &str) -> fmt
::Result
{
70 self.buffer
.write_str(s
)
74 fn write_char(&mut self, c
: char) -> fmt
::Result
{
75 self.buffer
.write_char(c
)
79 fn write_fmt(&mut self, args
: fmt
::Arguments
<'_
>) -> fmt
::Result
{
80 self.buffer
.write_fmt(args
)
85 crate fn empty_from(v
: &Buffer
) -> Buffer
{
86 Buffer { for_html: v.for_html, buffer: String::new() }
89 crate fn html() -> Buffer
{
90 Buffer { for_html: true, buffer: String::new() }
93 crate fn new() -> Buffer
{
94 Buffer { for_html: false, buffer: String::new() }
97 crate fn is_empty(&self) -> bool
{
98 self.buffer
.is_empty()
101 crate fn into_inner(self) -> String
{
105 crate fn insert_str(&mut self, idx
: usize, s
: &str) {
106 self.buffer
.insert_str(idx
, s
);
109 crate fn push_str(&mut self, s
: &str) {
110 self.buffer
.push_str(s
);
113 crate fn push_buffer(&mut self, other
: Buffer
) {
114 self.buffer
.push_str(&other
.buffer
);
117 // Intended for consumption by write! and writeln! (std::fmt) but without
118 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
120 crate fn write_str(&mut self, s
: &str) {
121 self.buffer
.push_str(s
);
124 // Intended for consumption by write! and writeln! (std::fmt) but without
125 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
127 crate fn write_fmt(&mut self, v
: fmt
::Arguments
<'_
>) {
129 self.buffer
.write_fmt(v
).unwrap();
132 crate fn to_display
<T
: Print
>(mut self, t
: T
) -> String
{
137 crate fn is_for_html(&self) -> bool
{
141 crate fn reserve(&mut self, additional
: usize) {
142 self.buffer
.reserve(additional
)
146 fn comma_sep
<T
: fmt
::Display
>(
147 items
: impl Iterator
<Item
= T
>,
148 space_after_comma
: bool
,
149 ) -> impl fmt
::Display
{
150 display_fn(move |f
| {
151 for (i
, item
) in items
.enumerate() {
153 write
!(f
, ",{}", if space_after_comma { " " }
else { "" }
)?
;
155 fmt
::Display
::fmt(&item
, f
)?
;
161 crate fn print_generic_bounds
<'a
, 'tcx
: 'a
>(
162 bounds
: &'a
[clean
::GenericBound
],
163 cx
: &'a Context
<'tcx
>,
164 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
165 display_fn(move |f
| {
166 let mut bounds_dup
= FxHashSet
::default();
168 for (i
, bound
) in bounds
.iter().filter(|b
| bounds_dup
.insert(b
.clone())).enumerate() {
172 fmt
::Display
::fmt(&bound
.print(cx
), f
)?
;
178 impl clean
::GenericParamDef
{
179 crate fn print
<'a
, 'tcx
: 'a
>(
181 cx
: &'a Context
<'tcx
>,
182 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
183 display_fn(move |f
| match &self.kind
{
184 clean
::GenericParamDefKind
::Lifetime { outlives }
=> {
185 write
!(f
, "{}", self.name
)?
;
187 if !outlives
.is_empty() {
189 for (i
, lt
) in outlives
.iter().enumerate() {
193 write
!(f
, "{}", lt
.print())?
;
199 clean
::GenericParamDefKind
::Type { bounds, default, .. }
=> {
200 f
.write_str(self.name
.as_str())?
;
202 if !bounds
.is_empty() {
204 write
!(f
, ": {:#}", print_generic_bounds(bounds
, cx
))?
;
206 write
!(f
, ": {}", print_generic_bounds(bounds
, cx
))?
;
210 if let Some(ref ty
) = default {
212 write
!(f
, " = {:#}", ty
.print(cx
))?
;
214 write
!(f
, " = {}", ty
.print(cx
))?
;
220 clean
::GenericParamDefKind
::Const { ty, default, .. }
=> {
222 write
!(f
, "const {}: {:#}", self.name
, ty
.print(cx
))?
;
224 write
!(f
, "const {}: {}", self.name
, ty
.print(cx
))?
;
227 if let Some(default) = default {
229 write
!(f
, " = {:#}", default)?
;
231 write
!(f
, " = {}", default)?
;
241 impl clean
::Generics
{
242 crate fn print
<'a
, 'tcx
: 'a
>(
244 cx
: &'a Context
<'tcx
>,
245 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
246 display_fn(move |f
| {
247 let mut real_params
=
248 self.params
.iter().filter(|p
| !p
.is_synthetic_type_param()).peekable();
249 if real_params
.peek().is_none() {
254 write
!(f
, "<{:#}>", comma_sep(real_params
.map(|g
| g
.print(cx
)), true))
256 write
!(f
, "<{}>", comma_sep(real_params
.map(|g
| g
.print(cx
)), true))
262 /// * The Generics from which to emit a where-clause.
263 /// * The number of spaces to indent each line with.
264 /// * Whether the where-clause needs to add a comma and newline after the last bound.
265 crate fn print_where_clause
<'a
, 'tcx
: 'a
>(
266 gens
: &'a clean
::Generics
,
267 cx
: &'a Context
<'tcx
>,
270 ) -> impl fmt
::Display
+ 'a
+ Captures
<'tcx
> {
273 display_fn(move |f
| {
274 let mut where_predicates
= gens
.where_predicates
.iter().filter(|pred
| {
275 !matches
!(pred
, clean
::WherePredicate
::BoundPredicate { bounds, .. }
if bounds
.is_empty())
277 display_fn(move |f
| {
281 f
.write_str("<br>")?
;
285 clean
::WherePredicate
::BoundPredicate { ty, bounds, bound_params }
=> {
286 let ty_cx
= ty
.print(cx
);
287 let generic_bounds
= print_generic_bounds(bounds
, cx
);
289 if bound_params
.is_empty() {
291 write
!(f
, "{ty_cx:#}: {generic_bounds:#}")
293 write
!(f
, "{ty_cx}: {generic_bounds}")
299 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
300 comma_sep(bound_params
.iter().map(|lt
| lt
.print()), true)
305 "for<{}> {ty_cx}: {generic_bounds}",
306 comma_sep(bound_params
.iter().map(|lt
| lt
.print()), true)
311 clean
::WherePredicate
::RegionPredicate { lifetime, bounds }
=> {
312 let mut bounds_display
= String
::new();
313 for bound
in bounds
.iter().map(|b
| b
.print(cx
)) {
314 write
!(bounds_display
, "{bound} + ")?
;
316 bounds_display
.truncate(bounds_display
.len() - " + ".len());
317 write
!(f
, "{}: {bounds_display}", lifetime
.print())
319 clean
::WherePredicate
::EqPredicate { lhs, rhs }
=> {
321 write
!(f
, "{:#} == {:#}", lhs
.print(cx
), rhs
.print(cx
))
323 write
!(f
, "{} == {}", lhs
.print(cx
), rhs
.print(cx
))
330 if where_predicates
.peek().is_none() {
334 let where_preds
= comma_sep(where_predicates
, false);
335 let clause
= if f
.alternate() {
337 // add a space so stripping <br> tags and breaking spaces still renders properly
338 format
!(" where{where_preds}, ")
340 format
!(" where{where_preds}")
343 let mut br_with_padding
= String
::with_capacity(6 * indent
+ 28);
344 br_with_padding
.push_str("<br>");
345 for _
in 0..indent
+ 4 {
346 br_with_padding
.push_str(" ");
348 let where_preds
= where_preds
.to_string().replace("<br>", &br_with_padding
);
351 let mut clause
= " ".repeat(indent
.saturating_sub(1));
352 // add a space so stripping <br> tags and breaking spaces still renders properly
355 " <span class=\"where fmt-newline\">where{where_preds}, </span>"
359 // insert a <br> tag after a single space but before multiple spaces at the start
361 format
!(" <br><span class=\"where\">where{where_preds}</span>")
363 let mut clause
= br_with_padding
;
364 clause
.truncate(clause
.len() - 5 * " ".len());
365 write
!(clause
, " <span class=\"where\">where{where_preds}</span>")?
;
370 write
!(f
, "{clause}")
374 impl clean
::Lifetime
{
375 crate fn print(&self) -> impl fmt
::Display
+ '_
{
380 impl clean
::Constant
{
381 crate fn print(&self, tcx
: TyCtxt
<'_
>) -> impl fmt
::Display
+ '_
{
382 let expr
= self.expr(tcx
);
385 if f
.alternate() { f.write_str(&expr) }
else { write!(f, "{}
", Escape(&expr)) }
391 impl clean::PolyTrait {
392 fn print<'a, 'tcx: 'a>(
394 cx: &'a Context<'tcx>,
395 ) -> impl fmt::Display + 'a + Captures<'tcx> {
396 display_fn(move |f| {
397 if !self.generic_params.is_empty() {
402 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
408 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
413 write!(f, "{:#}
", self.trait_.print(cx))
415 write!(f, "{}
", self.trait_.print(cx))
421 impl clean::GenericBound {
422 crate fn print<'a, 'tcx: 'a>(
424 cx: &'a Context<'tcx>,
425 ) -> impl fmt::Display + 'a + Captures<'tcx> {
426 display_fn(move |f| match self {
427 clean::GenericBound::Outlives(lt) => write!(f, "{}
", lt.print()),
428 clean::GenericBound::TraitBound(ty, modifier) => {
429 let modifier_str = match modifier {
430 hir::TraitBoundModifier::None => "",
431 hir::TraitBoundModifier::Maybe => "?
",
432 // ~const is experimental; do not display those bounds in rustdoc
433 hir::TraitBoundModifier::MaybeConst => "",
436 write!(f, "{}{:#}
", modifier_str, ty.print(cx))
438 write!(f, "{}{}
", modifier_str, ty.print(cx))
445 impl clean::GenericArgs {
446 fn print<'a, 'tcx: 'a>(
448 cx: &'a Context<'tcx>,
449 ) -> impl fmt::Display + 'a + Captures<'tcx> {
450 display_fn(move |f| {
452 clean::GenericArgs::AngleBracketed { args, bindings } => {
453 if !args.is_empty() || !bindings.is_empty() {
457 f.write_str("<
;")?;
459 let mut comma = false;
466 write!(f, "{:#}
", arg.print(cx))?;
468 write!(f, "{}
", arg.print(cx))?;
471 for binding in bindings {
477 write!(f, "{:#}
", binding.print(cx))?;
479 write!(f, "{}
", binding.print(cx))?;
485 f.write_str(">
;")?;
489 clean::GenericArgs::Parenthesized { inputs, output } => {
491 let mut comma = false;
498 write!(f, "{:#}
", ty.print(cx))?;
500 write!(f, "{}
", ty.print(cx))?;
504 if let Some(ref ty) = *output {
506 write!(f, " -> {:#}
", ty.print(cx))?;
508 write!(f, " ->
; {}
", ty.print(cx))?;
518 // Possible errors when computing href link source for a `DefId`
519 crate enum HrefError {
520 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
522 /// This can only happen for non-local items.
526 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
527 /// implements it for a local type.
528 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
531 /// rustc a.rs --crate-type=lib
532 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
535 /// Now, the associated items in the trait impl want to link to the corresponding item in the
536 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
537 /// *documentation (was) not built*.
538 DocumentationNotBuilt,
539 /// This can only happen for non-local items when `--document-private-items` is not passed.
541 // Not in external cache, href link should be in same page
545 // Panics if `syms` is empty.
546 crate fn join_with_double_colon(syms: &[Symbol]) -> String {
547 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
548 s.push_str(&syms[0].as_str());
549 for sym in &syms[1..] {
551 s.push_str(&sym.as_str());
556 crate fn href_with_root_path(
559 root_path: Option<&str>,
560 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
562 let def_kind = tcx.def_kind(did);
563 let did = match def_kind {
564 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
565 // documented on their parent's page
570 let cache = cx.cache();
571 let relative_to = &cx.current;
572 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
573 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
577 && !cache.access_levels.is_public(did)
578 && !cache.document_private
579 && !cache.primitive_locations.values().any(|&id| id == did)
581 return Err(HrefError::Private);
584 let mut is_remote = false;
585 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
586 Some(&(ref fqp, shortty)) => (fqp, shortty, {
587 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
588 debug!(?fqp, ?shortty, ?module_fqp);
589 href_relative_parts(module_fqp, relative_to).collect()
592 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
593 let module_fqp = to_module_fqp(shortty, fqp);
597 match cache.extern_locations[&did.krate] {
598 ExternalLocation::Remote(ref s) => {
600 let s = s.trim_end_matches('/');
601 let mut builder = UrlPartsBuilder::singleton(s);
602 builder.extend(module_fqp.iter().copied());
605 ExternalLocation::Local => {
606 href_relative_parts(module_fqp, relative_to).collect()
608 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
612 return Err(HrefError::NotInExternalCache);
617 if let Some(root_path) = root_path {
618 let root = root_path.trim_end_matches('/');
619 url_parts.push_front(root);
624 ItemType::Module => {
625 url_parts.push("index
.html
");
628 let prefix = shortty.as_str();
629 let last = fqp.last().unwrap();
630 url_parts.push_fmt(format_args!("{}
.{}
.html
", prefix, last));
633 Ok((url_parts.finish(), shortty, fqp.to_vec()))
636 crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
637 href_with_root_path(did, cx, None)
640 /// Both paths should only be modules.
641 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
642 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
643 crate fn href_relative_parts<'fqp>(
645 relative_to_fqp: &[Symbol],
646 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
647 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
648 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
650 let dissimilar_part_count = relative_to_fqp.len() - i;
651 let fqp_module = &fqp[i..fqp.len()];
652 return box iter::repeat(sym::dotdot)
653 .take(dissimilar_part_count)
654 .chain(fqp_module.iter().copied());
657 // e.g. linking to std::sync::atomic from std::sync
658 if relative_to_fqp.len() < fqp.len() {
659 box fqp[relative_to_fqp.len()..fqp.len()].iter().copied()
660 // e.g. linking to std::sync from std::sync::atomic
661 } else if fqp.len() < relative_to_fqp.len() {
662 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
663 box iter::repeat(sym::dotdot).take(dissimilar_part_count)
664 // linking to the same module
670 /// Used to render a [`clean::Path`].
671 fn resolved_path<'cx>(
672 w: &mut fmt::Formatter<'_>,
677 cx: &'cx Context<'_>,
679 let last = path.segments.last().unwrap();
682 for seg in &path.segments[..path.segments.len() - 1] {
683 write!(w, "{}
::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
687 write!(w, "{}{:#}
", &last.name, last.args.print(cx))?;
689 let path = if use_absolute {
690 if let Ok((_, _, fqp)) = href(did, cx) {
693 join_with_double_colon(&fqp[..fqp.len() - 1]),
694 anchor(did, *fqp.last().unwrap(), cx)
697 last.name.to_string()
700 anchor(did, last.name, cx).to_string()
702 write!(w, "{}{}
", path, last.args.print(cx))?;
708 f: &mut fmt::Formatter<'_>,
709 prim: clean::PrimitiveType,
714 let mut needs_termination = false;
716 match m.primitive_locations.get(&prim) {
717 Some(&def_id) if def_id.is_local() => {
718 let len = cx.current.len();
719 let len = if len == 0 { 0 } else { len - 1 };
722 "<a class
=\"primitive
\" href
=\"{}primitive
.{}
.html
\">",
726 needs_termination = true;
729 let loc = match m.extern_locations[&def_id.krate] {
730 ExternalLocation::Remote(ref s) => {
731 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
732 let builder: UrlPartsBuilder =
733 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
738 ExternalLocation::Local => {
739 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
740 Some(if cx.current.first() == Some(&cname_sym) {
741 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
743 iter::repeat(sym::dotdot)
744 .take(cx.current.len())
745 .chain(iter::once(cname_sym))
749 ExternalLocation::Unknown => None,
751 if let Some(mut loc) = loc {
752 loc.push_fmt(format_args!("primitive
.{}
.html
", prim.as_sym()));
753 write!(f, "<a class
=\"primitive
\" href
=\"{}
\">", loc.finish())?;
754 needs_termination = true;
760 write!(f, "{}
", name)?;
761 if needs_termination {
767 /// Helper to render type parameters
768 fn tybounds<'a, 'tcx: 'a>(
769 bounds: &'a [clean::PolyTrait],
770 lt: &'a Option<clean::Lifetime>,
771 cx: &'a Context<'tcx>,
772 ) -> impl fmt::Display + 'a + Captures<'tcx> {
773 display_fn(move |f| {
774 for (i, bound) in bounds.iter().enumerate() {
779 fmt::Display::fmt(&bound.print(cx), f)?;
782 if let Some(lt) = lt {
784 fmt::Display::fmt(<.print(), f)?;
790 crate fn anchor<'a, 'cx: 'a>(
793 cx: &'cx Context<'_>,
794 ) -> impl fmt::Display + 'a {
795 let parts = href(did, cx);
796 display_fn(move |f| {
797 if let Ok((url, short_ty, fqp)) = parts {
800 r#"<a class
="{}" href
="{}" title
="{} {}">{}
</a
>"#,
804 join_with_double_colon(&fqp),
808 write!(f, "{}
", text)
815 f: &mut fmt::Formatter<'_>,
817 cx: &'cx Context<'_>,
819 trace!("fmt_type(t
= {:?}
)", t);
822 clean::Generic(name) => write!(f, "{}
", name),
823 clean::Type::Path { ref path } => {
824 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
825 let did = path.def_id();
826 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
828 clean::DynTrait(ref bounds, ref lt) => {
829 f.write_str("dyn ")?;
830 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
832 clean::Infer => write!(f, "_
"),
833 clean::Primitive(clean::PrimitiveType::Never) => {
834 primitive_link(f, PrimitiveType::Never, "!", cx)
836 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
837 clean::BareFunction(ref decl) => {
842 decl.print_hrtb_with_space(cx),
843 decl.unsafety.print_with_space(),
844 print_abi_with_space(decl.abi),
851 decl.print_hrtb_with_space(cx),
852 decl.unsafety.print_with_space(),
853 print_abi_with_space(decl.abi)
855 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
856 write!(f, "{}
", decl.decl.print(cx))
859 clean::Tuple(ref typs) => {
861 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
863 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
864 // Carry `f.alternate()` into this display w/o branching manually.
865 fmt::Display::fmt(&one.print(cx), f)?;
866 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
869 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
870 for (i, item) in many.iter().enumerate() {
874 fmt::Display::fmt(&item.print(cx), f)?;
876 primitive_link(f, PrimitiveType::Tuple, ")", cx)
880 clean::Slice(ref t) => {
881 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
882 fmt::Display::fmt(&t.print(cx), f)?;
883 primitive_link(f, PrimitiveType::Slice, "]", cx)
885 clean::Array(ref t, ref n) => {
886 primitive_link(f, PrimitiveType::Array, "[", cx)?;
887 fmt::Display::fmt(&t.print(cx), f)?;
889 primitive_link(f, PrimitiveType::Array, &format!("; {}
]", n), cx)
891 primitive_link(f, PrimitiveType::Array, &format!("; {}
]", Escape(n)), cx)
894 clean::RawPointer(m, ref t) => {
896 hir::Mutability::Mut => "mut",
897 hir::Mutability::Not => "const",
900 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
901 let text = if f.alternate() {
902 format!("*{} {:#}
", m, t.print(cx))
904 format!("*{} {}
", m, t.print(cx))
906 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
908 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{}
", m), cx)?;
909 fmt::Display::fmt(&t.print(cx), f)
912 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
914 Some(l) => format!("{}
", l.print()),
917 let m = mutability.print_with_space();
918 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
920 clean::Slice(ref bt) => {
921 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
923 clean::Generic(_) => {
927 PrimitiveType::Slice,
928 &format!("{}{}{}
[{:#}
]", amp, lt, m, bt.print(cx)),
934 PrimitiveType::Slice,
935 &format!("{}{}{}
[{}
]", amp, lt, m, bt.print(cx)),
943 PrimitiveType::Slice,
944 &format!("{}{}{}
[", amp, lt, m),
948 write!(f, "{:#}
", bt.print(cx))?;
950 write!(f, "{}
", bt.print(cx))?;
952 primitive_link(f, PrimitiveType::Slice, "]", cx)
956 clean::DynTrait(ref bounds, ref trait_lt)
957 if bounds.len() > 1 || trait_lt.is_some() =>
959 write!(f, "{}{}{}
(", amp, lt, m)?;
960 fmt_type(ty, f, use_absolute, cx)?;
963 clean::Generic(..) => {
966 PrimitiveType::Reference,
967 &format!("{}{}{}
", amp, lt, m),
970 fmt_type(ty, f, use_absolute, cx)
973 write!(f, "{}{}{}
", amp, lt, m)?;
974 fmt_type(ty, f, use_absolute, cx)
978 clean::ImplTrait(ref bounds) => {
980 write!(f, "impl {:#}
", print_generic_bounds(bounds, cx))
982 write!(f, "impl {}
", print_generic_bounds(bounds, cx))
985 clean::QPath { ref assoc, ref self_type, ref trait_, ref self_def_id } => {
986 let should_show_cast = !trait_.segments.is_empty()
988 .zip(Some(trait_.def_id()))
989 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_);
991 if should_show_cast {
992 write!(f, "<{:#}
as {:#}
>::", self_type.print(cx), trait_.print(cx))?
994 write!(f, "{:#}
::", self_type.print(cx))?
997 if should_show_cast {
998 write!(f, "<
;{}
as {}
>
;::", self_type.print(cx), trait_.print(cx))?
1000 write!(f, "{}
::", self_type.print(cx))?
1003 // It's pretty unsightly to look at `<A as B>::C` in output, and
1004 // we've got hyperlinking on our side, so try to avoid longer
1005 // notation as much as possible by making `C` a hyperlink to trait
1006 // `B` to disambiguate.
1008 // FIXME: this is still a lossy conversion and there should probably
1009 // be a better way of representing this in general? Most of
1010 // the ugliness comes from inlining across crates where
1011 // everything comes in as a fully resolved QPath (hard to
1013 match href(trait_.def_id(), cx) {
1014 Ok((ref url, _, ref path)) if !f.alternate() => {
1017 "<a class
=\"associatedtype
\" href
=\"{url}
#{shortty}.{name}\" \
1018 title=\"type {path}::{name}\">{name}</a>{args}",
1020 shortty = ItemType::AssocType,
1022 path = join_with_double_colon(path),
1023 args = assoc.args.print(cx),
1026 _ => write!(f, "{}{:#}", assoc.name, assoc.args.print(cx))?,
1034 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1036 cx: &'a Context<'tcx>,
1037 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1038 display_fn(move |f| fmt_type(self, f, false, cx))
1043 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1045 cx: &'a Context<'tcx>,
1046 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1047 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1052 crate fn print<'a, 'tcx: 'a>(
1055 cx: &'a Context<'tcx>,
1056 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1057 display_fn(move |f| {
1059 write!(f, "impl{:#} ", self.generics.print(cx))?;
1061 write!(f, "impl{} ", self.generics.print(cx))?;
1064 if let Some(ref ty) = self.trait_ {
1065 match self.polarity {
1066 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1067 ty::ImplPolarity::Negative => write!(f, "!")?,
1069 fmt::Display::fmt(&ty.print(cx), f)?;
1070 write!(f, " for ")?;
1073 if let Some(ref ty) = self.kind.as_blanket_ty() {
1074 fmt_type(ty, f, use_absolute, cx)?;
1076 fmt_type(&self.for_, f, use_absolute, cx)?;
1079 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
1085 impl clean::Arguments {
1086 crate fn print<'a, 'tcx: 'a>(
1088 cx: &'a Context<'tcx>,
1089 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1090 display_fn(move |f| {
1091 for (i, input) in self.values.iter().enumerate() {
1092 if !input.name.is_empty() {
1093 write!(f, "{}: ", input.name)?;
1096 write!(f, "{:#}", input.type_.print(cx))?;
1098 write!(f, "{}", input.type_.print(cx))?;
1100 if i + 1 < self.values.len() {
1109 impl clean::FnRetTy {
1110 crate fn print<'a, 'tcx: 'a>(
1112 cx: &'a Context<'tcx>,
1113 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1114 display_fn(move |f| match self {
1115 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1116 clean::Return(ty) if f.alternate() => {
1117 write!(f, " -> {:#}", ty.print(cx))
1119 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
1120 clean::DefaultReturn => Ok(()),
1125 impl clean::BareFunctionDecl {
1126 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1128 cx: &'a Context<'tcx>,
1129 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1130 display_fn(move |f| {
1131 if !self.generic_params.is_empty() {
1135 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1144 impl clean::FnDecl {
1145 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
1147 cx: &'a Context<'tcx>,
1148 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1149 display_fn(move |f| {
1150 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1154 "({args:#}{ellipsis}){arrow:#}",
1155 args = self.inputs.print(cx),
1156 ellipsis = ellipsis,
1157 arrow = self.output.print(cx)
1162 "({args}{ellipsis}){arrow}",
1163 args = self.inputs.print(cx),
1164 ellipsis = ellipsis,
1165 arrow = self.output.print(cx)
1171 /// * `header_len`: The length of the function header and name. In other words, the number of
1172 /// characters in the function declaration up to but not including the parentheses.
1173 /// <br>Used to determine line-wrapping.
1174 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1176 /// * `asyncness`: Whether the function is async or not.
1177 crate fn full_print<'a, 'tcx: 'a>(
1181 asyncness: hir::IsAsync,
1182 cx: &'a Context<'tcx>,
1183 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1184 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1187 fn inner_full_print(
1191 asyncness: hir::IsAsync,
1192 f: &mut fmt::Formatter<'_>,
1195 let amp = if f.alternate() { "&" } else { "&" };
1196 let mut args = Buffer::html();
1197 let mut args_plain = Buffer::new();
1198 for (i, input) in self.inputs.values.iter().enumerate() {
1200 args.push_str("<br>");
1203 if let Some(selfty) = input.to_self() {
1205 clean::SelfValue => {
1206 args.push_str("self");
1207 args_plain.push_str("self");
1209 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1210 write!(args, "{}{} {}self", amp, lt.print(), mtbl.print_with_space());
1211 write!(args_plain, "&{} {}self", lt.print(), mtbl.print_with_space());
1213 clean::SelfBorrowed(None, mtbl) => {
1214 write!(args, "{}{}self", amp, mtbl.print_with_space());
1215 write!(args_plain, "&{}self", mtbl.print_with_space());
1217 clean::SelfExplicit(ref typ) => {
1219 write!(args, "self: {:#}", typ.print(cx));
1221 write!(args, "self: {}", typ.print(cx));
1223 write!(args_plain, "self: {:#}", typ.print(cx));
1228 args.push_str(" <br>");
1229 args_plain.push_str(" ");
1232 args.push_str("const ");
1233 args_plain.push_str("const ");
1235 if !input.name.is_empty() {
1236 write!(args, "{}: ", input.name);
1237 write!(args_plain, "{}: ", input.name);
1241 write!(args, "{:#}", input.type_.print(cx));
1243 write!(args, "{}", input.type_.print(cx));
1245 write!(args_plain, "{:#}", input.type_.print(cx));
1247 if i + 1 < self.inputs.values.len() {
1249 args_plain.push_str(",");
1253 let mut args_plain = format!("({})", args_plain.into_inner());
1254 let mut args = args.into_inner();
1256 if self.c_variadic {
1257 args.push_str(",<br> ...");
1258 args_plain.push_str(", ...");
1262 let arrow = if let hir::IsAsync::Async = asyncness {
1263 let output = self.sugared_async_return_type();
1264 arrow_plain = format!("{:#}", output.print(cx));
1265 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1267 arrow_plain
= format
!("{:#}", self.output
.print(cx
));
1268 if f
.alternate() { arrow_plain.clone() }
else { format!("{}
", self.output.print(cx)) }
1271 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1272 let output = if declaration_len > 80 {
1273 let full_pad = format!("<br
>{}
", " 
;".repeat(indent + 4));
1274 let close_pad = format!("<br
>{}
", " 
;".repeat(indent));
1276 "({args}{close}
){arrow}
",
1277 args = args.replace("<br
>", &full_pad),
1282 format!("({args}
){arrow}
", args = args.replace("<br
>", ""), arrow = arrow)
1286 write!(f, "{}
", output.replace("<br
>", "\n"))
1288 write!(f, "{}
", output)
1293 impl clean::Visibility {
1294 crate fn print_with_space<'a, 'tcx: 'a>(
1297 cx: &'a Context<'tcx>,
1298 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1299 let to_print = match self {
1300 clean::Public => "pub ".to_owned(),
1301 clean::Inherited => String::new(),
1302 clean::Visibility::Restricted(vis_did) => {
1303 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1304 // However, rustdoc currently never displays a module's
1305 // visibility, so it shouldn't matter.
1306 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1308 if vis_did.is_crate_root() {
1309 "pub(crate) ".to_owned()
1310 } else if parent_module == Some(vis_did) {
1311 // `pub(in foo)` where `foo` is the parent module
1312 // is the same as no visibility modifier
1314 } else if parent_module
1315 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1319 "pub(super) ".to_owned()
1321 let path = cx.tcx().def_path(vis_did);
1322 debug!("path
={:?}
", path);
1323 // modified from `resolved_path()` to work with `DefPathData`
1324 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1325 let anchor = anchor(vis_did, last_name, cx).to_string();
1327 let mut s = "pub(in ".to_owned();
1328 for seg in &path.data[..path.data.len() - 1] {
1329 s.push_str(&format!("{}
::", seg.data.get_opt_name().unwrap()));
1331 s.push_str(&format!("{}
) ", anchor));
1336 display_fn(move |f| f.write_str(&to_print))
1339 /// This function is the same as print_with_space, except that it renders no links.
1340 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1342 crate fn to_src_with_space<'a, 'tcx: 'a>(
1346 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1347 let to_print = match self {
1348 clean::Public => "pub ".to_owned(),
1349 clean::Inherited => String::new(),
1350 clean::Visibility::Restricted(vis_did) => {
1351 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1352 // However, rustdoc currently never displays a module's
1353 // visibility, so it shouldn't matter.
1354 let parent_module = find_nearest_parent_module(tcx, item_did);
1356 if vis_did.is_crate_root() {
1357 "pub(crate) ".to_owned()
1358 } else if parent_module == Some(vis_did) {
1359 // `pub(in foo)` where `foo` is the parent module
1360 // is the same as no visibility modifier
1362 } else if parent_module
1363 .map(|parent| find_nearest_parent_module(tcx, parent))
1367 "pub(super) ".to_owned()
1369 format!("pub(in {}
) ", tcx.def_path_str(vis_did))
1373 display_fn(move |f| f.write_str(&to_print))
1377 crate trait PrintWithSpace {
1378 fn print_with_space(&self) -> &str;
1381 impl PrintWithSpace for hir::Unsafety {
1382 fn print_with_space(&self) -> &str {
1384 hir::Unsafety::Unsafe => "unsafe ",
1385 hir::Unsafety::Normal => "",
1390 impl PrintWithSpace for hir::IsAsync {
1391 fn print_with_space(&self) -> &str {
1393 hir::IsAsync::Async => "async
",
1394 hir::IsAsync::NotAsync => "",
1399 impl PrintWithSpace for hir::Mutability {
1400 fn print_with_space(&self) -> &str {
1402 hir::Mutability::Not => "",
1403 hir::Mutability::Mut => "mut ",
1408 crate fn print_constness_with_space(c: &hir::Constness, s: Option<ConstStability>) -> &'static str {
1410 // const stable or when feature(staged_api) is not set
1412 hir::Constness::Const,
1413 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1415 | (hir::Constness::Const, None) => "const ",
1416 // const unstable or not const
1421 impl clean::Import {
1422 crate fn print<'a, 'tcx: 'a>(
1424 cx: &'a Context<'tcx>,
1425 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1426 display_fn(move |f| match self.kind {
1427 clean::ImportKind::Simple(name) => {
1428 if name == self.source.path.last() {
1429 write!(f, "use {}
;", self.source.print(cx))
1431 write!(f, "use {}
as {}
;", self.source.print(cx), name)
1434 clean::ImportKind::Glob => {
1435 if self.source.path.segments.is_empty() {
1438 write!(f, "use {}
::*;", self.source.print(cx))
1445 impl clean::ImportSource {
1446 crate fn print<'a, 'tcx: 'a>(
1448 cx: &'a Context<'tcx>,
1449 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1450 display_fn(move |f| match self.did {
1451 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1453 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1454 write!(f, "{}
::", seg.name)?;
1456 let name = self.path.last();
1457 if let hir::def::Res::PrimTy(p) = self.path.res {
1458 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1460 write!(f, "{}
", name)?;
1468 impl clean::TypeBinding {
1469 crate fn print<'a, 'tcx: 'a>(
1471 cx: &'a Context<'tcx>,
1472 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1473 display_fn(move |f| {
1474 f.write_str(self.assoc.name.as_str())?;
1476 write!(f, "{:#}
", self.assoc.args.print(cx))?;
1478 write!(f, "{}
", self.assoc.args.print(cx))?;
1481 clean::TypeBindingKind::Equality { ref term } => {
1483 write!(f, " = {:#}
", term.print(cx))?;
1485 write!(f, " = {}
", term.print(cx))?;
1488 clean::TypeBindingKind::Constraint { ref bounds } => {
1489 if !bounds.is_empty() {
1491 write!(f, ": {:#}
", print_generic_bounds(bounds, cx))?;
1493 write!(f, ": 
;{}
", print_generic_bounds(bounds, cx))?;
1503 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1504 display_fn(move |f| {
1505 let quot = if f.alternate() { "\"" } else { """ };
1507 Abi::Rust => Ok(()),
1508 abi => write!(f, "extern {0}{1}{0}
", quot, abi.name()),
1513 crate fn print_default_space<'a>(v: bool) -> &'a str {
1514 if v { "default " } else { "" }
1517 impl clean::GenericArg {
1518 crate fn print<'a, 'tcx: 'a>(
1520 cx: &'a Context<'tcx>,
1521 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1522 display_fn(move |f| match self {
1523 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1524 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1525 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1526 clean::GenericArg::Infer => fmt::Display::fmt("_
", f),
1531 impl clean::types::Term {
1532 crate fn print<'a, 'tcx: 'a>(
1534 cx: &'a Context<'tcx>,
1535 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1537 clean::types::Term::Type(ty) => ty.print(cx),
1543 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1544 struct WithFormatter<F>(Cell<Option<F>>);
1546 impl<F> fmt::Display for WithFormatter<F>
1548 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1551 (self.0.take()).unwrap()(f)
1555 WithFormatter(Cell::new(Some(f)))