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