]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/format.rs
1b445b8981e1a7dbc8a9e7912e08cd311e290a3e
[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`.
5 //!
6 //! These implementations all emit HTML. As an internal implementation detail,
7 //! some of them support an alternate format that emits text, but that should
8 //! not be used external to this module.
9
10 use std::borrow::Cow;
11 use std::cell::Cell;
12 use std::fmt::{self, Write};
13 use std::iter::{self, once};
14
15 use rustc_ast as ast;
16 use rustc_attr::{ConstStability, StabilityLevel};
17 use rustc_data_structures::captures::Captures;
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_hir as hir;
20 use rustc_hir::def::DefKind;
21 use rustc_hir::def_id::DefId;
22 use rustc_metadata::creader::{CStore, LoadedMacro};
23 use rustc_middle::ty;
24 use rustc_middle::ty::TyCtxt;
25 use rustc_span::symbol::kw;
26 use rustc_span::{sym, Symbol};
27 use rustc_target::spec::abi::Abi;
28
29 use itertools::Itertools;
30
31 use crate::clean::{
32 self, types::ExternalLocation, utils::find_nearest_parent_module, ExternalCrate, ItemId,
33 PrimitiveType,
34 };
35 use crate::formats::item_type::ItemType;
36 use crate::html::escape::Escape;
37 use crate::html::render::Context;
38 use crate::passes::collect_intra_doc_links::UrlFragment;
39
40 use super::url_parts_builder::estimate_item_path_byte_length;
41 use super::url_parts_builder::UrlPartsBuilder;
42
43 pub(crate) trait Print {
44 fn print(self, buffer: &mut Buffer);
45 }
46
47 impl<F> Print for F
48 where
49 F: FnOnce(&mut Buffer),
50 {
51 fn print(self, buffer: &mut Buffer) {
52 (self)(buffer)
53 }
54 }
55
56 impl Print for String {
57 fn print(self, buffer: &mut Buffer) {
58 buffer.write_str(&self);
59 }
60 }
61
62 impl Print for &'_ str {
63 fn print(self, buffer: &mut Buffer) {
64 buffer.write_str(self);
65 }
66 }
67
68 #[derive(Debug, Clone)]
69 pub(crate) struct Buffer {
70 for_html: bool,
71 buffer: String,
72 }
73
74 impl core::fmt::Write for Buffer {
75 #[inline]
76 fn write_str(&mut self, s: &str) -> fmt::Result {
77 self.buffer.write_str(s)
78 }
79
80 #[inline]
81 fn write_char(&mut self, c: char) -> fmt::Result {
82 self.buffer.write_char(c)
83 }
84
85 #[inline]
86 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
87 self.buffer.write_fmt(args)
88 }
89 }
90
91 impl Buffer {
92 pub(crate) fn empty_from(v: &Buffer) -> Buffer {
93 Buffer { for_html: v.for_html, buffer: String::new() }
94 }
95
96 pub(crate) fn html() -> Buffer {
97 Buffer { for_html: true, buffer: String::new() }
98 }
99
100 pub(crate) fn new() -> Buffer {
101 Buffer { for_html: false, buffer: String::new() }
102 }
103
104 pub(crate) fn is_empty(&self) -> bool {
105 self.buffer.is_empty()
106 }
107
108 pub(crate) fn into_inner(self) -> String {
109 self.buffer
110 }
111
112 pub(crate) fn push_str(&mut self, s: &str) {
113 self.buffer.push_str(s);
114 }
115
116 pub(crate) fn push_buffer(&mut self, other: Buffer) {
117 self.buffer.push_str(&other.buffer);
118 }
119
120 // Intended for consumption by write! and writeln! (std::fmt) but without
121 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
122 // import).
123 pub(crate) fn write_str(&mut self, s: &str) {
124 self.buffer.push_str(s);
125 }
126
127 // Intended for consumption by write! and writeln! (std::fmt) but without
128 // the fmt::Result return type imposed by fmt::Write (and avoiding the trait
129 // import).
130 pub(crate) fn write_fmt(&mut self, v: fmt::Arguments<'_>) {
131 self.buffer.write_fmt(v).unwrap();
132 }
133
134 pub(crate) fn to_display<T: Print>(mut self, t: T) -> String {
135 t.print(&mut self);
136 self.into_inner()
137 }
138
139 pub(crate) fn reserve(&mut self, additional: usize) {
140 self.buffer.reserve(additional)
141 }
142
143 pub(crate) fn len(&self) -> usize {
144 self.buffer.len()
145 }
146 }
147
148 pub(crate) fn comma_sep<T: fmt::Display>(
149 items: impl Iterator<Item = T>,
150 space_after_comma: bool,
151 ) -> impl fmt::Display {
152 display_fn(move |f| {
153 for (i, item) in items.enumerate() {
154 if i != 0 {
155 write!(f, ",{}", if space_after_comma { " " } else { "" })?;
156 }
157 fmt::Display::fmt(&item, f)?;
158 }
159 Ok(())
160 })
161 }
162
163 pub(crate) fn print_generic_bounds<'a, 'tcx: 'a>(
164 bounds: &'a [clean::GenericBound],
165 cx: &'a Context<'tcx>,
166 ) -> impl fmt::Display + 'a + Captures<'tcx> {
167 display_fn(move |f| {
168 let mut bounds_dup = FxHashSet::default();
169
170 for (i, bound) in bounds.iter().filter(|b| bounds_dup.insert(b.clone())).enumerate() {
171 if i > 0 {
172 f.write_str(" + ")?;
173 }
174 fmt::Display::fmt(&bound.print(cx), f)?;
175 }
176 Ok(())
177 })
178 }
179
180 impl clean::GenericParamDef {
181 pub(crate) fn print<'a, 'tcx: 'a>(
182 &'a self,
183 cx: &'a Context<'tcx>,
184 ) -> impl fmt::Display + 'a + Captures<'tcx> {
185 display_fn(move |f| match &self.kind {
186 clean::GenericParamDefKind::Lifetime { outlives } => {
187 write!(f, "{}", self.name)?;
188
189 if !outlives.is_empty() {
190 f.write_str(": ")?;
191 for (i, lt) in outlives.iter().enumerate() {
192 if i != 0 {
193 f.write_str(" + ")?;
194 }
195 write!(f, "{}", lt.print())?;
196 }
197 }
198
199 Ok(())
200 }
201 clean::GenericParamDefKind::Type { bounds, default, .. } => {
202 f.write_str(self.name.as_str())?;
203
204 if !bounds.is_empty() {
205 if f.alternate() {
206 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
207 } else {
208 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
209 }
210 }
211
212 if let Some(ref ty) = default {
213 if f.alternate() {
214 write!(f, " = {:#}", ty.print(cx))?;
215 } else {
216 write!(f, " = {}", ty.print(cx))?;
217 }
218 }
219
220 Ok(())
221 }
222 clean::GenericParamDefKind::Const { ty, default, .. } => {
223 if f.alternate() {
224 write!(f, "const {}: {:#}", self.name, ty.print(cx))?;
225 } else {
226 write!(f, "const {}: {}", self.name, ty.print(cx))?;
227 }
228
229 if let Some(default) = default {
230 if f.alternate() {
231 write!(f, " = {:#}", default)?;
232 } else {
233 write!(f, " = {}", default)?;
234 }
235 }
236
237 Ok(())
238 }
239 })
240 }
241 }
242
243 impl clean::Generics {
244 pub(crate) fn print<'a, 'tcx: 'a>(
245 &'a self,
246 cx: &'a Context<'tcx>,
247 ) -> impl fmt::Display + 'a + Captures<'tcx> {
248 display_fn(move |f| {
249 let mut real_params =
250 self.params.iter().filter(|p| !p.is_synthetic_type_param()).peekable();
251 if real_params.peek().is_none() {
252 return Ok(());
253 }
254
255 if f.alternate() {
256 write!(f, "<{:#}>", comma_sep(real_params.map(|g| g.print(cx)), true))
257 } else {
258 write!(f, "&lt;{}&gt;", comma_sep(real_params.map(|g| g.print(cx)), true))
259 }
260 })
261 }
262 }
263
264 #[derive(Clone, Copy, PartialEq, Eq)]
265 pub(crate) enum Ending {
266 Newline,
267 NoNewline,
268 }
269
270 /// * The Generics from which to emit a where-clause.
271 /// * The number of spaces to indent each line with.
272 /// * Whether the where-clause needs to add a comma and newline after the last bound.
273 pub(crate) fn print_where_clause<'a, 'tcx: 'a>(
274 gens: &'a clean::Generics,
275 cx: &'a Context<'tcx>,
276 indent: usize,
277 ending: Ending,
278 ) -> impl fmt::Display + 'a + Captures<'tcx> {
279 display_fn(move |f| {
280 let mut where_predicates = gens.where_predicates.iter().filter(|pred| {
281 !matches!(pred, clean::WherePredicate::BoundPredicate { bounds, .. } if bounds.is_empty())
282 }).map(|pred| {
283 display_fn(move |f| {
284 if f.alternate() {
285 f.write_str(" ")?;
286 } else {
287 f.write_str("\n")?;
288 }
289
290 match pred {
291 clean::WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
292 let ty_cx = ty.print(cx);
293 let generic_bounds = print_generic_bounds(bounds, cx);
294
295 if bound_params.is_empty() {
296 if f.alternate() {
297 write!(f, "{ty_cx:#}: {generic_bounds:#}")
298 } else {
299 write!(f, "{ty_cx}: {generic_bounds}")
300 }
301 } else {
302 if f.alternate() {
303 write!(
304 f,
305 "for<{:#}> {ty_cx:#}: {generic_bounds:#}",
306 comma_sep(bound_params.iter().map(|lt| lt.print(cx)), true)
307 )
308 } else {
309 write!(
310 f,
311 "for&lt;{}&gt; {ty_cx}: {generic_bounds}",
312 comma_sep(bound_params.iter().map(|lt| lt.print(cx)), true)
313 )
314 }
315 }
316 }
317 clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
318 let mut bounds_display = String::new();
319 for bound in bounds.iter().map(|b| b.print(cx)) {
320 write!(bounds_display, "{bound} + ")?;
321 }
322 bounds_display.truncate(bounds_display.len() - " + ".len());
323 write!(f, "{}: {bounds_display}", lifetime.print())
324 }
325 // FIXME(fmease): Render bound params.
326 clean::WherePredicate::EqPredicate { lhs, rhs, bound_params: _ } => {
327 if f.alternate() {
328 write!(f, "{:#} == {:#}", lhs.print(cx), rhs.print(cx))
329 } else {
330 write!(f, "{} == {}", lhs.print(cx), rhs.print(cx))
331 }
332 }
333 }
334 })
335 }).peekable();
336
337 if where_predicates.peek().is_none() {
338 return Ok(());
339 }
340
341 let where_preds = comma_sep(where_predicates, false);
342 let clause = if f.alternate() {
343 if ending == Ending::Newline {
344 format!(" where{where_preds},")
345 } else {
346 format!(" where{where_preds}")
347 }
348 } else {
349 let mut br_with_padding = String::with_capacity(6 * indent + 28);
350 br_with_padding.push_str("\n");
351
352 let padding_amount =
353 if ending == Ending::Newline { indent + 4 } else { indent + "fn where ".len() };
354
355 for _ in 0..padding_amount {
356 br_with_padding.push_str(" ");
357 }
358 let where_preds = where_preds.to_string().replace('\n', &br_with_padding);
359
360 if ending == Ending::Newline {
361 let mut clause = " ".repeat(indent.saturating_sub(1));
362 write!(clause, "<span class=\"where fmt-newline\">where{where_preds},</span>")?;
363 clause
364 } else {
365 // insert a newline after a single space but before multiple spaces at the start
366 if indent == 0 {
367 format!("\n<span class=\"where\">where{where_preds}</span>")
368 } else {
369 // put the first one on the same line as the 'where' keyword
370 let where_preds = where_preds.replacen(&br_with_padding, " ", 1);
371
372 let mut clause = br_with_padding;
373 clause.truncate(clause.len() - "where ".len());
374
375 write!(clause, "<span class=\"where\">where{where_preds}</span>")?;
376 clause
377 }
378 }
379 };
380 write!(f, "{clause}")
381 })
382 }
383
384 impl clean::Lifetime {
385 pub(crate) fn print(&self) -> impl fmt::Display + '_ {
386 self.0.as_str()
387 }
388 }
389
390 impl clean::Constant {
391 pub(crate) fn print(&self, tcx: TyCtxt<'_>) -> impl fmt::Display + '_ {
392 let expr = self.expr(tcx);
393 display_fn(
394 move |f| {
395 if f.alternate() { f.write_str(&expr) } else { write!(f, "{}", Escape(&expr)) }
396 },
397 )
398 }
399 }
400
401 impl clean::PolyTrait {
402 fn print<'a, 'tcx: 'a>(
403 &'a self,
404 cx: &'a Context<'tcx>,
405 ) -> impl fmt::Display + 'a + Captures<'tcx> {
406 display_fn(move |f| {
407 if !self.generic_params.is_empty() {
408 if f.alternate() {
409 write!(
410 f,
411 "for<{:#}> ",
412 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
413 )?;
414 } else {
415 write!(
416 f,
417 "for&lt;{}&gt; ",
418 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
419 )?;
420 }
421 }
422 if f.alternate() {
423 write!(f, "{:#}", self.trait_.print(cx))
424 } else {
425 write!(f, "{}", self.trait_.print(cx))
426 }
427 })
428 }
429 }
430
431 impl clean::GenericBound {
432 pub(crate) fn print<'a, 'tcx: 'a>(
433 &'a self,
434 cx: &'a Context<'tcx>,
435 ) -> impl fmt::Display + 'a + Captures<'tcx> {
436 display_fn(move |f| match self {
437 clean::GenericBound::Outlives(lt) => write!(f, "{}", lt.print()),
438 clean::GenericBound::TraitBound(ty, modifier) => {
439 let modifier_str = match modifier {
440 hir::TraitBoundModifier::None => "",
441 hir::TraitBoundModifier::Maybe => "?",
442 // ~const is experimental; do not display those bounds in rustdoc
443 hir::TraitBoundModifier::MaybeConst => "",
444 };
445 if f.alternate() {
446 write!(f, "{}{:#}", modifier_str, ty.print(cx))
447 } else {
448 write!(f, "{}{}", modifier_str, ty.print(cx))
449 }
450 }
451 })
452 }
453 }
454
455 impl clean::GenericArgs {
456 fn print<'a, 'tcx: 'a>(
457 &'a self,
458 cx: &'a Context<'tcx>,
459 ) -> impl fmt::Display + 'a + Captures<'tcx> {
460 display_fn(move |f| {
461 match self {
462 clean::GenericArgs::AngleBracketed { args, bindings } => {
463 if !args.is_empty() || !bindings.is_empty() {
464 if f.alternate() {
465 f.write_str("<")?;
466 } else {
467 f.write_str("&lt;")?;
468 }
469 let mut comma = false;
470 for arg in args.iter() {
471 if comma {
472 f.write_str(", ")?;
473 }
474 comma = true;
475 if f.alternate() {
476 write!(f, "{:#}", arg.print(cx))?;
477 } else {
478 write!(f, "{}", arg.print(cx))?;
479 }
480 }
481 for binding in bindings.iter() {
482 if comma {
483 f.write_str(", ")?;
484 }
485 comma = true;
486 if f.alternate() {
487 write!(f, "{:#}", binding.print(cx))?;
488 } else {
489 write!(f, "{}", binding.print(cx))?;
490 }
491 }
492 if f.alternate() {
493 f.write_str(">")?;
494 } else {
495 f.write_str("&gt;")?;
496 }
497 }
498 }
499 clean::GenericArgs::Parenthesized { inputs, output } => {
500 f.write_str("(")?;
501 let mut comma = false;
502 for ty in inputs.iter() {
503 if comma {
504 f.write_str(", ")?;
505 }
506 comma = true;
507 if f.alternate() {
508 write!(f, "{:#}", ty.print(cx))?;
509 } else {
510 write!(f, "{}", ty.print(cx))?;
511 }
512 }
513 f.write_str(")")?;
514 if let Some(ref ty) = *output {
515 if f.alternate() {
516 write!(f, " -> {:#}", ty.print(cx))?;
517 } else {
518 write!(f, " -&gt; {}", ty.print(cx))?;
519 }
520 }
521 }
522 }
523 Ok(())
524 })
525 }
526 }
527
528 // Possible errors when computing href link source for a `DefId`
529 #[derive(PartialEq, Eq)]
530 pub(crate) enum HrefError {
531 /// This item is known to rustdoc, but from a crate that does not have documentation generated.
532 ///
533 /// This can only happen for non-local items.
534 ///
535 /// # Example
536 ///
537 /// Crate `a` defines a public trait and crate `b` – the target crate that depends on `a` –
538 /// implements it for a local type.
539 /// We document `b` but **not** `a` (we only _build_ the latter – with `rustc`):
540 ///
541 /// ```sh
542 /// rustc a.rs --crate-type=lib
543 /// rustdoc b.rs --crate-type=lib --extern=a=liba.rlib
544 /// ```
545 ///
546 /// Now, the associated items in the trait impl want to link to the corresponding item in the
547 /// trait declaration (see `html::render::assoc_href_attr`) but it's not available since their
548 /// *documentation (was) not built*.
549 DocumentationNotBuilt,
550 /// This can only happen for non-local items when `--document-private-items` is not passed.
551 Private,
552 // Not in external cache, href link should be in same page
553 NotInExternalCache,
554 }
555
556 // Panics if `syms` is empty.
557 pub(crate) fn join_with_double_colon(syms: &[Symbol]) -> String {
558 let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
559 s.push_str(syms[0].as_str());
560 for sym in &syms[1..] {
561 s.push_str("::");
562 s.push_str(sym.as_str());
563 }
564 s
565 }
566
567 /// This function is to get the external macro path because they are not in the cache used in
568 /// `href_with_root_path`.
569 fn generate_macro_def_id_path(
570 def_id: DefId,
571 cx: &Context<'_>,
572 root_path: Option<&str>,
573 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
574 let tcx = cx.shared.tcx;
575 let crate_name = tcx.crate_name(def_id.krate);
576 let cache = cx.cache();
577
578 let fqp: Vec<Symbol> = tcx
579 .def_path(def_id)
580 .data
581 .into_iter()
582 .filter_map(|elem| {
583 // extern blocks (and a few others things) have an empty name.
584 match elem.data.get_opt_name() {
585 Some(s) if !s.is_empty() => Some(s),
586 _ => None,
587 }
588 })
589 .collect();
590 let mut relative = fqp.iter().copied();
591 let cstore = CStore::from_tcx(tcx);
592 // We need this to prevent a `panic` when this function is used from intra doc links...
593 if !cstore.has_crate_data(def_id.krate) {
594 debug!("No data for crate {}", crate_name);
595 return Err(HrefError::NotInExternalCache);
596 }
597 // Check to see if it is a macro 2.0 or built-in macro.
598 // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
599 let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx.sess) {
600 LoadedMacro::MacroDef(def, _) => {
601 // If `ast_def.macro_rules` is `true`, then it's not a macro 2.0.
602 matches!(&def.kind, ast::ItemKind::MacroDef(ast_def) if !ast_def.macro_rules)
603 }
604 _ => false,
605 };
606
607 let mut path = if is_macro_2 {
608 once(crate_name).chain(relative).collect()
609 } else {
610 vec![crate_name, relative.next_back().unwrap()]
611 };
612 if path.len() < 2 {
613 // The minimum we can have is the crate name followed by the macro name. If shorter, then
614 // it means that `relative` was empty, which is an error.
615 debug!("macro path cannot be empty!");
616 return Err(HrefError::NotInExternalCache);
617 }
618
619 if let Some(last) = path.last_mut() {
620 *last = Symbol::intern(&format!("macro.{}.html", last.as_str()));
621 }
622
623 let url = match cache.extern_locations[&def_id.krate] {
624 ExternalLocation::Remote(ref s) => {
625 // `ExternalLocation::Remote` always end with a `/`.
626 format!("{}{}", s, path.iter().map(|p| p.as_str()).join("/"))
627 }
628 ExternalLocation::Local => {
629 // `root_path` always end with a `/`.
630 format!(
631 "{}{}/{}",
632 root_path.unwrap_or(""),
633 crate_name,
634 path.iter().map(|p| p.as_str()).join("/")
635 )
636 }
637 ExternalLocation::Unknown => {
638 debug!("crate {} not in cache when linkifying macros", crate_name);
639 return Err(HrefError::NotInExternalCache);
640 }
641 };
642 Ok((url, ItemType::Macro, fqp))
643 }
644
645 pub(crate) fn href_with_root_path(
646 did: DefId,
647 cx: &Context<'_>,
648 root_path: Option<&str>,
649 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
650 let tcx = cx.tcx();
651 let def_kind = tcx.def_kind(did);
652 let did = match def_kind {
653 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
654 // documented on their parent's page
655 tcx.parent(did)
656 }
657 _ => did,
658 };
659 let cache = cx.cache();
660 let relative_to = &cx.current;
661 fn to_module_fqp(shortty: ItemType, fqp: &[Symbol]) -> &[Symbol] {
662 if shortty == ItemType::Module { fqp } else { &fqp[..fqp.len() - 1] }
663 }
664
665 if !did.is_local()
666 && !cache.effective_visibilities.is_directly_public(tcx, did)
667 && !cache.document_private
668 && !cache.primitive_locations.values().any(|&id| id == did)
669 {
670 return Err(HrefError::Private);
671 }
672
673 let mut is_remote = false;
674 let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
675 Some(&(ref fqp, shortty)) => (fqp, shortty, {
676 let module_fqp = to_module_fqp(shortty, fqp.as_slice());
677 debug!(?fqp, ?shortty, ?module_fqp);
678 href_relative_parts(module_fqp, relative_to).collect()
679 }),
680 None => {
681 if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
682 let module_fqp = to_module_fqp(shortty, fqp);
683 (
684 fqp,
685 shortty,
686 match cache.extern_locations[&did.krate] {
687 ExternalLocation::Remote(ref s) => {
688 is_remote = true;
689 let s = s.trim_end_matches('/');
690 let mut builder = UrlPartsBuilder::singleton(s);
691 builder.extend(module_fqp.iter().copied());
692 builder
693 }
694 ExternalLocation::Local => {
695 href_relative_parts(module_fqp, relative_to).collect()
696 }
697 ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
698 },
699 )
700 } else if matches!(def_kind, DefKind::Macro(_)) {
701 return generate_macro_def_id_path(did, cx, root_path);
702 } else {
703 return Err(HrefError::NotInExternalCache);
704 }
705 }
706 };
707 if !is_remote && let Some(root_path) = root_path {
708 let root = root_path.trim_end_matches('/');
709 url_parts.push_front(root);
710 }
711 debug!(?url_parts);
712 match shortty {
713 ItemType::Module => {
714 url_parts.push("index.html");
715 }
716 _ => {
717 let prefix = shortty.as_str();
718 let last = fqp.last().unwrap();
719 url_parts.push_fmt(format_args!("{}.{}.html", prefix, last));
720 }
721 }
722 Ok((url_parts.finish(), shortty, fqp.to_vec()))
723 }
724
725 pub(crate) fn href(
726 did: DefId,
727 cx: &Context<'_>,
728 ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> {
729 href_with_root_path(did, cx, None)
730 }
731
732 /// Both paths should only be modules.
733 /// This is because modules get their own directories; that is, `std::vec` and `std::vec::Vec` will
734 /// both need `../iter/trait.Iterator.html` to get at the iterator trait.
735 pub(crate) fn href_relative_parts<'fqp>(
736 fqp: &'fqp [Symbol],
737 relative_to_fqp: &[Symbol],
738 ) -> Box<dyn Iterator<Item = Symbol> + 'fqp> {
739 for (i, (f, r)) in fqp.iter().zip(relative_to_fqp.iter()).enumerate() {
740 // e.g. linking to std::iter from std::vec (`dissimilar_part_count` will be 1)
741 if f != r {
742 let dissimilar_part_count = relative_to_fqp.len() - i;
743 let fqp_module = &fqp[i..fqp.len()];
744 return Box::new(
745 iter::repeat(sym::dotdot)
746 .take(dissimilar_part_count)
747 .chain(fqp_module.iter().copied()),
748 );
749 }
750 }
751 // e.g. linking to std::sync::atomic from std::sync
752 if relative_to_fqp.len() < fqp.len() {
753 Box::new(fqp[relative_to_fqp.len()..fqp.len()].iter().copied())
754 // e.g. linking to std::sync from std::sync::atomic
755 } else if fqp.len() < relative_to_fqp.len() {
756 let dissimilar_part_count = relative_to_fqp.len() - fqp.len();
757 Box::new(iter::repeat(sym::dotdot).take(dissimilar_part_count))
758 // linking to the same module
759 } else {
760 Box::new(iter::empty())
761 }
762 }
763
764 pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Context<'_>) -> String {
765 let cache = cx.cache();
766 let Some((fqp, shortty)) = cache.paths.get(&did)
767 .or_else(|| cache.external_paths.get(&did))
768 else { return String::new() };
769 let mut buf = Buffer::new();
770 let fqp = if *shortty == ItemType::Primitive {
771 // primitives are documented in a crate, but not actually part of it
772 &fqp[fqp.len() - 1..]
773 } else {
774 &fqp
775 };
776 if let &Some(UrlFragment::Item(id)) = fragment {
777 write!(buf, "{} ", cx.tcx().def_descr(id));
778 for component in fqp {
779 write!(buf, "{component}::");
780 }
781 write!(buf, "{}", cx.tcx().item_name(id));
782 } else if !fqp.is_empty() {
783 let mut fqp_it = fqp.into_iter();
784 write!(buf, "{shortty} {}", fqp_it.next().unwrap());
785 for component in fqp_it {
786 write!(buf, "::{component}");
787 }
788 }
789 buf.into_inner()
790 }
791
792 /// Used to render a [`clean::Path`].
793 fn resolved_path<'cx>(
794 w: &mut fmt::Formatter<'_>,
795 did: DefId,
796 path: &clean::Path,
797 print_all: bool,
798 use_absolute: bool,
799 cx: &'cx Context<'_>,
800 ) -> fmt::Result {
801 let last = path.segments.last().unwrap();
802
803 if print_all {
804 for seg in &path.segments[..path.segments.len() - 1] {
805 write!(w, "{}::", if seg.name == kw::PathRoot { "" } else { seg.name.as_str() })?;
806 }
807 }
808 if w.alternate() {
809 write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
810 } else {
811 let path = if use_absolute {
812 if let Ok((_, _, fqp)) = href(did, cx) {
813 format!(
814 "{}::{}",
815 join_with_double_colon(&fqp[..fqp.len() - 1]),
816 anchor(did, *fqp.last().unwrap(), cx)
817 )
818 } else {
819 last.name.to_string()
820 }
821 } else {
822 anchor(did, last.name, cx).to_string()
823 };
824 write!(w, "{}{}", path, last.args.print(cx))?;
825 }
826 Ok(())
827 }
828
829 fn primitive_link(
830 f: &mut fmt::Formatter<'_>,
831 prim: clean::PrimitiveType,
832 name: &str,
833 cx: &Context<'_>,
834 ) -> fmt::Result {
835 primitive_link_fragment(f, prim, name, "", cx)
836 }
837
838 fn primitive_link_fragment(
839 f: &mut fmt::Formatter<'_>,
840 prim: clean::PrimitiveType,
841 name: &str,
842 fragment: &str,
843 cx: &Context<'_>,
844 ) -> fmt::Result {
845 let m = &cx.cache();
846 let mut needs_termination = false;
847 if !f.alternate() {
848 match m.primitive_locations.get(&prim) {
849 Some(&def_id) if def_id.is_local() => {
850 let len = cx.current.len();
851 let len = if len == 0 { 0 } else { len - 1 };
852 write!(
853 f,
854 "<a class=\"primitive\" href=\"{}primitive.{}.html{fragment}\">",
855 "../".repeat(len),
856 prim.as_sym()
857 )?;
858 needs_termination = true;
859 }
860 Some(&def_id) => {
861 let loc = match m.extern_locations[&def_id.krate] {
862 ExternalLocation::Remote(ref s) => {
863 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
864 let builder: UrlPartsBuilder =
865 [s.as_str().trim_end_matches('/'), cname_sym.as_str()]
866 .into_iter()
867 .collect();
868 Some(builder)
869 }
870 ExternalLocation::Local => {
871 let cname_sym = ExternalCrate { crate_num: def_id.krate }.name(cx.tcx());
872 Some(if cx.current.first() == Some(&cname_sym) {
873 iter::repeat(sym::dotdot).take(cx.current.len() - 1).collect()
874 } else {
875 iter::repeat(sym::dotdot)
876 .take(cx.current.len())
877 .chain(iter::once(cname_sym))
878 .collect()
879 })
880 }
881 ExternalLocation::Unknown => None,
882 };
883 if let Some(mut loc) = loc {
884 loc.push_fmt(format_args!("primitive.{}.html", prim.as_sym()));
885 write!(f, "<a class=\"primitive\" href=\"{}{fragment}\">", loc.finish())?;
886 needs_termination = true;
887 }
888 }
889 None => {}
890 }
891 }
892 write!(f, "{}", name)?;
893 if needs_termination {
894 write!(f, "</a>")?;
895 }
896 Ok(())
897 }
898
899 /// Helper to render type parameters
900 fn tybounds<'a, 'tcx: 'a>(
901 bounds: &'a [clean::PolyTrait],
902 lt: &'a Option<clean::Lifetime>,
903 cx: &'a Context<'tcx>,
904 ) -> impl fmt::Display + 'a + Captures<'tcx> {
905 display_fn(move |f| {
906 for (i, bound) in bounds.iter().enumerate() {
907 if i > 0 {
908 write!(f, " + ")?;
909 }
910
911 fmt::Display::fmt(&bound.print(cx), f)?;
912 }
913
914 if let Some(lt) = lt {
915 write!(f, " + ")?;
916 fmt::Display::fmt(&lt.print(), f)?;
917 }
918 Ok(())
919 })
920 }
921
922 pub(crate) fn anchor<'a, 'cx: 'a>(
923 did: DefId,
924 text: Symbol,
925 cx: &'cx Context<'_>,
926 ) -> impl fmt::Display + 'a {
927 let parts = href(did, cx);
928 display_fn(move |f| {
929 if let Ok((url, short_ty, fqp)) = parts {
930 write!(
931 f,
932 r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
933 short_ty,
934 url,
935 short_ty,
936 join_with_double_colon(&fqp),
937 text.as_str()
938 )
939 } else {
940 write!(f, "{}", text)
941 }
942 })
943 }
944
945 fn fmt_type<'cx>(
946 t: &clean::Type,
947 f: &mut fmt::Formatter<'_>,
948 use_absolute: bool,
949 cx: &'cx Context<'_>,
950 ) -> fmt::Result {
951 trace!("fmt_type(t = {:?})", t);
952
953 match *t {
954 clean::Generic(name) => write!(f, "{}", name),
955 clean::Type::Path { ref path } => {
956 // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
957 let did = path.def_id();
958 resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
959 }
960 clean::DynTrait(ref bounds, ref lt) => {
961 f.write_str("dyn ")?;
962 fmt::Display::fmt(&tybounds(bounds, lt, cx), f)
963 }
964 clean::Infer => write!(f, "_"),
965 clean::Primitive(clean::PrimitiveType::Never) => {
966 primitive_link(f, PrimitiveType::Never, "!", cx)
967 }
968 clean::Primitive(prim) => primitive_link(f, prim, prim.as_sym().as_str(), cx),
969 clean::BareFunction(ref decl) => {
970 if f.alternate() {
971 write!(
972 f,
973 "{:#}{}{:#}fn{:#}",
974 decl.print_hrtb_with_space(cx),
975 decl.unsafety.print_with_space(),
976 print_abi_with_space(decl.abi),
977 decl.decl.print(cx),
978 )
979 } else {
980 write!(
981 f,
982 "{}{}{}",
983 decl.print_hrtb_with_space(cx),
984 decl.unsafety.print_with_space(),
985 print_abi_with_space(decl.abi)
986 )?;
987 primitive_link(f, PrimitiveType::Fn, "fn", cx)?;
988 write!(f, "{}", decl.decl.print(cx))
989 }
990 }
991 clean::Tuple(ref typs) => {
992 match &typs[..] {
993 &[] => primitive_link(f, PrimitiveType::Unit, "()", cx),
994 [one] => {
995 if let clean::Generic(name) = one {
996 primitive_link(f, PrimitiveType::Tuple, &format!("({name},)"), cx)
997 } else {
998 write!(f, "(")?;
999 // Carry `f.alternate()` into this display w/o branching manually.
1000 fmt::Display::fmt(&one.print(cx), f)?;
1001 write!(f, ",)")
1002 }
1003 }
1004 many => {
1005 let generic_names: Vec<Symbol> = many
1006 .iter()
1007 .filter_map(|t| match t {
1008 clean::Generic(name) => Some(*name),
1009 _ => None,
1010 })
1011 .collect();
1012 let is_generic = generic_names.len() == many.len();
1013 if is_generic {
1014 primitive_link(
1015 f,
1016 PrimitiveType::Tuple,
1017 &format!("({})", generic_names.iter().map(|s| s.as_str()).join(", ")),
1018 cx,
1019 )
1020 } else {
1021 write!(f, "(")?;
1022 for (i, item) in many.iter().enumerate() {
1023 if i != 0 {
1024 write!(f, ", ")?;
1025 }
1026 // Carry `f.alternate()` into this display w/o branching manually.
1027 fmt::Display::fmt(&item.print(cx), f)?;
1028 }
1029 write!(f, ")")
1030 }
1031 }
1032 }
1033 }
1034 clean::Slice(ref t) => match **t {
1035 clean::Generic(name) => {
1036 primitive_link(f, PrimitiveType::Slice, &format!("[{name}]"), cx)
1037 }
1038 _ => {
1039 write!(f, "[")?;
1040 fmt::Display::fmt(&t.print(cx), f)?;
1041 write!(f, "]")
1042 }
1043 },
1044 clean::Array(ref t, ref n) => match **t {
1045 clean::Generic(name) if !f.alternate() => primitive_link(
1046 f,
1047 PrimitiveType::Array,
1048 &format!("[{name}; {n}]", n = Escape(n)),
1049 cx,
1050 ),
1051 _ => {
1052 write!(f, "[")?;
1053 fmt::Display::fmt(&t.print(cx), f)?;
1054 if f.alternate() {
1055 write!(f, "; {n}")?;
1056 } else {
1057 write!(f, "; ")?;
1058 primitive_link(f, PrimitiveType::Array, &format!("{n}", n = Escape(n)), cx)?;
1059 }
1060 write!(f, "]")
1061 }
1062 },
1063 clean::RawPointer(m, ref t) => {
1064 let m = match m {
1065 hir::Mutability::Mut => "mut",
1066 hir::Mutability::Not => "const",
1067 };
1068
1069 if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
1070 let text = if f.alternate() {
1071 format!("*{} {:#}", m, t.print(cx))
1072 } else {
1073 format!("*{} {}", m, t.print(cx))
1074 };
1075 primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
1076 } else {
1077 primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?;
1078 fmt::Display::fmt(&t.print(cx), f)
1079 }
1080 }
1081 clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
1082 let lt = match l {
1083 Some(l) => format!("{} ", l.print()),
1084 _ => String::new(),
1085 };
1086 let m = mutability.print_with_space();
1087 let amp = if f.alternate() { "&" } else { "&amp;" };
1088 match **ty {
1089 clean::DynTrait(ref bounds, ref trait_lt)
1090 if bounds.len() > 1 || trait_lt.is_some() =>
1091 {
1092 write!(f, "{}{}{}(", amp, lt, m)?;
1093 fmt_type(ty, f, use_absolute, cx)?;
1094 write!(f, ")")
1095 }
1096 clean::Generic(name) => {
1097 primitive_link(f, PrimitiveType::Reference, &format!("{amp}{lt}{m}{name}"), cx)
1098 }
1099 _ => {
1100 write!(f, "{}{}{}", amp, lt, m)?;
1101 fmt_type(ty, f, use_absolute, cx)
1102 }
1103 }
1104 }
1105 clean::ImplTrait(ref bounds) => {
1106 if f.alternate() {
1107 write!(f, "impl {:#}", print_generic_bounds(bounds, cx))
1108 } else {
1109 write!(f, "impl {}", print_generic_bounds(bounds, cx))
1110 }
1111 }
1112 clean::QPath(box clean::QPathData {
1113 ref assoc,
1114 ref self_type,
1115 ref trait_,
1116 should_show_cast,
1117 }) => {
1118 if f.alternate() {
1119 if should_show_cast {
1120 write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
1121 } else {
1122 write!(f, "{:#}::", self_type.print(cx))?
1123 }
1124 } else {
1125 if should_show_cast {
1126 write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
1127 } else {
1128 write!(f, "{}::", self_type.print(cx))?
1129 }
1130 };
1131 // It's pretty unsightly to look at `<A as B>::C` in output, and
1132 // we've got hyperlinking on our side, so try to avoid longer
1133 // notation as much as possible by making `C` a hyperlink to trait
1134 // `B` to disambiguate.
1135 //
1136 // FIXME: this is still a lossy conversion and there should probably
1137 // be a better way of representing this in general? Most of
1138 // the ugliness comes from inlining across crates where
1139 // everything comes in as a fully resolved QPath (hard to
1140 // look at).
1141 if !f.alternate() && let Ok((url, _, path)) = href(trait_.def_id(), cx) {
1142 write!(
1143 f,
1144 "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
1145 title=\"type {path}::{name}\">{name}</a>",
1146 shortty = ItemType::AssocType,
1147 name = assoc.name,
1148 path = join_with_double_colon(&path),
1149 )
1150 } else {
1151 write!(f, "{}", assoc.name)
1152 }?;
1153
1154 // Carry `f.alternate()` into this display w/o branching manually.
1155 fmt::Display::fmt(&assoc.args.print(cx), f)
1156 }
1157 }
1158 }
1159
1160 impl clean::Type {
1161 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1162 &'a self,
1163 cx: &'a Context<'tcx>,
1164 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1165 display_fn(move |f| fmt_type(self, f, false, cx))
1166 }
1167 }
1168
1169 impl clean::Path {
1170 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1171 &'a self,
1172 cx: &'a Context<'tcx>,
1173 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1174 display_fn(move |f| resolved_path(f, self.def_id(), self, false, false, cx))
1175 }
1176 }
1177
1178 impl clean::Impl {
1179 pub(crate) fn print<'a, 'tcx: 'a>(
1180 &'a self,
1181 use_absolute: bool,
1182 cx: &'a Context<'tcx>,
1183 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1184 display_fn(move |f| {
1185 if f.alternate() {
1186 write!(f, "impl{:#} ", self.generics.print(cx))?;
1187 } else {
1188 write!(f, "impl{} ", self.generics.print(cx))?;
1189 }
1190
1191 if let Some(ref ty) = self.trait_ {
1192 match self.polarity {
1193 ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
1194 ty::ImplPolarity::Negative => write!(f, "!")?,
1195 }
1196 fmt::Display::fmt(&ty.print(cx), f)?;
1197 write!(f, " for ")?;
1198 }
1199
1200 if let clean::Type::Tuple(types) = &self.for_ &&
1201 let [clean::Type::Generic(name)] = &types[..] &&
1202 (self.kind.is_fake_variadic() || self.kind.is_auto())
1203 {
1204 // Hardcoded anchor library/core/src/primitive_docs.rs
1205 // Link should match `# Trait implementations`
1206 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("({name}₁, {name}₂, …, {name}ₙ)"), "#trait-implementations-1", cx)?;
1207 } else if let clean::BareFunction(bare_fn) = &self.for_ &&
1208 let [clean::Argument { type_: clean::Type::Generic(name), .. }] = &bare_fn.decl.inputs.values[..] &&
1209 (self.kind.is_fake_variadic() || self.kind.is_auto())
1210 {
1211 // Hardcoded anchor library/core/src/primitive_docs.rs
1212 // Link should match `# Trait implementations`
1213
1214 let hrtb = bare_fn.print_hrtb_with_space(cx);
1215 let unsafety = bare_fn.unsafety.print_with_space();
1216 let abi = print_abi_with_space(bare_fn.abi);
1217 if f.alternate() {
1218 write!(
1219 f,
1220 "{hrtb:#}{unsafety}{abi:#}",
1221 )?;
1222 } else {
1223 write!(
1224 f,
1225 "{hrtb}{unsafety}{abi}",
1226 )?;
1227 }
1228 let ellipsis = if bare_fn.decl.c_variadic {
1229 ", ..."
1230 } else {
1231 ""
1232 };
1233 primitive_link_fragment(f, PrimitiveType::Tuple, &format!("fn ({name}₁, {name}₂, …, {name}ₙ{ellipsis})"), "#trait-implementations-1", cx)?;
1234 // Write output.
1235 if let clean::FnRetTy::Return(ty) = &bare_fn.decl.output {
1236 write!(f, " -> ")?;
1237 fmt_type(ty, f, use_absolute, cx)?;
1238 }
1239 } else if let Some(ty) = self.kind.as_blanket_ty() {
1240 fmt_type(ty, f, use_absolute, cx)?;
1241 } else {
1242 fmt_type(&self.for_, f, use_absolute, cx)?;
1243 }
1244
1245 fmt::Display::fmt(&print_where_clause(&self.generics, cx, 0, Ending::Newline), f)?;
1246 Ok(())
1247 })
1248 }
1249 }
1250
1251 impl clean::Arguments {
1252 pub(crate) fn print<'a, 'tcx: 'a>(
1253 &'a self,
1254 cx: &'a Context<'tcx>,
1255 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1256 display_fn(move |f| {
1257 for (i, input) in self.values.iter().enumerate() {
1258 write!(f, "{}: ", input.name)?;
1259
1260 if f.alternate() {
1261 write!(f, "{:#}", input.type_.print(cx))?;
1262 } else {
1263 write!(f, "{}", input.type_.print(cx))?;
1264 }
1265 if i + 1 < self.values.len() {
1266 write!(f, ", ")?;
1267 }
1268 }
1269 Ok(())
1270 })
1271 }
1272 }
1273
1274 impl clean::FnRetTy {
1275 pub(crate) fn print<'a, 'tcx: 'a>(
1276 &'a self,
1277 cx: &'a Context<'tcx>,
1278 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1279 display_fn(move |f| match self {
1280 clean::Return(clean::Tuple(tys)) if tys.is_empty() => Ok(()),
1281 clean::Return(ty) if f.alternate() => {
1282 write!(f, " -> {:#}", ty.print(cx))
1283 }
1284 clean::Return(ty) => write!(f, " -&gt; {}", ty.print(cx)),
1285 clean::DefaultReturn => Ok(()),
1286 })
1287 }
1288 }
1289
1290 impl clean::BareFunctionDecl {
1291 fn print_hrtb_with_space<'a, 'tcx: 'a>(
1292 &'a self,
1293 cx: &'a Context<'tcx>,
1294 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1295 display_fn(move |f| {
1296 if !self.generic_params.is_empty() {
1297 write!(
1298 f,
1299 "for&lt;{}&gt; ",
1300 comma_sep(self.generic_params.iter().map(|g| g.print(cx)), true)
1301 )
1302 } else {
1303 Ok(())
1304 }
1305 })
1306 }
1307 }
1308
1309 // Implements Write but only counts the bytes "written".
1310 struct WriteCounter(usize);
1311
1312 impl std::fmt::Write for WriteCounter {
1313 fn write_str(&mut self, s: &str) -> fmt::Result {
1314 self.0 += s.len();
1315 Ok(())
1316 }
1317 }
1318
1319 // Implements Display by emitting the given number of spaces.
1320 struct Indent(usize);
1321
1322 impl fmt::Display for Indent {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 (0..self.0).for_each(|_| {
1325 f.write_char(' ').unwrap();
1326 });
1327 Ok(())
1328 }
1329 }
1330
1331 impl clean::FnDecl {
1332 pub(crate) fn print<'b, 'a: 'b, 'tcx: 'a>(
1333 &'a self,
1334 cx: &'a Context<'tcx>,
1335 ) -> impl fmt::Display + 'b + Captures<'tcx> {
1336 display_fn(move |f| {
1337 let ellipsis = if self.c_variadic { ", ..." } else { "" };
1338 if f.alternate() {
1339 write!(
1340 f,
1341 "({args:#}{ellipsis}){arrow:#}",
1342 args = self.inputs.print(cx),
1343 ellipsis = ellipsis,
1344 arrow = self.output.print(cx)
1345 )
1346 } else {
1347 write!(
1348 f,
1349 "({args}{ellipsis}){arrow}",
1350 args = self.inputs.print(cx),
1351 ellipsis = ellipsis,
1352 arrow = self.output.print(cx)
1353 )
1354 }
1355 })
1356 }
1357
1358 /// * `header_len`: The length of the function header and name. In other words, the number of
1359 /// characters in the function declaration up to but not including the parentheses.
1360 /// This is expected to go into a `<pre>`/`code-header` block, so indentation and newlines
1361 /// are preserved.
1362 /// * `indent`: The number of spaces to indent each successive line with, if line-wrapping is
1363 /// necessary.
1364 pub(crate) fn full_print<'a, 'tcx: 'a>(
1365 &'a self,
1366 header_len: usize,
1367 indent: usize,
1368 cx: &'a Context<'tcx>,
1369 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1370 display_fn(move |f| {
1371 // First, generate the text form of the declaration, with no line wrapping, and count the bytes.
1372 let mut counter = WriteCounter(0);
1373 write!(&mut counter, "{:#}", display_fn(|f| { self.inner_full_print(None, f, cx) }))
1374 .unwrap();
1375 // If the text form was over 80 characters wide, we will line-wrap our output.
1376 let line_wrapping_indent =
1377 if header_len + counter.0 > 80 { Some(indent) } else { None };
1378 // Generate the final output. This happens to accept `{:#}` formatting to get textual
1379 // output but in practice it is only formatted with `{}` to get HTML output.
1380 self.inner_full_print(line_wrapping_indent, f, cx)
1381 })
1382 }
1383
1384 fn inner_full_print(
1385 &self,
1386 // For None, the declaration will not be line-wrapped. For Some(n),
1387 // the declaration will be line-wrapped, with an indent of n spaces.
1388 line_wrapping_indent: Option<usize>,
1389 f: &mut fmt::Formatter<'_>,
1390 cx: &Context<'_>,
1391 ) -> fmt::Result {
1392 let amp = if f.alternate() { "&" } else { "&amp;" };
1393
1394 write!(f, "(")?;
1395 if let Some(n) = line_wrapping_indent {
1396 write!(f, "\n{}", Indent(n + 4))?;
1397 }
1398 for (i, input) in self.inputs.values.iter().enumerate() {
1399 if i > 0 {
1400 match line_wrapping_indent {
1401 None => write!(f, ", ")?,
1402 Some(n) => write!(f, ",\n{}", Indent(n + 4))?,
1403 };
1404 }
1405 if let Some(selfty) = input.to_self() {
1406 match selfty {
1407 clean::SelfValue => {
1408 write!(f, "self")?;
1409 }
1410 clean::SelfBorrowed(Some(ref lt), mtbl) => {
1411 write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?;
1412 }
1413 clean::SelfBorrowed(None, mtbl) => {
1414 write!(f, "{}{}self", amp, mtbl.print_with_space())?;
1415 }
1416 clean::SelfExplicit(ref typ) => {
1417 write!(f, "self: ")?;
1418 fmt::Display::fmt(&typ.print(cx), f)?;
1419 }
1420 }
1421 } else {
1422 if input.is_const {
1423 write!(f, "const ")?;
1424 }
1425 write!(f, "{}: ", input.name)?;
1426 fmt::Display::fmt(&input.type_.print(cx), f)?;
1427 }
1428 }
1429
1430 if self.c_variadic {
1431 match line_wrapping_indent {
1432 None => write!(f, ", ...")?,
1433 Some(n) => write!(f, "\n{}...", Indent(n + 4))?,
1434 };
1435 }
1436
1437 match line_wrapping_indent {
1438 None => write!(f, ")")?,
1439 Some(n) => write!(f, "\n{})", Indent(n))?,
1440 };
1441
1442 fmt::Display::fmt(&self.output.print(cx), f)?;
1443 Ok(())
1444 }
1445 }
1446
1447 pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
1448 visibility: Option<ty::Visibility<DefId>>,
1449 item_did: ItemId,
1450 cx: &'a Context<'tcx>,
1451 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1452 use std::fmt::Write as _;
1453
1454 let to_print: Cow<'static, str> = match visibility {
1455 None => "".into(),
1456 Some(ty::Visibility::Public) => "pub ".into(),
1457 Some(ty::Visibility::Restricted(vis_did)) => {
1458 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1459 // However, rustdoc currently never displays a module's
1460 // visibility, so it shouldn't matter.
1461 let parent_module = find_nearest_parent_module(cx.tcx(), item_did.expect_def_id());
1462
1463 if vis_did.is_crate_root() {
1464 "pub(crate) ".into()
1465 } else if parent_module == Some(vis_did) {
1466 // `pub(in foo)` where `foo` is the parent module
1467 // is the same as no visibility modifier
1468 "".into()
1469 } else if parent_module.and_then(|parent| find_nearest_parent_module(cx.tcx(), parent))
1470 == Some(vis_did)
1471 {
1472 "pub(super) ".into()
1473 } else {
1474 let path = cx.tcx().def_path(vis_did);
1475 debug!("path={:?}", path);
1476 // modified from `resolved_path()` to work with `DefPathData`
1477 let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
1478 let anchor = anchor(vis_did, last_name, cx);
1479
1480 let mut s = "pub(in ".to_owned();
1481 for seg in &path.data[..path.data.len() - 1] {
1482 let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
1483 }
1484 let _ = write!(s, "{}) ", anchor);
1485 s.into()
1486 }
1487 }
1488 };
1489 display_fn(move |f| write!(f, "{}", to_print))
1490 }
1491
1492 /// This function is the same as print_with_space, except that it renders no links.
1493 /// It's used for macros' rendered source view, which is syntax highlighted and cannot have
1494 /// any HTML in it.
1495 pub(crate) fn visibility_to_src_with_space<'a, 'tcx: 'a>(
1496 visibility: Option<ty::Visibility<DefId>>,
1497 tcx: TyCtxt<'tcx>,
1498 item_did: DefId,
1499 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1500 let to_print: Cow<'static, str> = match visibility {
1501 None => "".into(),
1502 Some(ty::Visibility::Public) => "pub ".into(),
1503 Some(ty::Visibility::Restricted(vis_did)) => {
1504 // FIXME(camelid): This may not work correctly if `item_did` is a module.
1505 // However, rustdoc currently never displays a module's
1506 // visibility, so it shouldn't matter.
1507 let parent_module = find_nearest_parent_module(tcx, item_did);
1508
1509 if vis_did.is_crate_root() {
1510 "pub(crate) ".into()
1511 } else if parent_module == Some(vis_did) {
1512 // `pub(in foo)` where `foo` is the parent module
1513 // is the same as no visibility modifier
1514 "".into()
1515 } else if parent_module.and_then(|parent| find_nearest_parent_module(tcx, parent))
1516 == Some(vis_did)
1517 {
1518 "pub(super) ".into()
1519 } else {
1520 format!("pub(in {}) ", tcx.def_path_str(vis_did)).into()
1521 }
1522 }
1523 };
1524 display_fn(move |f| f.write_str(&to_print))
1525 }
1526
1527 pub(crate) trait PrintWithSpace {
1528 fn print_with_space(&self) -> &str;
1529 }
1530
1531 impl PrintWithSpace for hir::Unsafety {
1532 fn print_with_space(&self) -> &str {
1533 match self {
1534 hir::Unsafety::Unsafe => "unsafe ",
1535 hir::Unsafety::Normal => "",
1536 }
1537 }
1538 }
1539
1540 impl PrintWithSpace for hir::IsAsync {
1541 fn print_with_space(&self) -> &str {
1542 match self {
1543 hir::IsAsync::Async => "async ",
1544 hir::IsAsync::NotAsync => "",
1545 }
1546 }
1547 }
1548
1549 impl PrintWithSpace for hir::Mutability {
1550 fn print_with_space(&self) -> &str {
1551 match self {
1552 hir::Mutability::Not => "",
1553 hir::Mutability::Mut => "mut ",
1554 }
1555 }
1556 }
1557
1558 pub(crate) fn print_constness_with_space(
1559 c: &hir::Constness,
1560 s: Option<ConstStability>,
1561 ) -> &'static str {
1562 match (c, s) {
1563 // const stable or when feature(staged_api) is not set
1564 (
1565 hir::Constness::Const,
1566 Some(ConstStability { level: StabilityLevel::Stable { .. }, .. }),
1567 )
1568 | (hir::Constness::Const, None) => "const ",
1569 // const unstable or not const
1570 _ => "",
1571 }
1572 }
1573
1574 impl clean::Import {
1575 pub(crate) fn print<'a, 'tcx: 'a>(
1576 &'a self,
1577 cx: &'a Context<'tcx>,
1578 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1579 display_fn(move |f| match self.kind {
1580 clean::ImportKind::Simple(name) => {
1581 if name == self.source.path.last() {
1582 write!(f, "use {};", self.source.print(cx))
1583 } else {
1584 write!(f, "use {} as {};", self.source.print(cx), name)
1585 }
1586 }
1587 clean::ImportKind::Glob => {
1588 if self.source.path.segments.is_empty() {
1589 write!(f, "use *;")
1590 } else {
1591 write!(f, "use {}::*;", self.source.print(cx))
1592 }
1593 }
1594 })
1595 }
1596 }
1597
1598 impl clean::ImportSource {
1599 pub(crate) fn print<'a, 'tcx: 'a>(
1600 &'a self,
1601 cx: &'a Context<'tcx>,
1602 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1603 display_fn(move |f| match self.did {
1604 Some(did) => resolved_path(f, did, &self.path, true, false, cx),
1605 _ => {
1606 for seg in &self.path.segments[..self.path.segments.len() - 1] {
1607 write!(f, "{}::", seg.name)?;
1608 }
1609 let name = self.path.last();
1610 if let hir::def::Res::PrimTy(p) = self.path.res {
1611 primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
1612 } else {
1613 write!(f, "{}", name)?;
1614 }
1615 Ok(())
1616 }
1617 })
1618 }
1619 }
1620
1621 impl clean::TypeBinding {
1622 pub(crate) fn print<'a, 'tcx: 'a>(
1623 &'a self,
1624 cx: &'a Context<'tcx>,
1625 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1626 display_fn(move |f| {
1627 f.write_str(self.assoc.name.as_str())?;
1628 if f.alternate() {
1629 write!(f, "{:#}", self.assoc.args.print(cx))?;
1630 } else {
1631 write!(f, "{}", self.assoc.args.print(cx))?;
1632 }
1633 match self.kind {
1634 clean::TypeBindingKind::Equality { ref term } => {
1635 if f.alternate() {
1636 write!(f, " = {:#}", term.print(cx))?;
1637 } else {
1638 write!(f, " = {}", term.print(cx))?;
1639 }
1640 }
1641 clean::TypeBindingKind::Constraint { ref bounds } => {
1642 if !bounds.is_empty() {
1643 if f.alternate() {
1644 write!(f, ": {:#}", print_generic_bounds(bounds, cx))?;
1645 } else {
1646 write!(f, ": {}", print_generic_bounds(bounds, cx))?;
1647 }
1648 }
1649 }
1650 }
1651 Ok(())
1652 })
1653 }
1654 }
1655
1656 pub(crate) fn print_abi_with_space(abi: Abi) -> impl fmt::Display {
1657 display_fn(move |f| {
1658 let quot = if f.alternate() { "\"" } else { "&quot;" };
1659 match abi {
1660 Abi::Rust => Ok(()),
1661 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1662 }
1663 })
1664 }
1665
1666 pub(crate) fn print_default_space<'a>(v: bool) -> &'a str {
1667 if v { "default " } else { "" }
1668 }
1669
1670 impl clean::GenericArg {
1671 pub(crate) fn print<'a, 'tcx: 'a>(
1672 &'a self,
1673 cx: &'a Context<'tcx>,
1674 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1675 display_fn(move |f| match self {
1676 clean::GenericArg::Lifetime(lt) => fmt::Display::fmt(&lt.print(), f),
1677 clean::GenericArg::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1678 clean::GenericArg::Const(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1679 clean::GenericArg::Infer => fmt::Display::fmt("_", f),
1680 })
1681 }
1682 }
1683
1684 impl clean::types::Term {
1685 pub(crate) fn print<'a, 'tcx: 'a>(
1686 &'a self,
1687 cx: &'a Context<'tcx>,
1688 ) -> impl fmt::Display + 'a + Captures<'tcx> {
1689 display_fn(move |f| match self {
1690 clean::types::Term::Type(ty) => fmt::Display::fmt(&ty.print(cx), f),
1691 clean::types::Term::Constant(ct) => fmt::Display::fmt(&ct.print(cx.tcx()), f),
1692 })
1693 }
1694 }
1695
1696 pub(crate) fn display_fn(
1697 f: impl FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1698 ) -> impl fmt::Display {
1699 struct WithFormatter<F>(Cell<Option<F>>);
1700
1701 impl<F> fmt::Display for WithFormatter<F>
1702 where
1703 F: FnOnce(&mut fmt::Formatter<'_>) -> fmt::Result,
1704 {
1705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1706 (self.0.take()).unwrap()(f)
1707 }
1708 }
1709
1710 WithFormatter(Cell::new(Some(f)))
1711 }