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