]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/html/format.rs
Updated version 1.19.0+dfsg1 from 'upstream/1.19.0+dfsg1'
[rustc.git] / src / librustdoc / html / format.rs
1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! HTML formatting module
12 //!
13 //! This module contains a large number of `fmt::Display` implementations for
14 //! various types in `rustdoc::clean`. These implementations all currently
15 //! assume that HTML output is desired, although it may be possible to redesign
16 //! them in the future to instead emit any format desired.
17
18 use std::fmt;
19 use std::iter::repeat;
20
21 use rustc::hir::def_id::DefId;
22 use syntax::abi::Abi;
23 use rustc::hir;
24
25 use clean::{self, PrimitiveType};
26 use core::DocAccessLevels;
27 use html::item_type::ItemType;
28 use html::render;
29 use html::render::{cache, CURRENT_LOCATION_KEY};
30
31 /// Helper to render an optional visibility with a space after it (if the
32 /// visibility is preset)
33 #[derive(Copy, Clone)]
34 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
35 /// Similarly to VisSpace, this structure is used to render a function style with a
36 /// space after it.
37 #[derive(Copy, Clone)]
38 pub struct UnsafetySpace(pub hir::Unsafety);
39 /// Similarly to VisSpace, this structure is used to render a function constness
40 /// with a space after it.
41 #[derive(Copy, Clone)]
42 pub struct ConstnessSpace(pub hir::Constness);
43 /// Similar to VisSpace, but used for mutability
44 #[derive(Copy, Clone)]
45 pub struct MutableSpace(pub clean::Mutability);
46 /// Similar to VisSpace, but used for mutability
47 #[derive(Copy, Clone)]
48 pub struct RawMutableSpace(pub clean::Mutability);
49 /// Wrapper struct for emitting type parameter bounds.
50 pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
51 /// Wrapper struct for emitting a comma-separated list of items
52 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
53 pub struct AbiSpace(pub Abi);
54
55 /// Wrapper struct for properly emitting a method declaration.
56 pub struct Method<'a> {
57 /// The declaration to emit.
58 pub decl: &'a clean::FnDecl,
59 /// The length of the function's "name", used to determine line-wrapping.
60 pub name_len: usize,
61 /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
62 pub indent: usize,
63 }
64
65 /// Wrapper struct for emitting a where clause from Generics.
66 pub struct WhereClause<'a>{
67 /// The Generics from which to emit a where clause.
68 pub gens: &'a clean::Generics,
69 /// The number of spaces to indent each line with.
70 pub indent: usize,
71 /// Whether the where clause needs to add a comma and newline after the last bound.
72 pub end_newline: bool,
73 }
74
75 pub struct HRef<'a> {
76 pub did: DefId,
77 pub text: &'a str,
78 }
79
80 impl<'a> VisSpace<'a> {
81 pub fn get(self) -> &'a Option<clean::Visibility> {
82 let VisSpace(v) = self; v
83 }
84 }
85
86 impl UnsafetySpace {
87 pub fn get(&self) -> hir::Unsafety {
88 let UnsafetySpace(v) = *self; v
89 }
90 }
91
92 impl ConstnessSpace {
93 pub fn get(&self) -> hir::Constness {
94 let ConstnessSpace(v) = *self; v
95 }
96 }
97
98 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
99 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100 for (i, item) in self.0.iter().enumerate() {
101 if i != 0 { write!(f, ", ")?; }
102 fmt::Display::fmt(item, f)?;
103 }
104 Ok(())
105 }
106 }
107
108 impl<'a> fmt::Display for TyParamBounds<'a> {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 let &TyParamBounds(bounds) = self;
111 for (i, bound) in bounds.iter().enumerate() {
112 if i > 0 {
113 f.write_str(" + ")?;
114 }
115 fmt::Display::fmt(bound, f)?;
116 }
117 Ok(())
118 }
119 }
120
121 impl fmt::Display for clean::Generics {
122 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
123 if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
124 if f.alternate() {
125 f.write_str("<")?;
126 } else {
127 f.write_str("&lt;")?;
128 }
129
130 for (i, life) in self.lifetimes.iter().enumerate() {
131 if i > 0 {
132 f.write_str(", ")?;
133 }
134 write!(f, "{}", *life)?;
135 }
136
137 if !self.type_params.is_empty() {
138 if !self.lifetimes.is_empty() {
139 f.write_str(", ")?;
140 }
141 for (i, tp) in self.type_params.iter().enumerate() {
142 if i > 0 {
143 f.write_str(", ")?
144 }
145 f.write_str(&tp.name)?;
146
147 if !tp.bounds.is_empty() {
148 if f.alternate() {
149 write!(f, ": {:#}", TyParamBounds(&tp.bounds))?;
150 } else {
151 write!(f, ":&nbsp;{}", TyParamBounds(&tp.bounds))?;
152 }
153 }
154
155 if let Some(ref ty) = tp.default {
156 if f.alternate() {
157 write!(f, " = {:#}", ty)?;
158 } else {
159 write!(f, "&nbsp;=&nbsp;{}", ty)?;
160 }
161 };
162 }
163 }
164 if f.alternate() {
165 f.write_str(">")?;
166 } else {
167 f.write_str("&gt;")?;
168 }
169 Ok(())
170 }
171 }
172
173 impl<'a> fmt::Display for WhereClause<'a> {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 let &WhereClause { gens, indent, end_newline } = self;
176 if gens.where_predicates.is_empty() {
177 return Ok(());
178 }
179 let mut clause = String::new();
180 if f.alternate() {
181 clause.push_str(" where");
182 } else {
183 if end_newline {
184 clause.push_str(" <span class=\"where fmt-newline\">where");
185 } else {
186 clause.push_str(" <span class=\"where\">where");
187 }
188 }
189 for (i, pred) in gens.where_predicates.iter().enumerate() {
190 if f.alternate() {
191 clause.push(' ');
192 } else {
193 clause.push_str("<br>");
194 }
195
196 match pred {
197 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
198 let bounds = bounds;
199 if f.alternate() {
200 clause.push_str(&format!("{:#}: {:#}", ty, TyParamBounds(bounds)));
201 } else {
202 clause.push_str(&format!("{}: {}", ty, TyParamBounds(bounds)));
203 }
204 }
205 &clean::WherePredicate::RegionPredicate { ref lifetime,
206 ref bounds } => {
207 clause.push_str(&format!("{}: ", lifetime));
208 for (i, lifetime) in bounds.iter().enumerate() {
209 if i > 0 {
210 clause.push_str(" + ");
211 }
212
213 clause.push_str(&format!("{}", lifetime));
214 }
215 }
216 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
217 if f.alternate() {
218 clause.push_str(&format!("{:#} == {:#}", lhs, rhs));
219 } else {
220 clause.push_str(&format!("{} == {}", lhs, rhs));
221 }
222 }
223 }
224
225 if i < gens.where_predicates.len() - 1 || end_newline {
226 clause.push(',');
227 }
228 }
229
230 if end_newline {
231 //add a space so stripping <br> tags and breaking spaces still renders properly
232 if f.alternate() {
233 clause.push(' ');
234 } else {
235 clause.push_str("&nbsp;");
236 }
237 }
238
239 if !f.alternate() {
240 clause.push_str("</span>");
241 let padding = repeat("&nbsp;").take(indent + 4).collect::<String>();
242 clause = clause.replace("<br>", &format!("<br>{}", padding));
243 clause.insert_str(0, &repeat("&nbsp;").take(indent.saturating_sub(1))
244 .collect::<String>());
245 if !end_newline {
246 clause.insert_str(0, "<br>");
247 }
248 }
249 write!(f, "{}", clause)
250 }
251 }
252
253 impl fmt::Display for clean::Lifetime {
254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255 f.write_str(self.get_ref())?;
256 Ok(())
257 }
258 }
259
260 impl fmt::Display for clean::PolyTrait {
261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262 if !self.lifetimes.is_empty() {
263 if f.alternate() {
264 f.write_str("for<")?;
265 } else {
266 f.write_str("for&lt;")?;
267 }
268 for (i, lt) in self.lifetimes.iter().enumerate() {
269 if i > 0 {
270 f.write_str(", ")?;
271 }
272 write!(f, "{}", lt)?;
273 }
274 if f.alternate() {
275 f.write_str("> ")?;
276 } else {
277 f.write_str("&gt; ")?;
278 }
279 }
280 if f.alternate() {
281 write!(f, "{:#}", self.trait_)
282 } else {
283 write!(f, "{}", self.trait_)
284 }
285 }
286 }
287
288 impl fmt::Display for clean::TyParamBound {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 match *self {
291 clean::RegionBound(ref lt) => {
292 write!(f, "{}", *lt)
293 }
294 clean::TraitBound(ref ty, modifier) => {
295 let modifier_str = match modifier {
296 hir::TraitBoundModifier::None => "",
297 hir::TraitBoundModifier::Maybe => "?",
298 };
299 if f.alternate() {
300 write!(f, "{}{:#}", modifier_str, *ty)
301 } else {
302 write!(f, "{}{}", modifier_str, *ty)
303 }
304 }
305 }
306 }
307 }
308
309 impl fmt::Display for clean::PathParameters {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 match *self {
312 clean::PathParameters::AngleBracketed {
313 ref lifetimes, ref types, ref bindings
314 } => {
315 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
316 if f.alternate() {
317 f.write_str("<")?;
318 } else {
319 f.write_str("&lt;")?;
320 }
321 let mut comma = false;
322 for lifetime in lifetimes {
323 if comma {
324 f.write_str(", ")?;
325 }
326 comma = true;
327 write!(f, "{}", *lifetime)?;
328 }
329 for ty in types {
330 if comma {
331 f.write_str(", ")?;
332 }
333 comma = true;
334 if f.alternate() {
335 write!(f, "{:#}", *ty)?;
336 } else {
337 write!(f, "{}", *ty)?;
338 }
339 }
340 for binding in bindings {
341 if comma {
342 f.write_str(", ")?;
343 }
344 comma = true;
345 if f.alternate() {
346 write!(f, "{:#}", *binding)?;
347 } else {
348 write!(f, "{}", *binding)?;
349 }
350 }
351 if f.alternate() {
352 f.write_str(">")?;
353 } else {
354 f.write_str("&gt;")?;
355 }
356 }
357 }
358 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
359 f.write_str("(")?;
360 let mut comma = false;
361 for ty in inputs {
362 if comma {
363 f.write_str(", ")?;
364 }
365 comma = true;
366 if f.alternate() {
367 write!(f, "{:#}", *ty)?;
368 } else {
369 write!(f, "{}", *ty)?;
370 }
371 }
372 f.write_str(")")?;
373 if let Some(ref ty) = *output {
374 if f.alternate() {
375 write!(f, " -> {:#}", ty)?;
376 } else {
377 write!(f, " -&gt; {}", ty)?;
378 }
379 }
380 }
381 }
382 Ok(())
383 }
384 }
385
386 impl fmt::Display for clean::PathSegment {
387 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
388 f.write_str(&self.name)?;
389 if f.alternate() {
390 write!(f, "{:#}", self.params)
391 } else {
392 write!(f, "{}", self.params)
393 }
394 }
395 }
396
397 impl fmt::Display for clean::Path {
398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399 if self.global {
400 f.write_str("::")?
401 }
402
403 for (i, seg) in self.segments.iter().enumerate() {
404 if i > 0 {
405 f.write_str("::")?
406 }
407 if f.alternate() {
408 write!(f, "{:#}", seg)?;
409 } else {
410 write!(f, "{}", seg)?;
411 }
412 }
413 Ok(())
414 }
415 }
416
417 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
418 let cache = cache();
419 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
420 return None
421 }
422
423 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
424 let (fqp, shortty, mut url) = match cache.paths.get(&did) {
425 Some(&(ref fqp, shortty)) => {
426 (fqp, shortty, repeat("../").take(loc.len()).collect())
427 }
428 None => match cache.external_paths.get(&did) {
429 Some(&(ref fqp, shortty)) => {
430 (fqp, shortty, match cache.extern_locations[&did.krate] {
431 (.., render::Remote(ref s)) => s.to_string(),
432 (.., render::Local) => repeat("../").take(loc.len()).collect(),
433 (.., render::Unknown) => return None,
434 })
435 }
436 None => return None,
437 }
438 };
439 for component in &fqp[..fqp.len() - 1] {
440 url.push_str(component);
441 url.push_str("/");
442 }
443 match shortty {
444 ItemType::Module => {
445 url.push_str(fqp.last().unwrap());
446 url.push_str("/index.html");
447 }
448 _ => {
449 url.push_str(shortty.css_class());
450 url.push_str(".");
451 url.push_str(fqp.last().unwrap());
452 url.push_str(".html");
453 }
454 }
455 Some((url, shortty, fqp.to_vec()))
456 }
457
458 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
459 /// rendering function with the necessary arguments for linking to a local path.
460 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
461 print_all: bool, use_absolute: bool) -> fmt::Result {
462 let empty = clean::PathSegment {
463 name: String::new(),
464 params: clean::PathParameters::Parenthesized {
465 inputs: Vec::new(),
466 output: None,
467 }
468 };
469 let last = path.segments.last()
470 .unwrap_or(&empty);
471 let rel_root = if path.segments.is_empty() {
472 None
473 } else {
474 match &*path.segments[0].name {
475 "self" => Some("./".to_string()),
476 _ => None,
477 }
478 };
479
480 if print_all {
481 let amt = path.segments.len() - 1;
482 match rel_root {
483 Some(mut root) => {
484 for seg in &path.segments[..amt] {
485 if "super" == seg.name || "self" == seg.name || w.alternate() {
486 write!(w, "{}::", seg.name)?;
487 } else {
488 root.push_str(&seg.name);
489 root.push_str("/");
490 write!(w, "<a class=\"mod\" href=\"{}index.html\">{}</a>::",
491 root,
492 seg.name)?;
493 }
494 }
495 }
496 None => {
497 for seg in &path.segments[..amt] {
498 write!(w, "{}::", seg.name)?;
499 }
500 }
501 }
502 }
503 if w.alternate() {
504 write!(w, "{:#}{:#}", HRef::new(did, &last.name), last.params)?;
505 } else {
506 let path = if use_absolute {
507 match href(did) {
508 Some((_, _, fqp)) => {
509 format!("{}::{}",
510 fqp[..fqp.len() - 1].join("::"),
511 HRef::new(did, fqp.last().unwrap_or(&String::new())))
512 }
513 None => format!("{}", HRef::new(did, &last.name)),
514 }
515 } else {
516 format!("{}", HRef::new(did, &last.name))
517 };
518 write!(w, "{}{}", path, last.params)?;
519 }
520 Ok(())
521 }
522
523 fn primitive_link(f: &mut fmt::Formatter,
524 prim: clean::PrimitiveType,
525 name: &str) -> fmt::Result {
526 let m = cache();
527 let mut needs_termination = false;
528 if !f.alternate() {
529 match m.primitive_locations.get(&prim) {
530 Some(&def_id) if def_id.is_local() => {
531 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
532 let len = if len == 0 {0} else {len - 1};
533 write!(f, "<a class=\"primitive\" href=\"{}primitive.{}.html\">",
534 repeat("../").take(len).collect::<String>(),
535 prim.to_url_str())?;
536 needs_termination = true;
537 }
538 Some(&def_id) => {
539 let loc = match m.extern_locations[&def_id.krate] {
540 (ref cname, _, render::Remote(ref s)) => {
541 Some((cname, s.to_string()))
542 }
543 (ref cname, _, render::Local) => {
544 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
545 Some((cname, repeat("../").take(len).collect::<String>()))
546 }
547 (.., render::Unknown) => None,
548 };
549 if let Some((cname, root)) = loc {
550 write!(f, "<a class=\"primitive\" href=\"{}{}/primitive.{}.html\">",
551 root,
552 cname,
553 prim.to_url_str())?;
554 needs_termination = true;
555 }
556 }
557 None => {}
558 }
559 }
560 write!(f, "{}", name)?;
561 if needs_termination {
562 write!(f, "</a>")?;
563 }
564 Ok(())
565 }
566
567 /// Helper to render type parameters
568 fn tybounds(w: &mut fmt::Formatter,
569 typarams: &Option<Vec<clean::TyParamBound>>) -> fmt::Result {
570 match *typarams {
571 Some(ref params) => {
572 for param in params {
573 write!(w, " + ")?;
574 fmt::Display::fmt(param, w)?;
575 }
576 Ok(())
577 }
578 None => Ok(())
579 }
580 }
581
582 impl<'a> HRef<'a> {
583 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
584 HRef { did: did, text: text }
585 }
586 }
587
588 impl<'a> fmt::Display for HRef<'a> {
589 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
590 match href(self.did) {
591 Some((url, shortty, fqp)) => if !f.alternate() {
592 write!(f, "<a class=\"{}\" href=\"{}\" title=\"{} {}\">{}</a>",
593 shortty, url, shortty, fqp.join("::"), self.text)
594 } else {
595 write!(f, "{}", self.text)
596 },
597 _ => write!(f, "{}", self.text),
598 }
599 }
600 }
601
602 fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter, use_absolute: bool) -> fmt::Result {
603 match *t {
604 clean::Generic(ref name) => {
605 f.write_str(name)
606 }
607 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
608 // Paths like T::Output and Self::Output should be rendered with all segments
609 resolved_path(f, did, path, is_generic, use_absolute)?;
610 tybounds(f, typarams)
611 }
612 clean::Infer => write!(f, "_"),
613 clean::Primitive(prim) => primitive_link(f, prim, prim.as_str()),
614 clean::BareFunction(ref decl) => {
615 if f.alternate() {
616 write!(f, "{}{}fn{:#}{:#}",
617 UnsafetySpace(decl.unsafety),
618 AbiSpace(decl.abi),
619 decl.generics,
620 decl.decl)
621 } else {
622 write!(f, "{}{}fn{}{}",
623 UnsafetySpace(decl.unsafety),
624 AbiSpace(decl.abi),
625 decl.generics,
626 decl.decl)
627 }
628 }
629 clean::Tuple(ref typs) => {
630 match &typs[..] {
631 &[] => primitive_link(f, PrimitiveType::Tuple, "()"),
632 &[ref one] => {
633 primitive_link(f, PrimitiveType::Tuple, "(")?;
634 //carry f.alternate() into this display w/o branching manually
635 fmt::Display::fmt(one, f)?;
636 primitive_link(f, PrimitiveType::Tuple, ",)")
637 }
638 many => {
639 primitive_link(f, PrimitiveType::Tuple, "(")?;
640 fmt::Display::fmt(&CommaSep(&many), f)?;
641 primitive_link(f, PrimitiveType::Tuple, ")")
642 }
643 }
644 }
645 clean::Slice(ref t) => {
646 primitive_link(f, PrimitiveType::Slice, "[")?;
647 fmt::Display::fmt(t, f)?;
648 primitive_link(f, PrimitiveType::Slice, "]")
649 }
650 clean::Array(ref t, n) => {
651 primitive_link(f, PrimitiveType::Array, "[")?;
652 fmt::Display::fmt(t, f)?;
653 primitive_link(f, PrimitiveType::Array, &format!("; {}]", n))
654 }
655 clean::Never => f.write_str("!"),
656 clean::RawPointer(m, ref t) => {
657 match **t {
658 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
659 if f.alternate() {
660 primitive_link(f, clean::PrimitiveType::RawPointer,
661 &format!("*{}{:#}", RawMutableSpace(m), t))
662 } else {
663 primitive_link(f, clean::PrimitiveType::RawPointer,
664 &format!("*{}{}", RawMutableSpace(m), t))
665 }
666 }
667 _ => {
668 primitive_link(f, clean::PrimitiveType::RawPointer,
669 &format!("*{}", RawMutableSpace(m)))?;
670 fmt::Display::fmt(t, f)
671 }
672 }
673 }
674 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
675 let lt = match *l {
676 Some(ref l) => format!("{} ", *l),
677 _ => "".to_string(),
678 };
679 let m = MutableSpace(mutability);
680 match **ty {
681 clean::Slice(ref bt) => { // BorrowedRef{ ... Slice(T) } is &[T]
682 match **bt {
683 clean::Generic(_) => {
684 if f.alternate() {
685 primitive_link(f, PrimitiveType::Slice,
686 &format!("&{}{}[{:#}]", lt, m, **bt))
687 } else {
688 primitive_link(f, PrimitiveType::Slice,
689 &format!("&amp;{}{}[{}]", lt, m, **bt))
690 }
691 }
692 _ => {
693 if f.alternate() {
694 primitive_link(f, PrimitiveType::Slice,
695 &format!("&{}{}[", lt, m))?;
696 write!(f, "{:#}", **bt)?;
697 } else {
698 primitive_link(f, PrimitiveType::Slice,
699 &format!("&amp;{}{}[", lt, m))?;
700 write!(f, "{}", **bt)?;
701 }
702 primitive_link(f, PrimitiveType::Slice, "]")
703 }
704 }
705 }
706 clean::ResolvedPath { typarams: Some(ref v), .. } if !v.is_empty() => {
707 if f.alternate() {
708 write!(f, "&{}{}", lt, m)?;
709 } else {
710 write!(f, "&amp;{}{}", lt, m)?;
711 }
712 write!(f, "(")?;
713 fmt_type(&ty, f, use_absolute)?;
714 write!(f, ")")
715 }
716 _ => {
717 if f.alternate() {
718 write!(f, "&{}{}", lt, m)?;
719 fmt_type(&ty, f, use_absolute)
720 } else {
721 write!(f, "&amp;{}{}", lt, m)?;
722 fmt_type(&ty, f, use_absolute)
723 }
724 }
725 }
726 }
727 clean::ImplTrait(ref bounds) => {
728 write!(f, "impl ")?;
729 for (i, bound) in bounds.iter().enumerate() {
730 if i != 0 {
731 write!(f, " + ")?;
732 }
733 if f.alternate() {
734 write!(f, "{:#}", *bound)?;
735 } else {
736 write!(f, "{}", *bound)?;
737 }
738 }
739 Ok(())
740 }
741 clean::QPath { ref name, ref self_type, ref trait_ } => {
742 let should_show_cast = match *trait_ {
743 box clean::ResolvedPath { .. } => {
744 let path = clean::Path::singleton(name.clone());
745 !path.segments.is_empty() && &format!("{:#}", trait_) != "()" &&
746 &format!("{:#}", self_type) != "Self"
747 }
748 _ => true,
749 };
750 if f.alternate() {
751 if should_show_cast {
752 write!(f, "<{:#} as {:#}>::", self_type, trait_)?
753 } else {
754 write!(f, "{:#}::", self_type)?
755 }
756 } else {
757 if should_show_cast {
758 write!(f, "&lt;{} as {}&gt;::", self_type, trait_)?
759 } else {
760 write!(f, "{}::", self_type)?
761 }
762 };
763 match *trait_ {
764 // It's pretty unsightly to look at `<A as B>::C` in output, and
765 // we've got hyperlinking on our side, so try to avoid longer
766 // notation as much as possible by making `C` a hyperlink to trait
767 // `B` to disambiguate.
768 //
769 // FIXME: this is still a lossy conversion and there should probably
770 // be a better way of representing this in general? Most of
771 // the ugliness comes from inlining across crates where
772 // everything comes in as a fully resolved QPath (hard to
773 // look at).
774 box clean::ResolvedPath { did, ref typarams, .. } => {
775 let path = clean::Path::singleton(name.clone());
776 resolved_path(f, did, &path, true, use_absolute)?;
777
778 // FIXME: `typarams` are not rendered, and this seems bad?
779 drop(typarams);
780 Ok(())
781 }
782 _ => {
783 write!(f, "{}", name)
784 }
785 }
786 }
787 clean::Unique(..) => {
788 panic!("should have been cleaned")
789 }
790 }
791 }
792
793 impl fmt::Display for clean::Type {
794 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
795 fmt_type(self, f, false)
796 }
797 }
798
799 fn fmt_impl(i: &clean::Impl,
800 f: &mut fmt::Formatter,
801 link_trait: bool,
802 use_absolute: bool) -> fmt::Result {
803 if f.alternate() {
804 write!(f, "impl{:#} ", i.generics)?;
805 } else {
806 write!(f, "impl{} ", i.generics)?;
807 }
808
809 if let Some(ref ty) = i.trait_ {
810 if i.polarity == Some(clean::ImplPolarity::Negative) {
811 write!(f, "!")?;
812 }
813
814 if link_trait {
815 fmt::Display::fmt(ty, f)?;
816 } else {
817 match *ty {
818 clean::ResolvedPath { typarams: None, ref path, is_generic: false, .. } => {
819 let last = path.segments.last().unwrap();
820 fmt::Display::fmt(&last.name, f)?;
821 fmt::Display::fmt(&last.params, f)?;
822 }
823 _ => unreachable!(),
824 }
825 }
826 write!(f, " for ")?;
827 }
828
829 fmt_type(&i.for_, f, use_absolute)?;
830
831 fmt::Display::fmt(&WhereClause { gens: &i.generics, indent: 0, end_newline: true }, f)?;
832 Ok(())
833 }
834
835 impl fmt::Display for clean::Impl {
836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
837 fmt_impl(self, f, true, false)
838 }
839 }
840
841 // The difference from above is that trait is not hyperlinked.
842 pub fn fmt_impl_for_trait_page(i: &clean::Impl,
843 f: &mut fmt::Formatter,
844 use_absolute: bool) -> fmt::Result {
845 fmt_impl(i, f, false, use_absolute)
846 }
847
848 impl fmt::Display for clean::Arguments {
849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
850 for (i, input) in self.values.iter().enumerate() {
851 if !input.name.is_empty() {
852 write!(f, "{}: ", input.name)?;
853 }
854 if f.alternate() {
855 write!(f, "{:#}", input.type_)?;
856 } else {
857 write!(f, "{}", input.type_)?;
858 }
859 if i + 1 < self.values.len() { write!(f, ", ")?; }
860 }
861 Ok(())
862 }
863 }
864
865 impl fmt::Display for clean::FunctionRetTy {
866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
867 match *self {
868 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
869 clean::Return(ref ty) if f.alternate() => write!(f, " -> {:#}", ty),
870 clean::Return(ref ty) => write!(f, " -&gt; {}", ty),
871 clean::DefaultReturn => Ok(()),
872 }
873 }
874 }
875
876 impl fmt::Display for clean::FnDecl {
877 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
878 if self.variadic {
879 if f.alternate() {
880 write!(f, "({args:#}, ...){arrow:#}", args = self.inputs, arrow = self.output)
881 } else {
882 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
883 }
884 } else {
885 if f.alternate() {
886 write!(f, "({args:#}){arrow:#}", args = self.inputs, arrow = self.output)
887 } else {
888 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
889 }
890 }
891 }
892 }
893
894 impl<'a> fmt::Display for Method<'a> {
895 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896 let &Method { decl, name_len, indent } = self;
897 let amp = if f.alternate() { "&" } else { "&amp;" };
898 let mut args = String::new();
899 let mut args_plain = String::new();
900 for (i, input) in decl.inputs.values.iter().enumerate() {
901 if i == 0 {
902 args.push_str("<br>");
903 }
904
905 if let Some(selfty) = input.to_self() {
906 match selfty {
907 clean::SelfValue => {
908 args.push_str("self");
909 args_plain.push_str("self");
910 }
911 clean::SelfBorrowed(Some(ref lt), mtbl) => {
912 args.push_str(&format!("{}{} {}self", amp, *lt, MutableSpace(mtbl)));
913 args_plain.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
914 }
915 clean::SelfBorrowed(None, mtbl) => {
916 args.push_str(&format!("{}{}self", amp, MutableSpace(mtbl)));
917 args_plain.push_str(&format!("&{}self", MutableSpace(mtbl)));
918 }
919 clean::SelfExplicit(ref typ) => {
920 if f.alternate() {
921 args.push_str(&format!("self: {:#}", *typ));
922 } else {
923 args.push_str(&format!("self: {}", *typ));
924 }
925 args_plain.push_str(&format!("self: {:#}", *typ));
926 }
927 }
928 } else {
929 if i > 0 {
930 args.push_str(" <br>");
931 args_plain.push_str(" ");
932 }
933 if !input.name.is_empty() {
934 args.push_str(&format!("{}: ", input.name));
935 args_plain.push_str(&format!("{}: ", input.name));
936 }
937
938 if f.alternate() {
939 args.push_str(&format!("{:#}", input.type_));
940 } else {
941 args.push_str(&format!("{}", input.type_));
942 }
943 args_plain.push_str(&format!("{:#}", input.type_));
944 }
945 if i + 1 < decl.inputs.values.len() {
946 args.push(',');
947 args_plain.push(',');
948 }
949 }
950
951 if decl.variadic {
952 args.push_str(",<br> ...");
953 args_plain.push_str(", ...");
954 }
955
956 let arrow_plain = format!("{:#}", decl.output);
957 let arrow = if f.alternate() {
958 format!("{:#}", decl.output)
959 } else {
960 format!("{}", decl.output)
961 };
962
963 let pad = repeat(" ").take(name_len).collect::<String>();
964 let plain = format!("{pad}({args}){arrow}",
965 pad = pad,
966 args = args_plain,
967 arrow = arrow_plain);
968
969 let output = if plain.len() > 80 {
970 let full_pad = format!("<br>{}", repeat("&nbsp;").take(indent + 4).collect::<String>());
971 let close_pad = format!("<br>{}", repeat("&nbsp;").take(indent).collect::<String>());
972 format!("({args}{close}){arrow}",
973 args = args.replace("<br>", &full_pad),
974 close = close_pad,
975 arrow = arrow)
976 } else {
977 format!("({args}){arrow}", args = args.replace("<br>", ""), arrow = arrow)
978 };
979
980 if f.alternate() {
981 write!(f, "{}", output.replace("<br>", "\n"))
982 } else {
983 write!(f, "{}", output)
984 }
985 }
986 }
987
988 impl<'a> fmt::Display for VisSpace<'a> {
989 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
990 match *self.get() {
991 Some(clean::Public) => write!(f, "pub "),
992 Some(clean::Inherited) | None => Ok(())
993 }
994 }
995 }
996
997 impl fmt::Display for UnsafetySpace {
998 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
999 match self.get() {
1000 hir::Unsafety::Unsafe => write!(f, "unsafe "),
1001 hir::Unsafety::Normal => Ok(())
1002 }
1003 }
1004 }
1005
1006 impl fmt::Display for ConstnessSpace {
1007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1008 match self.get() {
1009 hir::Constness::Const => write!(f, "const "),
1010 hir::Constness::NotConst => Ok(())
1011 }
1012 }
1013 }
1014
1015 impl fmt::Display for clean::Import {
1016 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1017 match *self {
1018 clean::Import::Simple(ref name, ref src) => {
1019 if *name == src.path.last_name() {
1020 write!(f, "use {};", *src)
1021 } else {
1022 write!(f, "use {} as {};", *src, *name)
1023 }
1024 }
1025 clean::Import::Glob(ref src) => {
1026 write!(f, "use {}::*;", *src)
1027 }
1028 }
1029 }
1030 }
1031
1032 impl fmt::Display for clean::ImportSource {
1033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1034 match self.did {
1035 Some(did) => resolved_path(f, did, &self.path, true, false),
1036 _ => {
1037 for (i, seg) in self.path.segments.iter().enumerate() {
1038 if i > 0 {
1039 write!(f, "::")?
1040 }
1041 write!(f, "{}", seg.name)?;
1042 }
1043 Ok(())
1044 }
1045 }
1046 }
1047 }
1048
1049 impl fmt::Display for clean::TypeBinding {
1050 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1051 if f.alternate() {
1052 write!(f, "{} = {:#}", self.name, self.ty)
1053 } else {
1054 write!(f, "{} = {}", self.name, self.ty)
1055 }
1056 }
1057 }
1058
1059 impl fmt::Display for MutableSpace {
1060 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1061 match *self {
1062 MutableSpace(clean::Immutable) => Ok(()),
1063 MutableSpace(clean::Mutable) => write!(f, "mut "),
1064 }
1065 }
1066 }
1067
1068 impl fmt::Display for RawMutableSpace {
1069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1070 match *self {
1071 RawMutableSpace(clean::Immutable) => write!(f, "const "),
1072 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
1073 }
1074 }
1075 }
1076
1077 impl fmt::Display for AbiSpace {
1078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1079 let quot = if f.alternate() { "\"" } else { "&quot;" };
1080 match self.0 {
1081 Abi::Rust => Ok(()),
1082 abi => write!(f, "extern {0}{1}{0} ", quot, abi.name()),
1083 }
1084 }
1085 }