]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/format.rs
9b2fb8582f54f678606b64bc3f247b7fc150e49c
[rustc.git] / src / librustdoc / html / format.rs
1 //! HTML formatting module
2 //!
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.
7
8 use std::borrow::Cow;
9 use std::cell::Cell;
10 use std::fmt;
11
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_hir as hir;
14 use rustc_middle::ty::TyCtxt;
15 use rustc_span::def_id::{DefId, CRATE_DEF_INDEX};
16 use rustc_target::spec::abi::Abi;
17
18 use crate::clean::{self, utils::find_nearest_parent_module, PrimitiveType};
19 use crate::formats::cache::cache;
20 use crate::formats::item_type::ItemType;
21 use crate::html::escape::Escape;
22 use crate::html::render::cache::ExternalLocation;
23 use crate::html::render::CURRENT_DEPTH;
24
25 crate trait Print {
26 fn print(self, buffer: &mut Buffer);
27 }
28
29 impl<F> Print for F
30 where
31 F: FnOnce(&mut Buffer),
32 {
33 fn print(self, buffer: &mut Buffer) {
34 (self)(buffer)
35 }
36 }
37
38 impl Print for String {
39 fn print(self, buffer: &mut Buffer) {
40 buffer.write_str(&self);
41 }
42 }
43
44 impl Print for &'_ str {
45 fn print(self, buffer: &mut Buffer) {
46 buffer.write_str(self);
47 }
48 }
49
50 #[derive(Debug, Clone)]
51 crate struct Buffer {
52 for_html: bool,
53 buffer: String,
54 }
55
56 impl Buffer {
57 crate fn empty_from(v: &Buffer) -> Buffer {
58 Buffer { for_html: v.for_html, buffer: String::new() }
59 }
60
61 crate fn html() -> Buffer {
62 Buffer { for_html: true, buffer: String::new() }
63 }
64
65 crate fn new() -> Buffer {
66 Buffer { for_html: false, buffer: String::new() }
67 }
68
69 crate fn is_empty(&self) -> bool {
70 self.buffer.is_empty()
71 }
72
73 crate fn into_inner(self) -> String {
74 self.buffer
75 }
76
77 crate fn insert_str(&mut self, idx: usize, s: &str) {
78 self.buffer.insert_str(idx, s);
79 }
80
81 crate fn push_str(&mut self, s: &str) {
82 self.buffer.push_str(s);
83 }
84
85 // Intended for consumption by write! and writeln! (std::fmt) but without
86 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
87 // import).
88 crate fn write_str(&mut self, s: &str) {
89 self.buffer.push_str(s);
90 }
91
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
94 // import).
95 crate fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
96 use fmt::Write;
97 self.buffer.write_fmt(v).unwrap();
98 }
99
100 crate fn to_display<T: Print>(mut self, t: T) -> String {
101 t.print(&mut self);
102 self.into_inner()
103 }
104
105 crate fn from_display<T: std::fmt::Display>(&mut self, t: T) {
106 if self.for_html {
107 write!(self, "{}", t);
108 } else {
109 write!(self, "{:#}", t);
110 }
111 }
112
113 crate fn is_for_html(&self) -> bool {
114 self.for_html
115 }
116 }
117
118 /// Wrapper struct for properly emitting a function or method declaration.
119 crate struct Function<'a> {
120 /// The declaration to emit.
121 crate decl: &'a clean::FnDecl,
122 /// The length of the function header and name. In other words, the number of characters in the
123 /// function declaration up to but not including the parentheses.
124 ///
125 /// Used to determine line-wrapping.
126 crate header_len: usize,
127 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
128 crate indent: usize,
129 /// Whether the function is async or not.
130 crate asyncness: hir::IsAsync,
131 }
132
133 /// Wrapper struct for emitting a where-clause from Generics.
134 crate struct WhereClause<'a> {
135 /// The Generics from which to emit a where-clause.
136 crate gens: &'a clean::Generics,
137 /// The number of spaces to indent each line with.
138 crate indent: usize,
139 /// Whether the where-clause needs to add a comma and newline after the last bound.
140 crate end_newline: bool,
141 }
142
143 fn comma_sep<T: fmt::Display>(items: impl Iterator<Item = T>) -> impl fmt::Display {
144 display_fn(move |f| {
145 for (i, item) in items.enumerate() {
146 if i != 0 {
147 write!(f, ", ")?;
148 }
149 fmt::Display::fmt(&item, f)?;
150 }
151 Ok(())
152 })
153 }
154
155 crate fn print_generic_bounds(bounds: &[clean::GenericBound]) -> impl fmt::Display + '_ {
156 display_fn(move |f| {
157 let mut bounds_dup = FxHashSet::default();
158
159 for (i, bound) in
160 bounds.iter().filter(|b| bounds_dup.insert(b.print().to_string())).enumerate()
161 {
162 if i > 0 {
163 f.write_str(" + ")?;
164 }
165 fmt::Display::fmt(&bound.print(), f)?;
166 }
167 Ok(())
168 })
169 }
170
171 impl clean::GenericParamDef {
172 crate fn print(&self) -> impl fmt::Display + '_ {
173 display_fn(move |f| match self.kind {
174 clean::GenericParamDefKind::Lifetime => write!(f, "{}", self.name),
175 clean::GenericParamDefKind::Type { ref bounds, ref default, .. } => {
176 f.write_str(&*self.name.as_str())?;
177
178 if !bounds.is_empty() {
179 if f.alternate() {
180 write!(f, ": {:#}", print_generic_bounds(bounds))?;
181 } else {
182 write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
183 }
184 }
185
186 if let Some(ref ty) = default {
187 if f.alternate() {
188 write!(f, " = {:#}", ty.print())?;
189 } else {
190 write!(f, "&nbsp;=&nbsp;{}", ty.print())?;
191 }
192 }
193
194 Ok(())
195 }
196 clean::GenericParamDefKind::Const { ref ty, .. } => {
197 if f.alternate() {
198 write!(f, "const {}: {:#}", self.name, ty.print())
199 } else {
200 write!(f, "const {}:&nbsp;{}", self.name, ty.print())
201 }
202 }
203 })
204 }
205 }
206
207 impl clean::Generics {
208 crate fn print(&self) -> impl fmt::Display + '_ {
209 display_fn(move |f| {
210 let real_params =
211 self.params.iter().filter(|p| !p.is_synthetic_type_param()).collect::<Vec<_>>();
212 if real_params.is_empty() {
213 return Ok(());
214 }
215 if f.alternate() {
216 write!(f, "<{:#}>", comma_sep(real_params.iter().map(|g| g.print())))
217 } else {
218 write!(f, "&lt;{}&gt;", comma_sep(real_params.iter().map(|g| g.print())))
219 }
220 })
221 }
222 }
223
224 impl<'a> fmt::Display for WhereClause<'a> {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 let &WhereClause { gens, indent, end_newline } = self;
227 if gens.where_predicates.is_empty() {
228 return Ok(());
229 }
230 let mut clause = String::new();
231 if f.alternate() {
232 clause.push_str(" where");
233 } else {
234 if end_newline {
235 clause.push_str(" <span class=\"where fmt-newline\">where");
236 } else {
237 clause.push_str(" <span class=\"where\">where");
238 }
239 }
240 for (i, pred) in gens.where_predicates.iter().enumerate() {
241 if f.alternate() {
242 clause.push(' ');
243 } else {
244 clause.push_str("<br>");
245 }
246
247 match pred {
248 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
249 let bounds = bounds;
250 if f.alternate() {
251 clause.push_str(&format!(
252 "{:#}: {:#}",
253 ty.print(),
254 print_generic_bounds(bounds)
255 ));
256 } else {
257 clause.push_str(&format!(
258 "{}: {}",
259 ty.print(),
260 print_generic_bounds(bounds)
261 ));
262 }
263 }
264 &clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => {
265 clause.push_str(&format!(
266 "{}: {}",
267 lifetime.print(),
268 bounds
269 .iter()
270 .map(|b| b.print().to_string())
271 .collect::<Vec<_>>()
272 .join(" + ")
273 ));
274 }
275 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
276 if f.alternate() {
277 clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
278 } else {
279 clause.push_str(&format!("{} == {}", lhs.print(), rhs.print()));
280 }
281 }
282 }
283
284 if i < gens.where_predicates.len() - 1 || end_newline {
285 clause.push(',');
286 }
287 }
288
289 if end_newline {
290 // add a space so stripping <br> tags and breaking spaces still renders properly
291 if f.alternate() {
292 clause.push(' ');
293 } else {
294 clause.push_str("&nbsp;");
295 }
296 }
297
298 if !f.alternate() {
299 clause.push_str("</span>");
300 let padding = "&nbsp;".repeat(indent + 4);
301 clause = clause.replace("<br>", &format!("<br>{}", padding));
302 clause.insert_str(0, &"&nbsp;".repeat(indent.saturating_sub(1)));
303 if !end_newline {
304 clause.insert_str(0, "<br>");
305 }
306 }
307 write!(f, "{}", clause)
308 }
309 }
310
311 impl clean::Lifetime {
312 crate fn print(&self) -> impl fmt::Display + '_ {
313 self.get_ref()
314 }
315 }
316
317 impl clean::Constant {
318 crate fn print(&self) -> impl fmt::Display + '_ {
319 display_fn(move |f| {
320 if f.alternate() {
321 f.write_str(&self.expr)
322 } else {
323 write!(f, "{}", Escape(&self.expr))
324 }
325 })
326 }
327 }
328
329 impl clean::PolyTrait {
330 fn print(&self) -> impl fmt::Display + '_ {
331 display_fn(move |f| {
332 if !self.generic_params.is_empty() {
333 if f.alternate() {
334 write!(
335 f,
336 "for<{:#}> ",
337 comma_sep(self.generic_params.iter().map(|g| g.print()))
338 )?;
339 } else {
340 write!(
341 f,
342 "for&lt;{}&gt; ",
343 comma_sep(self.generic_params.iter().map(|g| g.print()))
344 )?;
345 }
346 }
347 if f.alternate() {
348 write!(f, "{:#}", self.trait_.print())
349 } else {
350 write!(f, "{}", self.trait_.print())
351 }
352 })
353 }
354 }
355
356 impl clean::GenericBound {
357 crate fn print(&self) -> impl fmt::Display + '_ {
358 display_fn(move |f| match self {
359 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
360 clean::GenericBound::TraitBound(ty, modifier) => {
361 let modifier_str = match modifier {
362 hir::TraitBoundModifier::None => "",
363 hir::TraitBoundModifier::Maybe => "?",
364 hir::TraitBoundModifier::MaybeConst => "?const",
365 };
366 if f.alternate() {
367 write!(f, "{}{:#}", modifier_str, ty.print())
368 } else {
369 write!(f, "{}{}", modifier_str, ty.print())
370 }
371 }
372 })
373 }
374 }
375
376 impl clean::GenericArgs {
377 fn print(&self) -> impl fmt::Display + '_ {
378 display_fn(move |f| {
379 match *self {
380 clean::GenericArgs::AngleBracketed { ref args, ref bindings } => {
381 if !args.is_empty() || !bindings.is_empty() {
382 if f.alternate() {
383 f.write_str("<")?;
384 } else {
385 f.write_str("&lt;")?;
386 }
387 let mut comma = false;
388 for arg in args {
389 if comma {
390 f.write_str(", ")?;
391 }
392 comma = true;
393 if f.alternate() {
394 write!(f, "{:#}", arg.print())?;
395 } else {
396 write!(f, "{}", arg.print())?;
397 }
398 }
399 for binding in bindings {
400 if comma {
401 f.write_str(", ")?;
402 }
403 comma = true;
404 if f.alternate() {
405 write!(f, "{:#}", binding.print())?;
406 } else {
407 write!(f, "{}", binding.print())?;
408 }
409 }
410 if f.alternate() {
411 f.write_str(">")?;
412 } else {
413 f.write_str("&gt;")?;
414 }
415 }
416 }
417 clean::GenericArgs::Parenthesized { ref inputs, ref output } => {
418 f.write_str("(")?;
419 let mut comma = false;
420 for ty in inputs {
421 if comma {
422 f.write_str(", ")?;
423 }
424 comma = true;
425 if f.alternate() {
426 write!(f, "{:#}", ty.print())?;
427 } else {
428 write!(f, "{}", ty.print())?;
429 }
430 }
431 f.write_str(")")?;
432 if let Some(ref ty) = *output {
433 if f.alternate() {
434 write!(f, " -> {:#}", ty.print())?;
435 } else {
436 write!(f, " -&gt; {}", ty.print())?;
437 }
438 }
439 }
440 }
441 Ok(())
442 })
443 }
444 }
445
446 impl clean::PathSegment {
447 crate fn print(&self) -> impl fmt::Display + '_ {
448 display_fn(move |f| {
449 if f.alternate() {
450 write!(f, "{}{:#}", self.name, self.args.print())
451 } else {
452 write!(f, "{}{}", self.name, self.args.print())
453 }
454 })
455 }
456 }
457
458 impl clean::Path {
459 crate fn print(&self) -> impl fmt::Display + '_ {
460 display_fn(move |f| {
461 if self.global {
462 f.write_str("::")?
463 }
464
465 for (i, seg) in self.segments.iter().enumerate() {
466 if i > 0 {
467 f.write_str("::")?
468 }
469 if f.alternate() {
470 write!(f, "{:#}", seg.print())?;
471 } else {
472 write!(f, "{}", seg.print())?;
473 }
474 }
475 Ok(())
476 })
477 }
478 }
479
480 crate fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
481 let cache = cache();
482 if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
483 return None;
484 }
485
486 let depth = CURRENT_DEPTH.with(|l| l.get());
487 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
488 Some(&(ref fqp, shortty)) => (fqp, shortty, "../".repeat(depth)),
489 None => {
490 let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
491 (
492 fqp,
493 shortty,
494 match cache.extern_locations[&did.krate] {
495 (.., ExternalLocation::Remote(ref s)) => s.to_string(),
496 (.., ExternalLocation::Local) => "../".repeat(depth),
497 (.., ExternalLocation::Unknown) => return None,
498 },
499 )
500 }
501 };
502 for component in &fqp[..fqp.len() - 1] {
503 url.push_str(component);
504 url.push_str("/");
505 }
506 match shortty {
507 ItemType::Module => {
508 url.push_str(fqp.last().unwrap());
509 url.push_str("/index.html");
510 }
511 _ => {
512 url.push_str(shortty.as_str());
513 url.push_str(".");
514 url.push_str(fqp.last().unwrap());
515 url.push_str(".html");
516 }
517 }
518 Some((url, shortty, fqp.to_vec()))
519 }
520
521 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
522 /// rendering function with the necessary arguments for linking to a local path.
523 fn resolved_path(
524 w: &mut fmt::Formatter<'_>,
525 did: DefId,
526 path: &clean::Path,
527 print_all: bool,
528 use_absolute: bool,
529 ) -> fmt::Result {
530 let last = path.segments.last().unwrap();
531
532 if print_all {
533 for seg in &path.segments[..path.segments.len() - 1] {
534 write!(w, "{}::", seg.name)?;
535 }
536 }
537 if w.alternate() {
538 write!(w, "{}{:#}", &last.name, last.args.print())?;
539 } else {
540 let path = if use_absolute {
541 if let Some((_, _, fqp)) = href(did) {
542 format!("{}::{}", fqp[..fqp.len() - 1].join("::"), anchor(did, fqp.last().unwrap()))
543 } else {
544 last.name.to_string()
545 }
546 } else {
547 anchor(did, &*last.name.as_str()).to_string()
548 };
549 write!(w, "{}{}", path, last.args.print())?;
550 }
551 Ok(())
552 }
553
554 fn primitive_link(
555 f: &mut fmt::Formatter<'_>,
556 prim: clean::PrimitiveType,
557 name: &str,
558 ) -> fmt::Result {
559 let m = cache();
560 let mut needs_termination = false;
561 if !f.alternate() {
562 match m.primitive_locations.get(&prim) {
563 Some(&def_id) if def_id.is_local() => {
564 let len = CURRENT_DEPTH.with(|s| s.get());
565 let len = if len == 0 { 0 } else { len - 1 };
566 write!(
567 f,
568 "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
569 "../".repeat(len),
570 prim.to_url_str()
571 )?;
572 needs_termination = true;
573 }
574 Some(&def_id) => {
575 let loc = match m.extern_locations[&def_id.krate] {
576 (ref cname, _, ExternalLocation::Remote(ref s)) => Some((cname, s.to_string())),
577 (ref cname, _, ExternalLocation::Local) => {
578 let len = CURRENT_DEPTH.with(|s| s.get());
579 Some((cname, "../".repeat(len)))
580 }
581 (.., ExternalLocation::Unknown) => None,
582 };
583 if let Some((cname, root)) = loc {
584 write!(
585 f,
586 "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
587 root,
588 cname,
589 prim.to_url_str()
590 )?;
591 needs_termination = true;
592 }
593 }
594 None => {}
595 }
596 }
597 write!(f, "{}", name)?;
598 if needs_termination {
599 write!(f, "</a>")?;
600 }
601 Ok(())
602 }
603
604 /// Helper to render type parameters
605 fn tybounds(param_names: &Option<Vec<clean::GenericBound>>) -> impl fmt::Display + '_ {
606 display_fn(move |f| match *param_names {
607 Some(ref params) => {
608 for param in params {
609 write!(f, " + ")?;
610 fmt::Display::fmt(&param.print(), f)?;
611 }
612 Ok(())
613 }
614 None => Ok(()),
615 })
616 }
617
618 crate fn anchor(did: DefId, text: &str) -> impl fmt::Display + '_ {
619 display_fn(move |f| {
620 if let Some((url, short_ty, fqp)) = href(did) {
621 write!(
622 f,
623 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
624 short_ty,
625 url,
626 short_ty,
627 fqp.join("::"),
628 text
629 )
630 } else {
631 write!(f, "{}", text)
632 }
633 })
634 }
635
636 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> fmt::Result {
637 match *t {
638 clean::Generic(name) => write!(f, "{}", name),
639 clean::ResolvedPath { did, ref param_names, ref path, is_generic } => {
640 if param_names.is_some() {
641 f.write_str("dyn ")?;
642 }
643 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
644 resolved_path(f, did, path, is_generic, use_absolute)?;
645 fmt::Display::fmt(&tybounds(param_names), f)
646 }
647 clean::Infer => write!(f, "_"),
648 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
649 clean::BareFunction(ref decl) => {
650 if f.alternate() {
651 write!(
652 f,
653 "{}{:#}fn{:#}{:#}",
654 decl.unsafety.print_with_space(),
655 print_abi_with_space(decl.abi),
656 decl.print_generic_params(),
657 decl.decl.print()
658 )
659 } else {
660 write!(
661 f,
662 "{}{}",
663 decl.unsafety.print_with_space(),
664 print_abi_with_space(decl.abi)
665 )?;
666 primitive_link(f, PrimitiveType::Fn, "fn")?;
667 write!(f, "{}{}", decl.print_generic_params(), decl.decl.print())
668 }
669 }
670 clean::Tuple(ref typs) => {
671 match &typs[..] {
672 &[] => primitive_link(f, PrimitiveType::Unit, "()"),
673 &[ref one] => {
674 primitive_link(f, PrimitiveType::Tuple, "(")?;
675 // Carry `f.alternate()` into this display w/o branching manually.
676 fmt::Display::fmt(&one.print(), f)?;
677 primitive_link(f, PrimitiveType::Tuple, ",)")
678 }
679 many => {
680 primitive_link(f, PrimitiveType::Tuple, "(")?;
681 for (i, item) in many.iter().enumerate() {
682 if i != 0 {
683 write!(f, ", ")?;
684 }
685 fmt::Display::fmt(&item.print(), f)?;
686 }
687 primitive_link(f, PrimitiveType::Tuple, ")")
688 }
689 }
690 }
691 clean::Slice(ref t) => {
692 primitive_link(f, PrimitiveType::Slice, "[")?;
693 fmt::Display::fmt(&t.print(), f)?;
694 primitive_link(f, PrimitiveType::Slice, "]")
695 }
696 clean::Array(ref t, ref n) => {
697 primitive_link(f, PrimitiveType::Array, "[")?;
698 fmt::Display::fmt(&t.print(), f)?;
699 if f.alternate() {
700 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
701 } else {
702 primitive_link(f, PrimitiveType::Array, &format!("; {}]", Escape(n)))
703 }
704 }
705 clean::Never => primitive_link(f, PrimitiveType::Never, "!"),
706 clean::RawPointer(m, ref t) => {
707 let m = match m {
708 hir::Mutability::Mut => "mut",
709 hir::Mutability::Not => "const",
710 };
711 match **t {
712 clean::Generic(_) | clean::ResolvedPath { is_generic: true, .. } => {
713 if f.alternate() {
714 primitive_link(
715 f,
716 clean::PrimitiveType::RawPointer,
717 &format!("*{} {:#}", m, t.print()),
718 )
719 } else {
720 primitive_link(
721 f,
722 clean::PrimitiveType::RawPointer,
723 &format!("*{} {}", m, t.print()),
724 )
725 }
726 }
727 _ => {
728 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m))?;
729 fmt::Display::fmt(&t.print(), f)
730 }
731 }
732 }
733 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
734 let lt = match l {
735 Some(l) => format!("{} ", l.print()),
736 _ => String::new(),
737 };
738 let m = mutability.print_with_space();
739 let amp = if f.alternate() { "&".to_string() } else { "&amp;".to_string() };
740 match **ty {
741 clean::Slice(ref bt) => {
742 // `BorrowedRef{ ... Slice(T) }` is `&[T]`
743 match **bt {
744 clean::Generic(_) => {
745 if f.alternate() {
746 primitive_link(
747 f,
748 PrimitiveType::Slice,
749 &format!("{}{}{}[{:#}]", amp, lt, m, bt.print()),
750 )
751 } else {
752 primitive_link(
753 f,
754 PrimitiveType::Slice,
755 &format!("{}{}{}[{}]", amp, lt, m, bt.print()),
756 )
757 }
758 }
759 _ => {
760 primitive_link(
761 f,
762 PrimitiveType::Slice,
763 &format!("{}{}{}[", amp, lt, m),
764 )?;
765 if f.alternate() {
766 write!(f, "{:#}", bt.print())?;
767 } else {
768 write!(f, "{}", bt.print())?;
769 }
770 primitive_link(f, PrimitiveType::Slice, "]")
771 }
772 }
773 }
774 clean::ResolvedPath { param_names: Some(ref v), .. } if !v.is_empty() => {
775 write!(f, "{}{}{}(", amp, lt, m)?;
776 fmt_type(&ty, f, use_absolute)?;
777 write!(f, ")")
778 }
779 clean::Generic(..) => {
780 primitive_link(f, PrimitiveType::Reference, &format!("{}{}{}", amp, lt, m))?;
781 fmt_type(&ty, f, use_absolute)
782 }
783 _ => {
784 write!(f, "{}{}{}", amp, lt, m)?;
785 fmt_type(&ty, f, use_absolute)
786 }
787 }
788 }
789 clean::ImplTrait(ref bounds) => {
790 if f.alternate() {
791 write!(f, "impl {:#}", print_generic_bounds(bounds))
792 } else {
793 write!(f, "impl {}", print_generic_bounds(bounds))
794 }
795 }
796 clean::QPath { ref name, ref self_type, ref trait_ } => {
797 let should_show_cast = match *trait_ {
798 box clean::ResolvedPath { ref path, .. } => {
799 !path.segments.is_empty() && !self_type.is_self_type()
800 }
801 _ => true,
802 };
803 if f.alternate() {
804 if should_show_cast {
805 write!(f, "<{:#} as {:#}>::", self_type.print(), trait_.print())?
806 } else {
807 write!(f, "{:#}::", self_type.print())?
808 }
809 } else {
810 if should_show_cast {
811 write!(f, "&lt;{} as {}&gt;::", self_type.print(), trait_.print())?
812 } else {
813 write!(f, "{}::", self_type.print())?
814 }
815 };
816 match *trait_ {
817 // It's pretty unsightly to look at `<A as B>::C` in output, and
818 // we've got hyperlinking on our side, so try to avoid longer
819 // notation as much as possible by making `C` a hyperlink to trait
820 // `B` to disambiguate.
821 //
822 // FIXME: this is still a lossy conversion and there should probably
823 // be a better way of representing this in general? Most of
824 // the ugliness comes from inlining across crates where
825 // everything comes in as a fully resolved QPath (hard to
826 // look at).
827 box clean::ResolvedPath { did, ref param_names, .. } => {
828 match href(did) {
829 Some((ref url, _, ref path)) if !f.alternate() => {
830 write!(
831 f,
832 "<a class=\"type\" href=\"{url}#{shortty}.{name}\" \
833 title=\"type {path}::{name}\">{name}</a>",
834 url = url,
835 shortty = ItemType::AssocType,
836 name = name,
837 path = path.join("::")
838 )?;
839 }
840 _ => write!(f, "{}", name)?,
841 }
842
843 // FIXME: `param_names` are not rendered, and this seems bad?
844 drop(param_names);
845 Ok(())
846 }
847 _ => write!(f, "{}", name),
848 }
849 }
850 }
851 }
852
853 impl clean::Type {
854 crate fn print(&self) -> impl fmt::Display + '_ {
855 display_fn(move |f| fmt_type(self, f, false))
856 }
857 }
858
859 impl clean::Impl {
860 crate fn print(&self) -> impl fmt::Display + '_ {
861 self.print_inner(true, false)
862 }
863
864 fn print_inner(&self, link_trait: bool, use_absolute: bool) -> impl fmt::Display + '_ {
865 display_fn(move |f| {
866 if f.alternate() {
867 write!(f, "impl{:#} ", self.generics.print())?;
868 } else {
869 write!(f, "impl{} ", self.generics.print())?;
870 }
871
872 if let Some(ref ty) = self.trait_ {
873 if self.polarity == Some(clean::ImplPolarity::Negative) {
874 write!(f, "!")?;
875 }
876
877 if link_trait {
878 fmt::Display::fmt(&ty.print(), f)?;
879 } else {
880 match ty {
881 clean::ResolvedPath {
882 param_names: None, path, is_generic: false, ..
883 } => {
884 let last = path.segments.last().unwrap();
885 fmt::Display::fmt(&last.name, f)?;
886 fmt::Display::fmt(&last.args.print(), f)?;
887 }
888 _ => unreachable!(),
889 }
890 }
891 write!(f, " for ")?;
892 }
893
894 if let Some(ref ty) = self.blanket_impl {
895 fmt_type(ty, f, use_absolute)?;
896 } else {
897 fmt_type(&self.for_, f, use_absolute)?;
898 }
899
900 fmt::Display::fmt(
901 &WhereClause { gens: &self.generics, indent: 0, end_newline: true },
902 f,
903 )?;
904 Ok(())
905 })
906 }
907 }
908
909 // The difference from above is that trait is not hyperlinked.
910 crate fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut Buffer, use_absolute: bool) {
911 f.from_display(i.print_inner(false, use_absolute))
912 }
913
914 impl clean::Arguments {
915 crate fn print(&self) -> impl fmt::Display + '_ {
916 display_fn(move |f| {
917 for (i, input) in self.values.iter().enumerate() {
918 if !input.name.is_empty() {
919 write!(f, "{}: ", input.name)?;
920 }
921 if f.alternate() {
922 write!(f, "{:#}", input.type_.print())?;
923 } else {
924 write!(f, "{}", input.type_.print())?;
925 }
926 if i + 1 < self.values.len() {
927 write!(f, ", ")?;
928 }
929 }
930 Ok(())
931 })
932 }
933 }
934
935 impl clean::FnRetTy {
936 crate fn print(&self) -> impl fmt::Display + '_ {
937 display_fn(move |f| match self {
938 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
939 clean::Return(ty) if f.alternate() => write!(f, " -> {:#}", ty.print()),
940 clean::Return(ty) => write!(f, " -&gt; {}", ty.print()),
941 clean::DefaultReturn => Ok(()),
942 })
943 }
944 }
945
946 impl clean::BareFunctionDecl {
947 fn print_generic_params(&self) -> impl fmt::Display + '_ {
948 comma_sep(self.generic_params.iter().map(|g| g.print()))
949 }
950 }
951
952 impl clean::FnDecl {
953 crate fn print(&self) -> impl fmt::Display + '_ {
954 display_fn(move |f| {
955 let ellipsis = if self.c_variadic { ", ..." } else { "" };
956 if f.alternate() {
957 write!(
958 f,
959 "({args:#}{ellipsis}){arrow:#}",
960 args = self.inputs.print(),
961 ellipsis = ellipsis,
962 arrow = self.output.print()
963 )
964 } else {
965 write!(
966 f,
967 "({args}{ellipsis}){arrow}",
968 args = self.inputs.print(),
969 ellipsis = ellipsis,
970 arrow = self.output.print()
971 )
972 }
973 })
974 }
975 }
976
977 impl Function<'_> {
978 crate fn print(&self) -> impl fmt::Display + '_ {
979 display_fn(move |f| {
980 let &Function { decl, header_len, indent, asyncness } = self;
981 let amp = if f.alternate() { "&" } else { "&amp;" };
982 let mut args = String::new();
983 let mut args_plain = String::new();
984 for (i, input) in decl.inputs.values.iter().enumerate() {
985 if i == 0 {
986 args.push_str("<br>");
987 }
988
989 if let Some(selfty) = input.to_self() {
990 match selfty {
991 clean::SelfValue => {
992 args.push_str("self");
993 args_plain.push_str("self");
994 }
995 clean::SelfBorrowed(Some(ref lt), mtbl) => {
996 args.push_str(&format!(
997 "{}{} {}self",
998 amp,
999 lt.print(),
1000 mtbl.print_with_space()
1001 ));
1002 args_plain.push_str(&format!(
1003 "&{} {}self",
1004 lt.print(),
1005 mtbl.print_with_space()
1006 ));
1007 }
1008 clean::SelfBorrowed(None, mtbl) => {
1009 args.push_str(&format!("{}{}self", amp, mtbl.print_with_space()));
1010 args_plain.push_str(&format!("&{}self", mtbl.print_with_space()));
1011 }
1012 clean::SelfExplicit(ref typ) => {
1013 if f.alternate() {
1014 args.push_str(&format!("self: {:#}", typ.print()));
1015 } else {
1016 args.push_str(&format!("self: {}", typ.print()));
1017 }
1018 args_plain.push_str(&format!("self: {:#}", typ.print()));
1019 }
1020 }
1021 } else {
1022 if i > 0 {
1023 args.push_str(" <br>");
1024 args_plain.push_str(" ");
1025 }
1026 if !input.name.is_empty() {
1027 args.push_str(&format!("{}: ", input.name));
1028 args_plain.push_str(&format!("{}: ", input.name));
1029 }
1030
1031 if f.alternate() {
1032 args.push_str(&format!("{:#}", input.type_.print()));
1033 } else {
1034 args.push_str(&input.type_.print().to_string());
1035 }
1036 args_plain.push_str(&format!("{:#}", input.type_.print()));
1037 }
1038 if i + 1 < decl.inputs.values.len() {
1039 args.push(',');
1040 args_plain.push(',');
1041 }
1042 }
1043
1044 let mut args_plain = format!("({})", args_plain);
1045
1046 if decl.c_variadic {
1047 args.push_str(",<br> ...");
1048 args_plain.push_str(", ...");
1049 }
1050
1051 let output = if let hir::IsAsync::Async = asyncness {
1052 Cow::Owned(decl.sugared_async_return_type())
1053 } else {
1054 Cow::Borrowed(&decl.output)
1055 };
1056
1057 let arrow_plain = format!("{:#}", &output.print());
1058 let arrow = if f.alternate() {
1059 format!("{:#}", &output.print())
1060 } else {
1061 output.print().to_string()
1062 };
1063
1064 let declaration_len = header_len + args_plain.len() + arrow_plain.len();
1065 let output = if declaration_len > 80 {
1066 let full_pad = format!("<br>{}", "&nbsp;".repeat(indent + 4));
1067 let close_pad = format!("<br>{}", "&nbsp;".repeat(indent));
1068 format!(
1069 "({args}{close}){arrow}",
1070 args = args.replace("<br>", &full_pad),
1071 close = close_pad,
1072 arrow = arrow
1073 )
1074 } else {
1075 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
1076 };
1077
1078 if f.alternate() {
1079 write!(f, "{}", output.replace("<br>", "\n"))
1080 } else {
1081 write!(f, "{}", output)
1082 }
1083 })
1084 }
1085 }
1086
1087 impl clean::Visibility {
1088 crate fn print_with_space<'tcx>(
1089 self,
1090 tcx: TyCtxt<'tcx>,
1091 item_did: DefId,
1092 ) -> impl fmt::Display + 'tcx {
1093 use rustc_span::symbol::kw;
1094
1095 display_fn(move |f| match self {
1096 clean::Public => f.write_str("pub "),
1097 clean::Inherited => Ok(()),
1098
1099 clean::Visibility::Restricted(vis_did) => {
1100 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1101 // However, rustdoc currently never displays a module's
1102 // visibility, so it shouldn't matter.
1103 let parent_module = find_nearest_parent_module(tcx, item_did);
1104
1105 if vis_did.index == CRATE_DEF_INDEX {
1106 write!(f, "pub(crate) ")
1107 } else if parent_module == Some(vis_did) {
1108 // `pub(in foo)` where `foo` is the parent module
1109 // is the same as no visibility modifier
1110 Ok(())
1111 } else if parent_module
1112 .map(|parent| find_nearest_parent_module(tcx, parent))
1113 .flatten()
1114 == Some(vis_did)
1115 {
1116 write!(f, "pub(super) ")
1117 } else {
1118 f.write_str("pub(")?;
1119 let path = tcx.def_path(vis_did);
1120 debug!("path={:?}", path);
1121 let first_name =
1122 path.data[0].data.get_opt_name().expect("modules are always named");
1123 if path.data.len() != 1
1124 || (first_name != kw::SelfLower && first_name != kw::Super)
1125 {
1126 f.write_str("in ")?;
1127 }
1128 // modified from `resolved_path()` to work with `DefPathData`
1129 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1130 for seg in &path.data[..path.data.len() - 1] {
1131 write!(f, "{}::", seg.data.get_opt_name().unwrap())?;
1132 }
1133 let path = anchor(vis_did, &last_name.as_str()).to_string();
1134 write!(f, "{}) ", path)
1135 }
1136 }
1137 })
1138 }
1139 }
1140
1141 crate trait PrintWithSpace {
1142 fn print_with_space(&self) -> &str;
1143 }
1144
1145 impl PrintWithSpace for hir::Unsafety {
1146 fn print_with_space(&self) -> &str {
1147 match self {
1148 hir::Unsafety::Unsafe => "unsafe ",
1149 hir::Unsafety::Normal => "",
1150 }
1151 }
1152 }
1153
1154 impl PrintWithSpace for hir::Constness {
1155 fn print_with_space(&self) -> &str {
1156 match self {
1157 hir::Constness::Const => "const ",
1158 hir::Constness::NotConst => "",
1159 }
1160 }
1161 }
1162
1163 impl PrintWithSpace for hir::IsAsync {
1164 fn print_with_space(&self) -> &str {
1165 match self {
1166 hir::IsAsync::Async => "async ",
1167 hir::IsAsync::NotAsync => "",
1168 }
1169 }
1170 }
1171
1172 impl PrintWithSpace for hir::Mutability {
1173 fn print_with_space(&self) -> &str {
1174 match self {
1175 hir::Mutability::Not => "",
1176 hir::Mutability::Mut => "mut ",
1177 }
1178 }
1179 }
1180
1181 impl clean::Import {
1182 crate fn print(&self) -> impl fmt::Display + '_ {
1183 display_fn(move |f| match self.kind {
1184 clean::ImportKind::Simple(name) => {
1185 if name == self.source.path.last() {
1186 write!(f, "use {};", self.source.print())
1187 } else {
1188 write!(f, "use {} as {};", self.source.print(), name)
1189 }
1190 }
1191 clean::ImportKind::Glob => {
1192 if self.source.path.segments.is_empty() {
1193 write!(f, "use *;")
1194 } else {
1195 write!(f, "use {}::*;", self.source.print())
1196 }
1197 }
1198 })
1199 }
1200 }
1201
1202 impl clean::ImportSource {
1203 crate fn print(&self) -> impl fmt::Display + '_ {
1204 display_fn(move |f| match self.did {
1205 Some(did) => resolved_path(f, did, &self.path, true, false),
1206 _ => {
1207 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1208 write!(f, "{}::", seg.name)?;
1209 }
1210 let name = self.path.last_name();
1211 if let hir::def::Res::PrimTy(p) = self.path.res {
1212 primitive_link(f, PrimitiveType::from(p), &*name)?;
1213 } else {
1214 write!(f, "{}", name)?;
1215 }
1216 Ok(())
1217 }
1218 })
1219 }
1220 }
1221
1222 impl clean::TypeBinding {
1223 crate fn print(&self) -> impl fmt::Display + '_ {
1224 display_fn(move |f| {
1225 f.write_str(&*self.name.as_str())?;
1226 match self.kind {
1227 clean::TypeBindingKind::Equality { ref ty } => {
1228 if f.alternate() {
1229 write!(f, " = {:#}", ty.print())?;
1230 } else {
1231 write!(f, " = {}", ty.print())?;
1232 }
1233 }
1234 clean::TypeBindingKind::Constraint { ref bounds } => {
1235 if !bounds.is_empty() {
1236 if f.alternate() {
1237 write!(f, ": {:#}", print_generic_bounds(bounds))?;
1238 } else {
1239 write!(f, ":&nbsp;{}", print_generic_bounds(bounds))?;
1240 }
1241 }
1242 }
1243 }
1244 Ok(())
1245 })
1246 }
1247 }
1248
1249 crate fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1250 display_fn(move |f| {
1251 let quot = if f.alternate() { "\"" } else { "&quot;" };
1252 match abi {
1253 Abi::Rust => Ok(()),
1254 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1255 }
1256 })
1257 }
1258
1259 crate fn print_default_space<'a>(v: bool) -> &'a str {
1260 if v { "default " } else { "" }
1261 }
1262
1263 impl clean::GenericArg {
1264 crate fn print(&self) -> impl fmt::Display + '_ {
1265 display_fn(move |f| match self {
1266 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1267 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(), f),
1268 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(), f),
1269 })
1270 }
1271 }
1272
1273 crate fn display_fn(f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Display {
1274 WithFormatter(Cell::new(Some(f)))
1275 }
1276
1277 struct WithFormatter<F>(Cell<Option<F>>);
1278
1279 impl<F> fmt::Display for WithFormatter<F>
1280 where
1281 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1282 {
1283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1284 (self.0.take()).unwrap()(f)
1285 }
1286 }