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_data_structures::captures::Captures;
13 use rustc_data_structures::fx::FxHashSet;
15 use rustc_hir::def_id::DefId;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_span::def_id::CRATE_DEF_INDEX;
18 use rustc_target::spec::abi::Abi;
21 self, utils::find_nearest_parent_module, ExternalCrate, FakeDefId, GetDefId, PrimitiveType,
23 use crate::formats::item_type::ItemType;
24 use crate::html::escape::Escape;
25 use crate::html::render::cache::ExternalLocation;
26 use crate::html::render::Context;
29 fn print(self, buffer: &mut Buffer);
34 F: FnOnce(&mut Buffer),
36 fn print(self, buffer: &mut Buffer) {
41 impl Print for String {
42 fn print(self, buffer: &mut Buffer) {
43 buffer.write_str(&self);
47 impl Print for &'_ str {
48 fn print(self, buffer: &mut Buffer) {
49 buffer.write_str(self);
53 #[derive(Debug, Clone)]
60 crate fn empty_from(v: &Buffer) -> Buffer {
61 Buffer { for_html: v.for_html, buffer: String::new() }
64 crate fn html() -> Buffer {
65 Buffer { for_html: true, buffer: String::new() }
68 crate fn new() -> Buffer {
69 Buffer { for_html: false, buffer: String::new() }
72 crate fn is_empty(&self) -> bool {
73 self.buffer.is_empty()
76 crate fn into_inner(self) -> String {
80 crate fn insert_str(&mut self, idx: usize, s: &str) {
81 self.buffer.insert_str(idx, s);
84 crate fn push_str(&mut self, s: &str) {
85 self.buffer.push_str(s);
88 crate fn push_buffer(&mut self, other: Buffer) {
89 self.buffer.push_str(&other.buffer);
92 // Intended for consumption by write! and writeln! (std::fmt) but without
93 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
95 crate fn write_str(&mut self, s: &str) {
96 self.buffer.push_str(s);
99 // Intended for consumption by write! and writeln! (std::fmt) but without
100 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
102 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
104 self.buffer.write_fmt(v).unwrap();
107 crate fn to_display<T: Print>(mut self, t: T) -> String {
112 crate fn is_for_html(&self) -> bool {
116 crate fn reserve(&mut self, additional: usize) {
117 self.buffer.reserve(additional)
121 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
122 display_fn(move |f| {
123 for (i, item) in items.enumerate() {
127 fmt::Display::fmt(&item, f)?;
133 crate fn print_generic_bounds<'a, 'tcx: 'a>(
134 bounds: &'a [clean::GenericBound],
135 cx: &'a Context<'tcx>,
136 ) -> impl fmt::Display + 'a + Captures<'tcx> {
137 display_fn(move |f| {
138 let mut bounds_dup = FxHashSet::default();
141 bounds.iter().filter(|b| bounds_dup.insert(b.print(cx).to_string())).enumerate()
146 fmt::Display::fmt(&bound.print(cx), f)?;
152 impl clean::GenericParamDef {
153 crate fn print<'a, 'tcx: 'a>(
155 cx: &'a Context<'tcx>,
156 ) -> impl fmt::Display + 'a + Captures<'tcx> {
157 display_fn(move |f| match self.kind {
158 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
159 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
160 f.write_str(&*self.name.as_str())?;
162 if !bounds.is_empty() {
164 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
166 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
170 if let Some(ref ty) = default {
172 write!(f, " = {:#}", ty.print(cx))?;
174 write!(f, " = {}", ty.print(cx))?;
180 clean::GenericParamDefKind::Const { ref ty, .. } => {
182 write!(f, "const {}: {:#}", self.name, ty.print(cx))
184 write!(f, "const {}: {}", self.name, ty.print(cx))
191 impl clean::Generics {
192 crate fn print<'a, 'tcx: 'a>(
194 cx: &'a Context<'tcx>,
195 ) -> impl fmt::Display + 'a + Captures<'tcx> {
196 display_fn(move |f| {
198 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
199 if real_params.is_empty() {
203 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
205 write!(f, "<{}>", comma_sep(real_params.iter().map(|g| g.print(cx))))
211 /// * The Generics from which to emit a where-clause.
212 /// * The number of spaces to indent each line with.
213 /// * Whether the where-clause needs to add a comma and newline after the last bound.
214 crate fn print_where_clause<'a, 'tcx: 'a>(
215 gens: &'a clean::Generics,
216 cx: &'a Context<'tcx>,
219 ) -> impl fmt::Display + 'a + Captures<'tcx> {
220 display_fn(move |f| {
221 if gens.where_predicates.is_empty() {
224 let mut clause = String::new();
226 clause.push_str(" where");
229 clause.push_str(" <span class=\"where fmt-newline\">where");
231 clause.push_str(" <span class=\"where\">where");
234 for (i, pred) in gens.where_predicates.iter().enumerate() {
238 clause.push_str("<br>");
242 clean::WherePredicate::BoundPredicate { ty, bounds } => {
245 clause.push_str(&format!(
248 print_generic_bounds(bounds, cx)
251 clause.push_str(&format!(
254 print_generic_bounds(bounds, cx)
258 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
259 clause.push_str(&format!(
264 .map(|b| b.print(cx).to_string())
269 clean::WherePredicate::EqPredicate { lhs, rhs } => {
271 clause.push_str(&format!("{:#} == {:#}", lhs.print(cx), rhs.print(cx),));
273 clause.push_str(&format!("{} == {}", lhs.print(cx), rhs.print(cx),));
278 if i < gens.where_predicates.len() - 1 || end_newline {
284 // add a space so stripping <br> tags and breaking spaces still renders properly
288 clause.push_str(" ");
293 clause.push_str("</span>");
294 let padding = " ".repeat(indent + 4);
295 clause = clause.replace("<br>", &format!("<br>{}", padding));
296 clause.insert_str(0, &" ".repeat(indent.saturating_sub(1)));
298 clause.insert_str(0, "<br>");
301 write!(f, "{}", clause)
305 impl clean::Lifetime {
306 crate fn print(&self) -> impl fmt::Display + '_ {
311 impl clean::Constant {
312 crate fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
313 let expr = self.expr(tcx);
316 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
322 impl clean::PolyTrait {
323 fn print<'a, 'tcx: 'a>(
325 cx: &'a Context<'tcx>,
326 ) -> impl fmt::Display + 'a + Captures<'tcx> {
327 display_fn(move |f| {
328 if !self.generic_params.is_empty() {
333 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
339 comma_sep(self.generic_params.iter().map(|g| g.print(cx)))
344 write!(f, "{:#}", self.trait_.print(cx))
346 write!(f, "{}", self.trait_.print(cx))
352 impl clean::GenericBound {
353 crate fn print<'a, 'tcx: 'a>(
355 cx: &'a Context<'tcx>,
356 ) -> impl fmt::Display + 'a + Captures<'tcx> {
357 display_fn(move |f| match self {
358 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
359 clean::GenericBound::TraitBound(ty, modifier) => {
360 let modifier_str = match modifier {
361 hir::TraitBoundModifier::None => "",
362 hir::TraitBoundModifier::Maybe => "?",
363 hir::TraitBoundModifier::MaybeConst => "?const",
366 write!(f, "{}{:#}", modifier_str, ty.print(cx))
368 write!(f, "{}{}", modifier_str, ty.print(cx))
375 impl clean::GenericArgs {
376 fn print<'a, 'tcx: 'a>(
378 cx: &'a Context<'tcx>,
379 ) -> impl fmt::Display + 'a + Captures<'tcx> {
380 display_fn(move |f| {
382 clean::GenericArgs::AngleBracketed { args, bindings } => {
383 if !args.is_empty() || !bindings.is_empty() {
387 f.write_str("<")?;
389 let mut comma = false;
396 write!(f, "{:#}", arg.print(cx))?;
398 write!(f, "{}", arg.print(cx))?;
401 for binding in bindings {
407 write!(f, "{:#}", binding.print(cx))?;
409 write!(f, "{}", binding.print(cx))?;
415 f.write_str(">")?;
419 clean::GenericArgs::Parenthesized { inputs, output } => {
421 let mut comma = false;
428 write!(f, "{:#}", ty.print(cx))?;
430 write!(f, "{}", ty.print(cx))?;
434 if let Some(ref ty) = *output {
436 write!(f, " -> {:#}", ty.print(cx))?;
438 write!(f, " -> {}", ty.print(cx))?;
448 crate fn href(did: DefId, cx: &Context<'_>) -> Option<(String, ItemType, Vec<String>)> {
449 let cache = &cx.cache();
450 let relative_to = &cx.current;
451 fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
452 if shortty == ItemType::Module { &fqp[..] } else { &fqp[..fqp.len() - 1] }
455 if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
459 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
460 Some(&(ref fqp, shortty)) => (fqp, shortty, {
461 let module_fqp = to_module_fqp(shortty, fqp);
462 href_relative_parts(module_fqp, relative_to)
465 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
466 let module_fqp = to_module_fqp(shortty, fqp);
470 match cache.extern_locations[&did.krate] {
471 ExternalLocation::Remote(ref s) => {
472 let s = s.trim_end_matches('/');
473 let mut s = vec![&s[..]];
474 s.extend(module_fqp[..].iter().map(String::as_str));
477 ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
478 ExternalLocation::Unknown => return None,
483 let last = &fqp.last().unwrap()[..];
486 ItemType::Module => {
487 url_parts.push("index.html");
490 filename = format!("{}.{}.html", shortty.as_str(), last);
491 url_parts.push(&filename);
494 Some((url_parts.join("/"), shortty, fqp.to_vec()))
497 /// Both paths should only be modules.
498 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
499 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
500 crate fn href_relative_parts<'a>(fqp: &'a [String], relative_to_fqp: &'a [String]) -> Vec<&'a str> {
501 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
502 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
504 let dissimilar_part_count = relative_to_fqp.len() - i;
505 let fqp_module = fqp[i..fqp.len()].iter().map(String::as_str);
506 return iter::repeat("..").take(dissimilar_part_count).chain(fqp_module).collect();
509 // e.g. linking to std::sync::atomic from std::sync
510 if relative_to_fqp.len() < fqp.len() {
511 fqp[relative_to_fqp.len()..fqp.len()].iter().map(String::as_str).collect()
512 // e.g. linking to std::sync from std::sync::atomic
513 } else if fqp.len() < relative_to_fqp.len() {
514 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
515 iter::repeat("..").take(dissimilar_part_count).collect()
516 // linking to the same module
522 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
523 /// rendering function with the necessary arguments for linking to a local path.
524 fn resolved_path<'a, 'cx: 'a>(
525 w: &mut fmt::Formatter<'_>,
530 cx: &'cx Context<'_>,
532 let last = path.segments.last().unwrap();
535 for seg in &path.segments[..path.segments.len() - 1] {
536 write!(w, "{}::", seg.name)?;
540 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
542 let path = if use_absolute {
543 if let Some((_, _, fqp)) = href(did, cx) {
546 fqp[..fqp.len() - 1].join("::"),
547 anchor(did, fqp.last().unwrap(), cx)
550 last.name.to_string()
553 anchor(did, &*last.name.as_str(), cx).to_string()
555 write!(w, "{}{}", path, last.args.print(cx))?;
561 f: &mut fmt::Formatter<'_>,
562 prim: clean::PrimitiveType,
567 let mut needs_termination = false;
569 match m.primitive_locations.get(&prim) {
570 Some(&def_id) if def_id.is_local() => {
571 let len = cx.current.len();
572 let len = if len == 0 { 0 } else { len - 1 };
575 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
579 needs_termination = true;
583 let loc = match m.extern_locations[&def_id.krate] {
584 ExternalLocation::Remote(ref s) => {
586 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
587 Some(vec![s.trim_end_matches('/'), &cname_str[..]])
589 ExternalLocation::Local => {
591 ExternalCrate { crate_num: def_id.krate }.name(cx.tcx()).as_str();
592 Some(if cx.current.first().map(|x| &x[..]) == Some(&cname_str[..]) {
593 iter::repeat("..").take(cx.current.len() - 1).collect()
595 let cname = iter::once(&cname_str[..]);
596 iter::repeat("..").take(cx.current.len()).chain(cname).collect()
599 ExternalLocation::Unknown => None,
601 if let Some(loc) = loc {
604 "<a class=\"primitive\" href=\"{}/primitive.{}.html\">",
608 needs_termination = true;
614 write!(f, "{}", name)?;
615 if needs_termination {
621 /// Helper to render type parameters
622 fn tybounds<'a, 'tcx: 'a>(
623 param_names: &'a Option<Vec<clean::GenericBound>>,
624 cx: &'a Context<'tcx>,
625 ) -> impl fmt::Display + 'a + Captures<'tcx> {
626 display_fn(move |f| match *param_names {
627 Some(ref params) => {
628 for param in params {
630 fmt::Display::fmt(¶m.print(cx), f)?;
638 crate fn anchor<'a, 'cx: 'a>(
641 cx: &'cx Context<'_>,
642 ) -> impl fmt::Display + 'a {
643 let parts = href(did.into(), cx);
644 display_fn(move |f| {
645 if let Some((url, short_ty, fqp)) = parts {
648 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
656 write!(f, "{}", text)
663 f: &mut fmt::Formatter<'_>,
665 cx: &'cx Context<'_>,
667 debug!("fmt_type(t = {:?})", t);
670 clean::Generic(name) => write!(f, "{}", name),
671 clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
672 if param_names.is_some() {
673 f.write_str("dyn ")?;
675 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
676 resolved_path(f, did, path, is_generic, use_absolute, cx)?;
677 fmt::Display::fmt(&tybounds(param_names, cx), f)
679 clean::Infer => write!(f, "_"),
680 clean::Primitive(prim) => primitive_link(f, prim, &*prim.as_sym().as_str(), cx),
681 clean::BareFunction(ref decl) => {
686 decl.print_hrtb_with_space(cx),
687 decl.unsafety.print_with_space(),
688 print_abi_with_space(decl.abi),
695 decl.print_hrtb_with_space(cx),
696 decl.unsafety.print_with_space(),
697 print_abi_with_space(decl.abi)
699 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
700 write!(f, "{}", decl.decl.print(cx))
703 clean::Tuple(ref typs) => {
705 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
707 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
708 // Carry `f.alternate()` into this display w/o branching manually.
709 fmt::Display::fmt(&one.print(cx), f)?;
710 primitive_link(f, PrimitiveType::Tuple, ",)", cx)
713 primitive_link(f, PrimitiveType::Tuple, "(", cx)?;
714 for (i, item) in many.iter().enumerate() {
718 fmt::Display::fmt(&item.print(cx), f)?;
720 primitive_link(f, PrimitiveType::Tuple, ")", cx)
724 clean::Slice(ref t) => {
725 primitive_link(f, PrimitiveType::Slice, "[", cx)?;
726 fmt::Display::fmt(&t.print(cx), f)?;
727 primitive_link(f, PrimitiveType::Slice, "]", cx)
729 clean::Array(ref t, ref n) => {
730 primitive_link(f, PrimitiveType::Array, "[", cx)?;
731 fmt::Display::fmt(&t.print(cx), f)?;
733 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n), cx)
735 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)), cx)
738 clean::Never => primitive_link(f, PrimitiveType::Never, "!", cx),
739 clean::RawPointer(m, ref t) => {
741 hir::Mutability::Mut => "mut",
742 hir::Mutability::Not => "const",
745 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
749 clean::PrimitiveType::RawPointer,
750 &format!("*{} {:#}", m, t.print(cx)),
756 clean::PrimitiveType::RawPointer,
757 &format!("*{} {}", m, t.print(cx)),
763 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
764 fmt::Display::fmt(&t.print(cx), f)
768 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
770 Some(l) => format!("{} ", l.print()),
773 let m = mutability.print_with_space();
774 let amp = if f.alternate() { "&".to_string() } else { "&".to_string() };
776 clean::Slice(ref bt) => {
777 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
779 clean::Generic(_) => {
783 PrimitiveType::Slice,
784 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print(cx)),
790 PrimitiveType::Slice,
791 &format!("{}{}{}[{}]", amp, lt, m, bt.print(cx)),
799 PrimitiveType::Slice,
800 &format!("{}{}{}[", amp, lt, m),
804 write!(f, "{:#}", bt.print(cx))?;
806 write!(f, "{}", bt.print(cx))?;
808 primitive_link(f, PrimitiveType::Slice, "]", cx)
812 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
813 write!(f, "{}{}{}(", amp, lt, m)?;
814 fmt_type(&ty, f, use_absolute, cx)?;
817 clean::Generic(..) => {
820 PrimitiveType::Reference,
821 &format!("{}{}{}", amp, lt, m),
824 fmt_type(&ty, f, use_absolute, cx)
827 write!(f, "{}{}{}", amp, lt, m)?;
828 fmt_type(&ty, f, use_absolute, cx)
832 clean::ImplTrait(ref bounds) => {
834 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
836 write!(f, "impl {}", print_generic_bounds(bounds, cx))
839 clean::QPath { ref name, ref self_type, ref trait_, ref self_def_id } => {
840 let should_show_cast = match *trait_ {
841 box clean::ResolvedPath { ref path, .. } => {
842 !path.segments.is_empty()
844 .zip(trait_.def_id())
845 .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
850 if should_show_cast {
851 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
853 write!(f, "{:#}::", self_type.print(cx))?
856 if should_show_cast {
857 write!(f, "<{} as {}>::", self_type.print(cx), trait_.print(cx))?
859 write!(f, "{}::", self_type.print(cx))?
863 // It's pretty unsightly to look at `<A as B>::C` in output, and
864 // we've got hyperlinking on our side, so try to avoid longer
865 // notation as much as possible by making `C` a hyperlink to trait
866 // `B` to disambiguate.
868 // FIXME: this is still a lossy conversion and there should probably
869 // be a better way of representing this in general? Most of
870 // the ugliness comes from inlining across crates where
871 // everything comes in as a fully resolved QPath (hard to
873 box clean::ResolvedPath { did, ref param_names, .. } => {
874 match href(did.into(), cx) {
875 Some((ref url, _, ref path)) if !f.alternate() => {
878 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
879 title=\"type {path}::{name}\">{name}</a>",
881 shortty = ItemType::AssocType,
883 path = path.join("::")
886 _ => write!(f, "{}", name)?,
889 // FIXME: `param_names` are not rendered, and this seems bad?
893 _ => write!(f, "{}", name),
900 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
902 cx: &'a Context<'tcx>,
903 ) -> impl fmt::Display + 'b + Captures<'tcx> {
904 display_fn(move |f| fmt_type(self, f, false, cx))
909 crate fn print<'a, 'tcx: 'a>(
912 cx: &'a Context<'tcx>,
913 ) -> impl fmt::Display + 'a + Captures<'tcx> {
914 display_fn(move |f| {
916 write!(f, "impl{:#} ", self.generics.print(cx))?;
918 write!(f, "impl{} ", self.generics.print(cx))?;
921 if let Some(ref ty) = self.trait_ {
922 if self.negative_polarity {
925 fmt::Display::fmt(&ty.print(cx), f)?;
929 if let Some(ref ty) = self.blanket_impl {
930 fmt_type(ty, f, use_absolute, cx)?;
932 fmt_type(&self.for_, f, use_absolute, cx)?;
935 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, true), f)?;
941 impl clean::Arguments {
942 crate fn print<'a, 'tcx: 'a>(
944 cx: &'a Context<'tcx>,
945 ) -> impl fmt::Display + 'a + Captures<'tcx> {
946 display_fn(move |f| {
947 for (i, input) in self.values.iter().enumerate() {
948 if !input.name.is_empty() {
949 write!(f, "{}: ", input.name)?;
952 write!(f, "{:#}", input.type_.print(cx))?;
954 write!(f, "{}", input.type_.print(cx))?;
956 if i + 1 < self.values.len() {
965 impl clean::FnRetTy {
966 crate fn print<'a, 'tcx: 'a>(
968 cx: &'a Context<'tcx>,
969 ) -> impl fmt::Display + 'a + Captures<'tcx> {
970 display_fn(move |f| match self {
971 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
972 clean::Return(ty) if f.alternate() => {
973 write!(f, " -> {:#}", ty.print(cx))
975 clean::Return(ty) => write!(f, " -> {}", ty.print(cx)),
976 clean::DefaultReturn => Ok(()),
981 impl clean::BareFunctionDecl {
982 fn print_hrtb_with_space<'a, 'tcx: 'a>(
984 cx: &'a Context<'tcx>,
985 ) -> impl fmt::Display + 'a + Captures<'tcx> {
986 display_fn(move |f| {
987 if !self.generic_params.is_empty() {
988 write!(f, "for<{}> ", comma_sep(self.generic_params.iter().map(|g| g.print(cx))))
997 crate fn print<'b, 'a: 'b, 'tcx: 'a>(
999 cx: &'a Context<'tcx>,
1000 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1001 display_fn(move |f| {
1002 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1006 "({args:#}{ellipsis}){arrow:#}",
1007 args = self.inputs.print(cx),
1008 ellipsis = ellipsis,
1009 arrow = self.output.print(cx)
1014 "({args}{ellipsis}){arrow}",
1015 args = self.inputs.print(cx),
1016 ellipsis = ellipsis,
1017 arrow = self.output.print(cx)
1023 /// * `header_len`: The length of the function header and name. In other words, the number of
1024 /// characters in the function declaration up to but not including the parentheses.
1025 /// <br>Used to determine line-wrapping.
1026 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1028 /// * `asyncness`: Whether the function is async or not.
1029 crate fn full_print<'a, 'tcx: 'a>(
1033 asyncness: hir::IsAsync,
1034 cx: &'a Context<'tcx>,
1035 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1036 display_fn(move |f| self.inner_full_print(header_len, indent, asyncness, f, cx))
1039 fn inner_full_print(
1043 asyncness: hir::IsAsync,
1044 f: &mut fmt::Formatter<'_>,
1047 let amp = if f.alternate() { "&" } else { "&" };
1048 let mut args = String::new();
1049 let mut args_plain = String::new();
1050 for (i, input) in self.inputs.values.iter().enumerate() {
1052 args.push_str("<br>");
1055 if let Some(selfty) = input.to_self() {
1057 clean::SelfValue => {
1058 args.push_str("self");
1059 args_plain.push_str("self");
1061 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1062 args.push_str(&format!(
1066 mtbl.print_with_space()
1068 args_plain.push_str(&format!(
1071 mtbl.print_with_space()
1074 clean::SelfBorrowed(None, mtbl) => {
1075 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1076 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1078 clean::SelfExplicit(ref typ) => {
1080 args.push_str(&format!("self: {:#}", typ.print(cx)));
1082 args.push_str(&format!("self: {}", typ.print(cx)));
1084 args_plain.push_str(&format!("self: {:#}", typ.print(cx)));
1089 args.push_str(" <br>");
1090 args_plain.push(' ');
1092 if !input.name.is_empty() {
1093 args.push_str(&format!("{}: ", input.name));
1094 args_plain.push_str(&format!("{}: ", input.name));
1098 args.push_str(&format!("{:#}", input.type_.print(cx)));
1100 args.push_str(&input.type_.print(cx).to_string());
1102 args_plain.push_str(&format!("{:#}", input.type_.print(cx)));
1104 if i + 1 < self.inputs.values.len() {
1106 args_plain.push(',');
1110 let mut args_plain = format!("({})", args_plain);
1112 if self.c_variadic {
1113 args.push_str(",<br> ...");
1114 args_plain.push_str(", ...");
1118 let arrow = if let hir::IsAsync::Async = asyncness {
1119 let output = self.sugared_async_return_type();
1120 arrow_plain = format!("{:#}", output.print(cx));
1121 if f.alternate() { arrow_plain.clone() } else { format!("{}", output.print(cx)) }
1123 arrow_plain = format!("{:#}", self.output.print(cx));
1124 if f.alternate() { arrow_plain.clone() } else { format!("{}", self.output.print(cx)) }
1127 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1128 let output = if declaration_len > 80 {
1129 let full_pad = format!("<br>{}", " ".repeat(indent + 4));
1130 let close_pad = format!("<br>{}", " ".repeat(indent));
1132 "({args}{close}){arrow}",
1133 args = args.replace("<br>", &full_pad),
1138 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1142 write!(f, "{}", output.replace("<br>", "\n"))
1144 write!(f, "{}", output)
1149 impl clean::Visibility {
1150 crate fn print_with_space<'a, 'tcx: 'a>(
1152 item_did: FakeDefId,
1153 cx: &'a Context<'tcx>,
1154 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1155 let to_print = match self {
1156 clean::Public => "pub ".to_owned(),
1157 clean::Inherited => String::new(),
1158 clean::Visibility::Restricted(vis_did) => {
1159 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1160 // However, rustdoc currently never displays a module's
1161 // visibility, so it shouldn't matter.
1162 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_real());
1164 if vis_did.index == CRATE_DEF_INDEX {
1165 "pub(crate) ".to_owned()
1166 } else if parent_module == Some(vis_did) {
1167 // `pub(in foo)` where `foo` is the parent module
1168 // is the same as no visibility modifier
1170 } else if parent_module
1171 .map(|parent| find_nearest_parent_module(cx.tcx(), parent))
1175 "pub(super) ".to_owned()
1177 let path = cx.tcx().def_path(vis_did);
1178 debug!("path={:?}", path);
1179 // modified from `resolved_path()` to work with `DefPathData`
1180 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1181 let anchor = anchor(vis_did, &last_name.as_str(), cx).to_string();
1183 let mut s = "pub(in ".to_owned();
1184 for seg in &path.data[..path.data.len() - 1] {
1185 s.push_str(&format!("{}::", seg.data.get_opt_name().unwrap()));
1187 s.push_str(&format!("{}) ", anchor));
1192 display_fn(move |f| f.write_str(&to_print))
1195 /// This function is the same as print_with_space, except that it renders no links.
1196 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1198 crate fn to_src_with_space<'a, 'tcx: 'a>(
1202 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1203 let to_print = match self {
1204 clean::Public => "pub ".to_owned(),
1205 clean::Inherited => String::new(),
1206 clean::Visibility::Restricted(vis_did) => {
1207 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1208 // However, rustdoc currently never displays a module's
1209 // visibility, so it shouldn't matter.
1210 let parent_module = find_nearest_parent_module(tcx, item_did);
1212 if vis_did.index == CRATE_DEF_INDEX {
1213 "pub(crate) ".to_owned()
1214 } else if parent_module == Some(vis_did) {
1215 // `pub(in foo)` where `foo` is the parent module
1216 // is the same as no visibility modifier
1218 } else if parent_module
1219 .map(|parent| find_nearest_parent_module(tcx, parent))
1223 "pub(super) ".to_owned()
1225 format!("pub(in {}) ", tcx.def_path_str(vis_did))
1229 display_fn(move |f| f.write_str(&to_print))
1233 crate trait PrintWithSpace {
1234 fn print_with_space(&self) -> &str;
1237 impl PrintWithSpace for hir::Unsafety {
1238 fn print_with_space(&self) -> &str {
1240 hir::Unsafety::Unsafe => "unsafe ",
1241 hir::Unsafety::Normal => "",
1246 impl PrintWithSpace for hir::Constness {
1247 fn print_with_space(&self) -> &str {
1249 hir::Constness::Const => "const ",
1250 hir::Constness::NotConst => "",
1255 impl PrintWithSpace for hir::IsAsync {
1256 fn print_with_space(&self) -> &str {
1258 hir::IsAsync::Async => "async ",
1259 hir::IsAsync::NotAsync => "",
1264 impl PrintWithSpace for hir::Mutability {
1265 fn print_with_space(&self) -> &str {
1267 hir::Mutability::Not => "",
1268 hir::Mutability::Mut => "mut ",
1273 impl clean::Import {
1274 crate fn print<'a, 'tcx: 'a>(
1276 cx: &'a Context<'tcx>,
1277 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1278 display_fn(move |f| match self.kind {
1279 clean::ImportKind::Simple(name) => {
1280 if name == self.source.path.last() {
1281 write!(f, "use {};", self.source.print(cx))
1283 write!(f, "use {} as {};", self.source.print(cx), name)
1286 clean::ImportKind::Glob => {
1287 if self.source.path.segments.is_empty() {
1290 write!(f, "use {}::*;", self.source.print(cx))
1297 impl clean::ImportSource {
1298 crate fn print<'a, 'tcx: 'a>(
1300 cx: &'a Context<'tcx>,
1301 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1302 display_fn(move |f| match self.did {
1303 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1305 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1306 write!(f, "{}::", seg.name)?;
1308 let name = self.path.last_name();
1309 if let hir::def::Res::PrimTy(p) = self.path.res {
1310 primitive_link(f, PrimitiveType::from(p), &*name, cx)?;
1312 write!(f, "{}", name)?;
1320 impl clean::TypeBinding {
1321 crate fn print<'a, 'tcx: 'a>(
1323 cx: &'a Context<'tcx>,
1324 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1325 display_fn(move |f| {
1326 f.write_str(&*self.name.as_str())?;
1328 clean::TypeBindingKind::Equality { ref ty } => {
1330 write!(f, " = {:#}", ty.print(cx))?;
1332 write!(f, " = {}", ty.print(cx))?;
1335 clean::TypeBindingKind::Constraint { ref bounds } => {
1336 if !bounds.is_empty() {
1338 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1340 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1350 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1351 display_fn(move |f| {
1352 let quot = if f.alternate() { "\"" } else { """ };
1354 Abi::Rust => Ok(()),
1355 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1360 crate fn print_default_space<'a>(v: bool) -> &'a str {
1361 if v { "default " } else { "" }
1364 impl clean::GenericArg {
1365 crate fn print<'a, 'tcx: 'a>(
1367 cx: &'a Context<'tcx>,
1368 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1369 display_fn(move |f| match self {
1370 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(<.print(), f),
1371 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1372 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1377 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1378 struct WithFormatter<F>(Cell<Option<F>>);
1380 impl<F> fmt::Display for WithFormatter<F>
1382 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385 (self.0.take()).unwrap()(f)
1389 WithFormatter(Cell::new(Some(f)))