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.
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.
11 //! HTML formatting module
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.
19 use std
::iter
::repeat
;
21 use rustc
::middle
::cstore
::LOCAL_CRATE
;
22 use rustc
::middle
::def_id
::{CRATE_DEF_INDEX, DefId}
;
27 use html
::item_type
::ItemType
;
29 use html
::render
::{cache, CURRENT_LOCATION_KEY}
;
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(pub Option
<hir
::Visibility
>);
35 /// Similarly to VisSpace, this structure is used to render a function style with a
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 /// Wrapper struct for properly emitting a method declaration.
44 pub struct Method
<'a
>(pub &'a clean
::SelfTy
, pub &'a clean
::FnDecl
);
45 /// Similar to VisSpace, but used for mutability
46 #[derive(Copy, Clone)]
47 pub struct MutableSpace(pub clean
::Mutability
);
48 /// Similar to VisSpace, but used for mutability
49 #[derive(Copy, Clone)]
50 pub struct RawMutableSpace(pub clean
::Mutability
);
51 /// Wrapper struct for emitting a where clause from Generics.
52 pub struct WhereClause
<'a
>(pub &'a clean
::Generics
);
53 /// Wrapper struct for emitting type parameter bounds.
54 pub struct TyParamBounds
<'a
>(pub &'a
[clean
::TyParamBound
]);
55 /// Wrapper struct for emitting a comma-separated list of items
56 pub struct CommaSep
<'a
, T
: 'a
>(pub &'a
[T
]);
57 pub struct AbiSpace(pub Abi
);
60 pub fn get(&self) -> Option
<hir
::Visibility
> {
61 let VisSpace(v
) = *self; v
66 pub fn get(&self) -> hir
::Unsafety
{
67 let UnsafetySpace(v
) = *self; v
72 pub fn get(&self) -> hir
::Constness
{
73 let ConstnessSpace(v
) = *self; v
77 impl<'a
, T
: fmt
::Display
> fmt
::Display
for CommaSep
<'a
, T
> {
78 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
79 for (i
, item
) in self.0.iter
().enumerate() {
80 if i
!= 0 { try!(write!(f, ", ")); }
81 try
!(write
!(f
, "{}", item
));
87 impl<'a
> fmt
::Display
for TyParamBounds
<'a
> {
88 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
89 let &TyParamBounds(bounds
) = self;
90 for (i
, bound
) in bounds
.iter().enumerate() {
92 try
!(f
.write_str(" + "));
94 try
!(write
!(f
, "{}", *bound
));
100 impl fmt
::Display
for clean
::Generics
{
101 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
102 if self.lifetimes
.is_empty() && self.type_params
.is_empty() { return Ok(()) }
103 try
!(f
.write_str("<"));
105 for (i
, life
) in self.lifetimes
.iter().enumerate() {
107 try
!(f
.write_str(", "));
109 try
!(write
!(f
, "{}", *life
));
112 if !self.type_params
.is_empty() {
113 if !self.lifetimes
.is_empty() {
114 try
!(f
.write_str(", "));
116 for (i
, tp
) in self.type_params
.iter().enumerate() {
118 try
!(f
.write_str(", "))
120 try
!(f
.write_str(&tp
.name
));
122 if !tp
.bounds
.is_empty() {
123 try
!(write
!(f
, ": {}", TyParamBounds(&tp
.bounds
)));
127 Some(ref ty
) => { try!(write!(f, " = {}
", ty)); },
132 try!(f.write_str(">
;"));
137 impl<'a> fmt::Display for WhereClause<'a> {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 let &WhereClause(gens) = self;
140 if gens.where_predicates.is_empty() {
143 try!(f.write_str(" <span class
='
where'
>where "));
144 for (i, pred) in gens.where_predicates.iter().enumerate() {
146 try!(f.write_str(", "));
149 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
151 try!(write!(f, "{}
: {}
", ty, TyParamBounds(bounds)));
153 &clean::WherePredicate::RegionPredicate { ref lifetime,
155 try!(write!(f, "{}
: ", lifetime));
156 for (i, lifetime) in bounds.iter().enumerate() {
158 try!(f.write_str(" + "));
161 try!(write!(f, "{}
", lifetime));
164 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
165 try!(write!(f, "{}
== {}
", lhs, rhs));
169 try!(f.write_str("</span
>"));
174 impl fmt::Display for clean::Lifetime {
175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
176 try!(f.write_str(self.get_ref()));
181 impl fmt::Display for clean::PolyTrait {
182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
183 if !self.lifetimes.is_empty() {
184 try!(f.write_str("for<
;"));
185 for (i, lt) in self.lifetimes.iter().enumerate() {
187 try!(f.write_str(", "));
189 try!(write!(f, "{}
", lt));
191 try!(f.write_str(">
; "));
193 write!(f, "{}
", self.trait_)
197 impl fmt::Display for clean::TyParamBound {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
200 clean::RegionBound(ref lt) => {
203 clean::TraitBound(ref ty, modifier) => {
204 let modifier_str = match modifier {
205 hir::TraitBoundModifier::None => "",
206 hir::TraitBoundModifier::Maybe => "?
",
208 write!(f, "{}{}
", modifier_str, *ty)
214 impl fmt::Display for clean::PathParameters {
215 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 clean::PathParameters::AngleBracketed {
218 ref lifetimes, ref types, ref bindings
220 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
221 try!(f.write_str("<
;"));
222 let mut comma = false;
223 for lifetime in lifetimes {
225 try!(f.write_str(", "));
228 try!(write!(f, "{}
", *lifetime));
232 try!(f.write_str(", "));
235 try!(write!(f, "{}
", *ty));
237 for binding in bindings {
239 try!(f.write_str(", "));
242 try!(write!(f, "{}
", *binding));
244 try!(f.write_str(">
;"));
247 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
248 try!(f.write_str("("));
249 let mut comma = false;
252 try!(f.write_str(", "));
255 try!(write!(f, "{}
", *ty));
257 try!(f.write_str(")"));
258 if let Some(ref ty) = *output {
259 try!(f.write_str(" ->
; "));
260 try!(write!(f, "{}
", ty));
268 impl fmt::Display for clean::PathSegment {
269 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
270 try!(f.write_str(&self.name));
271 write!(f, "{}
", self.params)
275 impl fmt::Display for clean::Path {
276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278 try!(f.write_str("::"))
281 for (i, seg) in self.segments.iter().enumerate() {
283 try!(f.write_str("::"))
285 try!(write!(f, "{}
", seg));
291 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
293 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
294 let &(ref fqp, shortty) = match cache.paths.get(&did) {
298 let mut url = if did.is_local() || cache.inlined.contains(&did) {
299 repeat("../").take(loc.len()).collect::<String>()
301 match cache.extern_locations[&did.krate] {
302 (_, render::Remote(ref s)) => s.to_string(),
303 (_, render::Local) => repeat("../").take(loc.len()).collect(),
304 (_, render::Unknown) => return None,
307 for component in &fqp[..fqp.len() - 1] {
308 url.push_str(component);
312 ItemType::Module => {
313 url.push_str(fqp.last().unwrap());
314 url.push_str("/index
.html
");
317 url.push_str(shortty.to_static_str());
319 url.push_str(fqp.last().unwrap());
320 url.push_str(".html
");
323 Some((url, shortty, fqp.to_vec()))
326 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
327 /// rendering function with the necessary arguments for linking to a local path.
328 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
329 print_all: bool) -> fmt::Result {
330 let last = path.segments.last().unwrap();
331 let rel_root = match &*path.segments[0].name {
332 "self" => Some("./".to_string()),
337 let amt = path.segments.len() - 1;
340 for seg in &path.segments[..amt] {
341 if "super" == seg.name || "self" == seg.name {
342 try!(write!(w, "{}
::", seg.name));
344 root.push_str(&seg.name);
346 try!(write!(w, "<a class
='
mod'
347 href
='{}index
.html'
>{}
</a
>::",
354 for seg in &path.segments[..amt] {
355 try!(write!(w, "{}
::", seg.name));
362 Some((url, shortty, fqp)) => {
363 try!(write!(w, "<a class
='{}' href
='{}' title
='{}'
>{}
</a
>",
364 shortty, url, fqp.join("::"), last.name));
366 _ => try!(write!(w, "{}
", last.name)),
368 try!(write!(w, "{}
", last.params));
372 fn primitive_link(f: &mut fmt::Formatter,
373 prim: clean::PrimitiveType,
374 name: &str) -> fmt::Result {
376 let mut needs_termination = false;
377 match m.primitive_locations.get(&prim) {
378 Some(&LOCAL_CRATE) => {
379 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
380 let len = if len == 0 {0} else {len - 1};
381 try!(write!(f, "<a class
='primitive' href
='{}primitive
.{}
.html'
>",
382 repeat("../").take(len).collect::<String>(),
384 needs_termination = true;
387 let path = &m.paths[&DefId {
389 index: CRATE_DEF_INDEX,
391 let loc = match m.extern_locations[&cnum] {
392 (_, render::Remote(ref s)) => Some(s.to_string()),
393 (_, render::Local) => {
394 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
395 Some(repeat("../").take(len).collect::<String>())
397 (_, render::Unknown) => None,
401 try!(write!(f, "<a class
='primitive' href
='{}{}
/primitive
.{}
.html'
>",
403 path.0.first().unwrap(),
405 needs_termination = true;
412 try!(write!(f, "{}
", name));
413 if needs_termination {
414 try!(write!(f, "</a
>"));
419 /// Helper to render type parameters
420 fn tybounds(w: &mut fmt::Formatter,
421 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
423 Some(ref params) => {
424 for param in params {
425 try!(write!(w, " + "));
426 try!(write!(w, "{}
", *param));
434 impl fmt::Display for clean::Type {
435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
437 clean::Generic(ref name) => {
440 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
441 // Paths like T::Output and Self::Output should be rendered with all segments
442 try!(resolved_path(f, did, path, is_generic));
443 tybounds(f, typarams)
445 clean::Infer => write!(f, "_
"),
446 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
447 clean::BareFunction(ref decl) => {
448 write!(f, "{}{}
fn{}{}
",
449 UnsafetySpace(decl.unsafety),
451 "" => " extern ".to_string(),
452 "\"Rust
\"" => "".to_string(),
453 s => format!(" extern {}
", s)
458 clean::Tuple(ref typs) => {
460 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
462 try!(primitive_link(f, clean::PrimitiveTuple, "("));
463 try!(write!(f, "{}
,", one));
464 primitive_link(f, clean::PrimitiveTuple, ")")
467 try!(primitive_link(f, clean::PrimitiveTuple, "("));
468 try!(write!(f, "{}
", CommaSep(&many)));
469 primitive_link(f, clean::PrimitiveTuple, ")")
473 clean::Vector(ref t) => {
474 try!(primitive_link(f, clean::Slice, &format!("[")));
475 try!(write!(f, "{}
", t));
476 primitive_link(f, clean::Slice, &format!("]"))
478 clean::FixedVector(ref t, ref s) => {
479 try!(primitive_link(f, clean::PrimitiveType::Array, "["));
480 try!(write!(f, "{}
", t));
481 primitive_link(f, clean::PrimitiveType::Array,
482 &format!("; {}
]", *s))
484 clean::Bottom => f.write_str("!"),
485 clean::RawPointer(m, ref t) => {
487 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
488 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
489 &format!("*{}{}
", RawMutableSpace(m), t))
492 try!(primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
493 &format!("*{}
", RawMutableSpace(m))));
498 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
500 Some(ref l) => format!("{}
", *l),
503 let m = MutableSpace(mutability);
505 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
508 primitive_link(f, clean::Slice,
509 &format!("&
;{}{}
[{}
]", lt, m, **bt)),
511 try!(primitive_link(f, clean::Slice,
512 &format!("&
;{}{}
[", lt, m)));
513 try!(write!(f, "{}
", **bt));
514 primitive_link(f, clean::Slice, "]")
519 write!(f, "&
;{}{}{}
", lt, m, **ty)
523 clean::PolyTraitRef(ref bounds) => {
524 for (i, bound) in bounds.iter().enumerate() {
526 try!(write!(f, " + "));
528 try!(write!(f, "{}
", *bound));
532 // It's pretty unsightly to look at `<A as B>::C` in output, and
533 // we've got hyperlinking on our side, so try to avoid longer
534 // notation as much as possible by making `C` a hyperlink to trait
535 // `B` to disambiguate.
537 // FIXME: this is still a lossy conversion and there should probably
538 // be a better way of representing this in general? Most of
539 // the ugliness comes from inlining across crates where
540 // everything comes in as a fully resolved QPath (hard to
545 trait_: box clean::ResolvedPath { did, ref typarams, .. },
547 try!(write!(f, "{}
::", self_type));
548 let path = clean::Path::singleton(name.clone());
549 try!(resolved_path(f, did, &path, false));
551 // FIXME: `typarams` are not rendered, and this seems bad?
555 clean::QPath { ref name, ref self_type, ref trait_ } => {
556 write!(f, "<
;{}
as {}
>
;::{}
", self_type, trait_, name)
558 clean::Unique(..) => {
559 panic!("should have been cleaned
")
565 impl fmt::Display for clean::Impl {
566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
567 try!(write!(f, "impl{}
", self.generics));
568 if let Some(ref ty) = self.trait_ {
569 try!(write!(f, "{}{}
for ",
570 if self.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" },
573 try!(write!(f, "{}{}
", self.for_, WhereClause(&self.generics)));
578 impl fmt::Display for clean::Arguments {
579 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
580 for (i, input) in self.values.iter().enumerate() {
581 if i > 0 { try!(write!(f, ", ")); }
582 if !input.name.is_empty() {
583 try!(write!(f, "{}
: ", input.name));
585 try!(write!(f, "{}
", input.type_));
591 impl fmt::Display for clean::FunctionRetTy {
592 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
595 clean::Return(ref ty) => write!(f, " ->
; {}
", ty),
596 clean::DefaultReturn => Ok(()),
597 clean::NoReturn => write!(f, " ->
; !")
602 impl fmt::Display for clean::FnDecl {
603 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
605 write!(f, "({args}
, ...){arrow}
", args = self.inputs, arrow = self.output)
607 write!(f, "({args}
){arrow}
", args = self.inputs, arrow = self.output)
612 impl<'a> fmt::Display for Method<'a> {
613 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614 let Method(selfty, d) = *self;
615 let mut args = String::new();
617 clean::SelfStatic => {},
618 clean::SelfValue => args.push_str("self"),
619 clean::SelfBorrowed(Some(ref lt), mtbl) => {
620 args.push_str(&format!("&
;{} {}
self", *lt, MutableSpace(mtbl)));
622 clean::SelfBorrowed(None, mtbl) => {
623 args.push_str(&format!("&
;{}
self", MutableSpace(mtbl)));
625 clean::SelfExplicit(ref typ) => {
626 args.push_str(&format!("self: {}
", *typ));
629 for (i, input) in d.inputs.values.iter().enumerate() {
630 if i > 0 || !args.is_empty() { args.push_str(", "); }
631 if !input.name.is_empty() {
632 args.push_str(&format!("{}
: ", input.name));
634 args.push_str(&format!("{}
", input.type_));
636 write!(f, "({args}
){arrow}
", args = args, arrow = d.output)
640 impl fmt::Display for VisSpace {
641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
643 Some(hir::Public) => write!(f, "pub "),
644 Some(hir::Inherited) | None => Ok(())
649 impl fmt::Display for UnsafetySpace {
650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
652 hir::Unsafety::Unsafe => write!(f, "unsafe "),
653 hir::Unsafety::Normal => Ok(())
658 impl fmt::Display for ConstnessSpace {
659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
661 hir::Constness::Const => write!(f, "const "),
662 hir::Constness::NotConst => Ok(())
667 impl fmt::Display for clean::Import {
668 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
670 clean::SimpleImport(ref name, ref src) => {
671 if *name == src.path.segments.last().unwrap().name {
672 write!(f, "use {}
;", *src)
674 write!(f, "use {}
as {}
;", *src, *name)
677 clean::GlobImport(ref src) => {
678 write!(f, "use {}
::*;", *src)
680 clean::ImportList(ref src, ref names) => {
681 try!(write!(f, "use {}
::{{", *src));
682 for (i, n) in names.iter().enumerate() {
684 try!(write!(f, ", "));
686 try!(write!(f, "{}
", *n));
694 impl fmt::Display for clean::ImportSource {
695 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
697 Some(did) => resolved_path(f, did, &self.path, true),
699 for (i, seg) in self.path.segments.iter().enumerate() {
701 try!(write!(f, "::"))
703 try!(write!(f, "{}
", seg.name));
711 impl fmt::Display for clean::ViewListIdent {
712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
715 let path = clean::Path::singleton(self.name.clone());
716 try!(resolved_path(f, did, &path, false));
718 _ => try!(write!(f, "{}
", self.name)),
721 if let Some(ref name) = self.rename {
722 try!(write!(f, " as {}
", name));
728 impl fmt::Display for clean::TypeBinding {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730 write!(f, "{}
={}
", self.name, self.ty)
734 impl fmt::Display for MutableSpace {
735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
737 MutableSpace(clean::Immutable) => Ok(()),
738 MutableSpace(clean::Mutable) => write!(f, "mut "),
743 impl fmt::Display for RawMutableSpace {
744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
746 RawMutableSpace(clean::Immutable) => write!(f, "const "),
747 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
752 impl fmt::Display for AbiSpace {
753 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
756 Abi::C => write!(f, "extern "),
757 abi => write!(f, "extern {}
", abi),