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::metadata::cstore::LOCAL_CRATE;
22 use rustc::middle::def_id::DefId;
28 use html::item_type::ItemType;
30 use html::render::{cache, CURRENT_LOCATION_KEY};
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(pub Option<hir::Visibility>);
36 /// Similarly to VisSpace, this structure is used to render a function style with a
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::SelfTy, pub &'a clean::FnDecl);
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);
61 pub fn get(&self) -> Option<hir::Visibility> {
62 let VisSpace(v) = *self; v
67 pub fn get(&self) -> hir::Unsafety {
68 let UnsafetySpace(v) = *self; v
73 pub fn get(&self) -> hir::Constness {
74 let ConstnessSpace(v) = *self; v
78 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80 for (i, item) in self.0.iter().enumerate() {
81 if i != 0 { try!(write!(f, ", ")); }
82 try!(write!(f, "{}", item));
88 impl<'a> fmt::Display for TyParamBounds<'a> {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 let &TyParamBounds(bounds) = self;
91 for (i, bound) in bounds.iter().enumerate() {
93 try!(f.write_str(" + "));
95 try!(write!(f, "{}", *bound));
101 impl fmt::Display for clean::Generics {
102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
103 if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
104 try!(f.write_str("<"));
106 for (i, life) in self.lifetimes.iter().enumerate() {
108 try!(f.write_str(", "));
110 try!(write!(f, "{}", *life));
113 if !self.type_params.is_empty() {
114 if !self.lifetimes.is_empty() {
115 try!(f.write_str(", "));
117 for (i, tp) in self.type_params.iter().enumerate() {
119 try!(f.write_str(", "))
121 try!(f.write_str(&tp.name));
123 if !tp.bounds.is_empty() {
124 try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
128 Some(ref ty) => { try!(write!(f, " = {}", ty)); },
133 try!(f.write_str(">"));
138 impl<'a> fmt::Display for WhereClause<'a> {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 let &WhereClause(gens) = self;
141 if gens.where_predicates.is_empty() {
144 try!(f.write_str(" <span class='where'>where "));
145 for (i, pred) in gens.where_predicates.iter().enumerate() {
147 try!(f.write_str(", "));
150 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
152 try!(write!(f, "{}: {}", ty, TyParamBounds(bounds)));
154 &clean::WherePredicate::RegionPredicate { ref lifetime,
156 try!(write!(f, "{}: ", lifetime));
157 for (i, lifetime) in bounds.iter().enumerate() {
159 try!(f.write_str(" + "));
162 try!(write!(f, "{}", lifetime));
165 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
166 try!(write!(f, "{} == {}", lhs, rhs));
170 try!(f.write_str("</span>"));
175 impl fmt::Display for clean::Lifetime {
176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177 try!(f.write_str(self.get_ref()));
182 impl fmt::Display for clean::PolyTrait {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184 if !self.lifetimes.is_empty() {
185 try!(f.write_str("for<"));
186 for (i, lt) in self.lifetimes.iter().enumerate() {
188 try!(f.write_str(", "));
190 try!(write!(f, "{}", lt));
192 try!(f.write_str("> "));
194 write!(f, "{}", self.trait_)
198 impl fmt::Display for clean::TyParamBound {
199 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201 clean::RegionBound(ref lt) => {
204 clean::TraitBound(ref ty, modifier) => {
205 let modifier_str = match modifier {
206 hir::TraitBoundModifier::None => "",
207 hir::TraitBoundModifier::Maybe => "?",
209 write!(f, "{}{}", modifier_str, *ty)
215 impl fmt::Display for clean::PathParameters {
216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
218 clean::PathParameters::AngleBracketed {
219 ref lifetimes, ref types, ref bindings
221 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
222 try!(f.write_str("<"));
223 let mut comma = false;
224 for lifetime in lifetimes {
226 try!(f.write_str(", "));
229 try!(write!(f, "{}", *lifetime));
233 try!(f.write_str(", "));
236 try!(write!(f, "{}", *ty));
238 for binding in bindings {
240 try!(f.write_str(", "));
243 try!(write!(f, "{}", *binding));
245 try!(f.write_str(">"));
248 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
249 try!(f.write_str("("));
250 let mut comma = false;
253 try!(f.write_str(", "));
256 try!(write!(f, "{}", *ty));
258 try!(f.write_str(")"));
259 if let Some(ref ty) = *output {
260 try!(f.write_str(" -> "));
261 try!(write!(f, "{}", ty));
269 impl fmt::Display for clean::PathSegment {
270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271 try!(f.write_str(&self.name));
272 write!(f, "{}", self.params)
276 impl fmt::Display for clean::Path {
277 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279 try!(f.write_str("::"))
282 for (i, seg) in self.segments.iter().enumerate() {
284 try!(f.write_str("::"))
286 try!(write!(f, "{}", seg));
292 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
294 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
295 let &(ref fqp, shortty) = match cache.paths.get(&did) {
299 let mut url = if did.is_local() || cache.inlined.contains(&did) {
300 repeat("../").take(loc.len()).collect::<String>()
302 match cache.extern_locations[&did.krate] {
303 (_, render::Remote(ref s)) => s.to_string(),
304 (_, render::Local) => repeat("../").take(loc.len()).collect(),
305 (_, render::Unknown) => return None,
308 for component in &fqp[..fqp.len() - 1] {
309 url.push_str(component);
313 ItemType::Module => {
314 url.push_str(fqp.last().unwrap());
315 url.push_str("/index.html");
318 url.push_str(shortty.to_static_str());
320 url.push_str(fqp.last().unwrap());
321 url.push_str(".html");
324 Some((url, shortty, fqp.to_vec()))
327 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
328 /// rendering function with the necessary arguments for linking to a local path.
329 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
330 print_all: bool) -> fmt::Result {
331 let last = path.segments.last().unwrap();
332 let rel_root = match &*path.segments[0].name {
333 "self" => Some("./".to_string()),
338 let amt = path.segments.len() - 1;
341 for seg in &path.segments[..amt] {
342 if "super" == seg.name || "self" == seg.name {
343 try!(write!(w, "{}::", seg.name));
345 root.push_str(&seg.name);
347 try!(write!(w, "<a class='mod'
348 href='{}index.html'>{}</a>::",
355 for seg in &path.segments[..amt] {
356 try!(write!(w, "{}::", seg.name));
363 Some((url, shortty, fqp)) => {
364 try!(write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
365 shortty, url, fqp.join("::"), last.name));
367 _ => try!(write!(w, "{}", last.name)),
369 try!(write!(w, "{}", last.params));
373 fn primitive_link(f: &mut fmt::Formatter,
374 prim: clean::PrimitiveType,
375 name: &str) -> fmt::Result {
377 let mut needs_termination = false;
378 match m.primitive_locations.get(&prim) {
379 Some(&LOCAL_CRATE) => {
380 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
381 let len = if len == 0 {0} else {len - 1};
382 try!(write!(f, "<a href='{}primitive.{}.html'>",
383 repeat("../").take(len).collect::<String>(),
385 needs_termination = true;
388 let path = &m.paths[&DefId {
390 xxx_node: ast::CRATE_NODE_ID,
392 let loc = match m.extern_locations[&cnum] {
393 (_, render::Remote(ref s)) => Some(s.to_string()),
394 (_, render::Local) => {
395 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
396 Some(repeat("../").take(len).collect::<String>())
398 (_, render::Unknown) => None,
402 try!(write!(f, "<a href='{}{}/primitive.{}.html'>",
404 path.0.first().unwrap(),
406 needs_termination = true;
413 try!(write!(f, "{}", name));
414 if needs_termination {
415 try!(write!(f, "</a>"));
420 /// Helper to render type parameters
421 fn tybounds(w: &mut fmt::Formatter,
422 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
424 Some(ref params) => {
425 for param in params {
426 try!(write!(w, " + "));
427 try!(write!(w, "{}", *param));
435 impl fmt::Display for clean::Type {
436 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
438 clean::Generic(ref name) => {
441 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
442 // Paths like T::Output and Self::Output should be rendered with all segments
443 try!(resolved_path(f, did, path, is_generic));
444 tybounds(f, typarams)
446 clean::Infer => write!(f, "_"),
447 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
448 clean::BareFunction(ref decl) => {
449 write!(f, "{}{}fn{}{}",
450 UnsafetySpace(decl.unsafety),
452 "" => " extern ".to_string(),
453 "\"Rust\"" => "".to_string(),
454 s => format!(" extern {} ", s)
459 clean::Tuple(ref typs) => {
460 primitive_link(f, clean::PrimitiveTuple,
462 [ref one] => format!("({},)", one),
463 many => format!("({})", CommaSep(&many)),
466 clean::Vector(ref t) => {
467 primitive_link(f, clean::Slice, &format!("[{}]", **t))
469 clean::FixedVector(ref t, ref s) => {
470 primitive_link(f, clean::PrimitiveType::Array,
471 &format!("[{}; {}]", **t, *s))
473 clean::Bottom => f.write_str("!"),
474 clean::RawPointer(m, ref t) => {
475 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
476 &format!("*{}{}", RawMutableSpace(m), **t))
478 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
480 Some(ref l) => format!("{} ", *l),
483 let m = MutableSpace(mutability);
485 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
488 primitive_link(f, clean::Slice,
489 &format!("&{}{}[{}]", lt, m, **bt)),
491 try!(primitive_link(f, clean::Slice,
492 &format!("&{}{}[", lt, m)));
493 try!(write!(f, "{}", **bt));
494 primitive_link(f, clean::Slice, "]")
499 write!(f, "&{}{}{}", lt, m, **ty)
503 clean::PolyTraitRef(ref bounds) => {
504 for (i, bound) in bounds.iter().enumerate() {
506 try!(write!(f, " + "));
508 try!(write!(f, "{}", *bound));
512 // It's pretty unsightly to look at `<A as B>::C` in output, and
513 // we've got hyperlinking on our side, so try to avoid longer
514 // notation as much as possible by making `C` a hyperlink to trait
515 // `B` to disambiguate.
517 // FIXME: this is still a lossy conversion and there should probably
518 // be a better way of representing this in general? Most of
519 // the ugliness comes from inlining across crates where
520 // everything comes in as a fully resolved QPath (hard to
525 trait_: box clean::ResolvedPath { did, ref typarams, .. },
527 try!(write!(f, "{}::", self_type));
528 let path = clean::Path::singleton(name.clone());
529 try!(resolved_path(f, did, &path, false));
531 // FIXME: `typarams` are not rendered, and this seems bad?
535 clean::QPath { ref name, ref self_type, ref trait_ } => {
536 write!(f, "<{} as {}>::{}", self_type, trait_, name)
538 clean::Unique(..) => {
539 panic!("should have been cleaned")
545 impl fmt::Display for clean::Impl {
546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
547 try!(write!(f, "impl{} ", self.generics));
548 if let Some(ref ty) = self.trait_ {
549 try!(write!(f, "{}{} for ",
550 if self.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" },
553 try!(write!(f, "{}{}", self.for_, WhereClause(&self.generics)));
558 impl fmt::Display for clean::Arguments {
559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
560 for (i, input) in self.values.iter().enumerate() {
561 if i > 0 { try!(write!(f, ", ")); }
562 if !input.name.is_empty() {
563 try!(write!(f, "{}: ", input.name));
565 try!(write!(f, "{}", input.type_));
571 impl fmt::Display for clean::FunctionRetTy {
572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
574 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
575 clean::Return(ref ty) => write!(f, " -> {}", ty),
576 clean::DefaultReturn => Ok(()),
577 clean::NoReturn => write!(f, " -> !")
582 impl fmt::Display for clean::FnDecl {
583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
585 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
587 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
592 impl<'a> fmt::Display for Method<'a> {
593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
594 let Method(selfty, d) = *self;
595 let mut args = String::new();
597 clean::SelfStatic => {},
598 clean::SelfValue => args.push_str("self"),
599 clean::SelfBorrowed(Some(ref lt), mtbl) => {
600 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
602 clean::SelfBorrowed(None, mtbl) => {
603 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
605 clean::SelfExplicit(ref typ) => {
606 args.push_str(&format!("self: {}", *typ));
609 for (i, input) in d.inputs.values.iter().enumerate() {
610 if i > 0 || !args.is_empty() { args.push_str(", "); }
611 if !input.name.is_empty() {
612 args.push_str(&format!("{}: ", input.name));
614 args.push_str(&format!("{}", input.type_));
616 write!(f, "({args}){arrow}", args = args, arrow = d.output)
620 impl fmt::Display for VisSpace {
621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
623 Some(hir::Public) => write!(f, "pub "),
624 Some(hir::Inherited) | None => Ok(())
629 impl fmt::Display for UnsafetySpace {
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
632 hir::Unsafety::Unsafe => write!(f, "unsafe "),
633 hir::Unsafety::Normal => Ok(())
638 impl fmt::Display for ConstnessSpace {
639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
641 hir::Constness::Const => write!(f, "const "),
642 hir::Constness::NotConst => Ok(())
647 impl fmt::Display for clean::Import {
648 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
650 clean::SimpleImport(ref name, ref src) => {
651 if *name == src.path.segments.last().unwrap().name {
652 write!(f, "use {};", *src)
654 write!(f, "use {} as {};", *src, *name)
657 clean::GlobImport(ref src) => {
658 write!(f, "use {}::*;", *src)
660 clean::ImportList(ref src, ref names) => {
661 try!(write!(f, "use {}::{{", *src));
662 for (i, n) in names.iter().enumerate() {
664 try!(write!(f, ", "));
666 try!(write!(f, "{}", *n));
674 impl fmt::Display for clean::ImportSource {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677 Some(did) => resolved_path(f, did, &self.path, true),
679 for (i, seg) in self.path.segments.iter().enumerate() {
681 try!(write!(f, "::"))
683 try!(write!(f, "{}", seg.name));
691 impl fmt::Display for clean::ViewListIdent {
692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
695 let path = clean::Path::singleton(self.name.clone());
696 try!(resolved_path(f, did, &path, false));
698 _ => try!(write!(f, "{}", self.name)),
701 if let Some(ref name) = self.rename {
702 try!(write!(f, " as {}", name));
708 impl fmt::Display for clean::TypeBinding {
709 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
710 write!(f, "{}={}", self.name, self.ty)
714 impl fmt::Display for MutableSpace {
715 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
717 MutableSpace(clean::Immutable) => Ok(()),
718 MutableSpace(clean::Mutable) => write!(f, "mut "),
723 impl fmt::Display for RawMutableSpace {
724 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
726 RawMutableSpace(clean::Immutable) => write!(f, "const "),
727 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
732 impl fmt::Display for AbiSpace {
733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
736 Abi::C => write!(f, "extern "),
737 abi => write!(f, "extern {} ", abi),