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::hir::def_id::{CRATE_DEF_INDEX, DefId};
27 use core::DocAccessLevels;
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<'a>(pub &'a Option<clean::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);
65 impl<'a> VisSpace<'a> {
66 pub fn get(self) -> &'a Option<clean::Visibility> {
67 let VisSpace(v) = self; v
72 pub fn get(&self) -> hir::Unsafety {
73 let UnsafetySpace(v) = *self; v
78 pub fn get(&self) -> hir::Constness {
79 let ConstnessSpace(v) = *self; v
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 write!(f, "{}", item)?;
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() {
100 write!(f, "{}", *bound)?;
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 f.write_str("<")?;
111 for (i, life) in self.lifetimes.iter().enumerate() {
115 write!(f, "{}", *life)?;
118 if !self.type_params.is_empty() {
119 if !self.lifetimes.is_empty() {
122 for (i, tp) in self.type_params.iter().enumerate() {
126 f.write_str(&tp.name)?;
128 if !tp.bounds.is_empty() {
129 write!(f, ": {}", TyParamBounds(&tp.bounds))?;
133 Some(ref ty) => { write!(f, " = {}", ty)?; },
138 f.write_str(">")?;
143 impl<'a> fmt::Display for WhereClause<'a> {
144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 let &WhereClause(gens) = self;
146 if gens.where_predicates.is_empty() {
149 f.write_str(" <span class='where'>where ")?;
150 for (i, pred) in gens.where_predicates.iter().enumerate() {
155 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
157 write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
159 &clean::WherePredicate::RegionPredicate { ref lifetime,
161 write!(f, "{}: ", lifetime)?;
162 for (i, lifetime) in bounds.iter().enumerate() {
167 write!(f, "{}", lifetime)?;
170 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
171 write!(f, "{} == {}", lhs, rhs)?;
175 f.write_str("</span>")?;
180 impl fmt::Display for clean::Lifetime {
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 f.write_str(self.get_ref())?;
187 impl fmt::Display for clean::PolyTrait {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 if !self.lifetimes.is_empty() {
190 f.write_str("for<")?;
191 for (i, lt) in self.lifetimes.iter().enumerate() {
195 write!(f, "{}", lt)?;
197 f.write_str("> ")?;
199 write!(f, "{}", self.trait_)
203 impl fmt::Display for clean::TyParamBound {
204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 clean::RegionBound(ref lt) => {
209 clean::TraitBound(ref ty, modifier) => {
210 let modifier_str = match modifier {
211 hir::TraitBoundModifier::None => "",
212 hir::TraitBoundModifier::Maybe => "?",
214 write!(f, "{}{}", modifier_str, *ty)
220 impl fmt::Display for clean::PathParameters {
221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 clean::PathParameters::AngleBracketed {
224 ref lifetimes, ref types, ref bindings
226 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
227 f.write_str("<")?;
228 let mut comma = false;
229 for lifetime in lifetimes {
234 write!(f, "{}", *lifetime)?;
241 write!(f, "{}", *ty)?;
243 for binding in bindings {
248 write!(f, "{}", *binding)?;
250 f.write_str(">")?;
253 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
255 let mut comma = false;
261 write!(f, "{}", *ty)?;
264 if let Some(ref ty) = *output {
265 f.write_str(" -> ")?;
266 write!(f, "{}", ty)?;
274 impl fmt::Display for clean::PathSegment {
275 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276 f.write_str(&self.name)?;
277 write!(f, "{}", self.params)
281 impl fmt::Display for clean::Path {
282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287 for (i, seg) in self.segments.iter().enumerate() {
291 write!(f, "{}", seg)?;
297 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
299 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
300 let &(ref fqp, shortty) = match cache.paths.get(&did) {
304 let mut url = if did.is_local() || cache.inlined.contains(&did) {
305 repeat("../").take(loc.len()).collect::<String>()
307 if !cache.access_levels.is_doc_reachable(did) {
310 match cache.extern_locations[&did.krate] {
311 (_, render::Remote(ref s)) => s.to_string(),
312 (_, render::Local) => repeat("../").take(loc.len()).collect(),
313 (_, render::Unknown) => return None,
316 for component in &fqp[..fqp.len() - 1] {
317 url.push_str(component);
321 ItemType::Module => {
322 url.push_str(fqp.last().unwrap());
323 url.push_str("/index.html");
326 url.push_str(shortty.to_static_str());
328 url.push_str(fqp.last().unwrap());
329 url.push_str(".html");
332 Some((url, shortty, fqp.to_vec()))
335 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
336 /// rendering function with the necessary arguments for linking to a local path.
337 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
338 print_all: bool) -> fmt::Result {
339 let last = path.segments.last().unwrap();
340 let rel_root = match &*path.segments[0].name {
341 "self" => Some("./".to_string()),
346 let amt = path.segments.len() - 1;
349 for seg in &path.segments[..amt] {
350 if "super" == seg.name || "self" == seg.name {
351 write!(w, "{}::", seg.name)?;
353 root.push_str(&seg.name);
355 write!(w, "<a class='mod'
356 href='{}index.html'>{}</a>::",
363 for seg in &path.segments[..amt] {
364 write!(w, "{}::", seg.name)?;
369 write!(w, "{}{}", HRef::new(did, &last.name), 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 write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
383 repeat("../").take(len).collect::<String>(),
385 needs_termination = true;
388 let path = &m.paths[&DefId {
390 index: CRATE_DEF_INDEX,
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 write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
404 path.0.first().unwrap(),
406 needs_termination = true;
413 write!(f, "{}", name)?;
414 if needs_termination {
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 {
427 write!(w, "{}", *param)?;
436 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
437 HRef { did: did, text: text }
441 impl<'a> fmt::Display for HRef<'a> {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 match href(self.did) {
444 Some((url, shortty, fqp)) => {
445 write!(f, "<a class='{}' href='{}' title='{}'>{}</a>",
446 shortty, url, fqp.join("::"), self.text)
448 _ => write!(f, "{}", self.text),
453 impl fmt::Display for clean::Type {
454 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
456 clean::Generic(ref name) => {
459 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
460 // Paths like T::Output and Self::Output should be rendered with all segments
461 resolved_path(f, did, path, is_generic)?;
462 tybounds(f, typarams)
464 clean::Infer => write!(f, "_"),
465 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
466 clean::BareFunction(ref decl) => {
467 write!(f, "{}{}fn{}{}",
468 UnsafetySpace(decl.unsafety),
470 "" => " extern ".to_string(),
471 "\"Rust\"" => "".to_string(),
472 s => format!(" extern {} ", s)
477 clean::Tuple(ref typs) => {
479 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
481 primitive_link(f, clean::PrimitiveTuple, "(")?;
482 write!(f, "{},", one)?;
483 primitive_link(f, clean::PrimitiveTuple, ")")
486 primitive_link(f, clean::PrimitiveTuple, "(")?;
487 write!(f, "{}", CommaSep(&many))?;
488 primitive_link(f, clean::PrimitiveTuple, ")")
492 clean::Vector(ref t) => {
493 primitive_link(f, clean::Slice, &format!("["))?;
495 primitive_link(f, clean::Slice, &format!("]"))
497 clean::FixedVector(ref t, ref s) => {
498 primitive_link(f, clean::PrimitiveType::Array, "[")?;
500 primitive_link(f, clean::PrimitiveType::Array,
501 &format!("; {}]", *s))
503 clean::Bottom => f.write_str("!"),
504 clean::RawPointer(m, ref t) => {
506 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
507 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
508 &format!("*{}{}", RawMutableSpace(m), t))
511 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
512 &format!("*{}", RawMutableSpace(m)))?;
517 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
519 Some(ref l) => format!("{} ", *l),
522 let m = MutableSpace(mutability);
524 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
527 primitive_link(f, clean::Slice,
528 &format!("&{}{}[{}]", lt, m, **bt)),
530 primitive_link(f, clean::Slice, &format!("&{}{}[", lt, m))?;
531 write!(f, "{}", **bt)?;
532 primitive_link(f, clean::Slice, "]")
537 write!(f, "&{}{}{}", lt, m, **ty)
541 clean::PolyTraitRef(ref bounds) => {
542 for (i, bound) in bounds.iter().enumerate() {
546 write!(f, "{}", *bound)?;
550 // It's pretty unsightly to look at `<A as B>::C` in output, and
551 // we've got hyperlinking on our side, so try to avoid longer
552 // notation as much as possible by making `C` a hyperlink to trait
553 // `B` to disambiguate.
555 // FIXME: this is still a lossy conversion and there should probably
556 // be a better way of representing this in general? Most of
557 // the ugliness comes from inlining across crates where
558 // everything comes in as a fully resolved QPath (hard to
563 trait_: box clean::ResolvedPath { did, ref typarams, .. },
565 write!(f, "{}::", self_type)?;
566 let path = clean::Path::singleton(name.clone());
567 resolved_path(f, did, &path, false)?;
569 // FIXME: `typarams` are not rendered, and this seems bad?
573 clean::QPath { ref name, ref self_type, ref trait_ } => {
574 write!(f, "<{} as {}>::{}", self_type, trait_, name)
576 clean::Unique(..) => {
577 panic!("should have been cleaned")
583 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
584 write!(f, "impl{} ", i.generics)?;
585 if let Some(ref ty) = i.trait_ {
587 if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
589 write!(f, "{}", *ty)?;
591 write!(f, "{}", ty.trait_name().unwrap())?;
595 write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
599 impl fmt::Display for clean::Impl {
600 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601 fmt_impl(self, f, true)
605 // The difference from above is that trait is not hyperlinked.
606 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
607 fmt_impl(i, f, false)
610 impl fmt::Display for clean::Arguments {
611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
612 for (i, input) in self.values.iter().enumerate() {
613 if i > 0 { write!(f, ", ")?; }
614 if !input.name.is_empty() {
615 write!(f, "{}: ", input.name)?;
617 write!(f, "{}", input.type_)?;
623 impl fmt::Display for clean::FunctionRetTy {
624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
626 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
627 clean::Return(ref ty) => write!(f, " -> {}", ty),
628 clean::DefaultReturn => Ok(()),
629 clean::NoReturn => write!(f, " -> !")
634 impl fmt::Display for clean::FnDecl {
635 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
639 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
644 impl<'a> fmt::Display for Method<'a> {
645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
646 let Method(selfty, d) = *self;
647 let mut args = String::new();
649 clean::SelfStatic => {},
650 clean::SelfValue => args.push_str("self"),
651 clean::SelfBorrowed(Some(ref lt), mtbl) => {
652 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
654 clean::SelfBorrowed(None, mtbl) => {
655 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
657 clean::SelfExplicit(ref typ) => {
658 args.push_str(&format!("self: {}", *typ));
661 for (i, input) in d.inputs.values.iter().enumerate() {
662 if i > 0 || !args.is_empty() { args.push_str(", "); }
663 if !input.name.is_empty() {
664 args.push_str(&format!("{}: ", input.name));
666 args.push_str(&format!("{}", input.type_));
668 write!(f, "({args}){arrow}", args = args, arrow = d.output)
672 impl<'a> fmt::Display for VisSpace<'a> {
673 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
675 Some(clean::Public) => write!(f, "pub "),
676 Some(clean::Inherited) | None => Ok(())
681 impl fmt::Display for UnsafetySpace {
682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
684 hir::Unsafety::Unsafe => write!(f, "unsafe "),
685 hir::Unsafety::Normal => Ok(())
690 impl fmt::Display for ConstnessSpace {
691 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693 hir::Constness::Const => write!(f, "const "),
694 hir::Constness::NotConst => Ok(())
699 impl fmt::Display for clean::Import {
700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702 clean::SimpleImport(ref name, ref src) => {
703 if *name == src.path.last_name() {
704 write!(f, "use {};", *src)
706 write!(f, "use {} as {};", *src, *name)
709 clean::GlobImport(ref src) => {
710 write!(f, "use {}::*;", *src)
712 clean::ImportList(ref src, ref names) => {
713 write!(f, "use {}::{{", *src)?;
714 for (i, n) in names.iter().enumerate() {
718 write!(f, "{}", *n)?;
726 impl fmt::Display for clean::ImportSource {
727 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
729 Some(did) => resolved_path(f, did, &self.path, true),
731 for (i, seg) in self.path.segments.iter().enumerate() {
735 write!(f, "{}", seg.name)?;
743 impl fmt::Display for clean::ViewListIdent {
744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 let path = clean::Path::singleton(self.name.clone());
748 resolved_path(f, did, &path, false)?;
750 _ => write!(f, "{}", self.name)?,
753 if let Some(ref name) = self.rename {
754 write!(f, " as {}", name)?;
760 impl fmt::Display for clean::TypeBinding {
761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762 write!(f, "{}={}", self.name, self.ty)
766 impl fmt::Display for MutableSpace {
767 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769 MutableSpace(clean::Immutable) => Ok(()),
770 MutableSpace(clean::Mutable) => write!(f, "mut "),
775 impl fmt::Display for RawMutableSpace {
776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
778 RawMutableSpace(clean::Immutable) => write!(f, "const "),
779 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
784 impl fmt::Display for AbiSpace {
785 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
788 Abi::C => write!(f, "extern "),
789 abi => write!(f, "extern {} ", abi),