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 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
303 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
304 let &(ref fqp, shortty) = match cache.paths.get(&did) {
309 let mut url = if did.is_local() || cache.inlined.contains(&did) {
310 repeat("../").take(loc.len()).collect::<String>()
312 match cache.extern_locations[&did.krate] {
313 (_, render::Remote(ref s)) => s.to_string(),
314 (_, render::Local) => repeat("../").take(loc.len()).collect(),
315 (_, render::Unknown) => return None,
318 for component in &fqp[..fqp.len() - 1] {
319 url.push_str(component);
323 ItemType::Module => {
324 url.push_str(fqp.last().unwrap());
325 url.push_str("/index.html");
328 url.push_str(shortty.to_static_str());
330 url.push_str(fqp.last().unwrap());
331 url.push_str(".html");
334 Some((url, shortty, fqp.to_vec()))
337 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
338 /// rendering function with the necessary arguments for linking to a local path.
339 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
340 print_all: bool) -> fmt::Result {
341 let last = path.segments.last().unwrap();
342 let rel_root = match &*path.segments[0].name {
343 "self" => Some("./".to_string()),
348 let amt = path.segments.len() - 1;
351 for seg in &path.segments[..amt] {
352 if "super" == seg.name || "self" == seg.name {
353 write!(w, "{}::", seg.name)?;
355 root.push_str(&seg.name);
357 write!(w, "<a class='mod'
358 href='{}index.html'>{}</a>::",
365 for seg in &path.segments[..amt] {
366 write!(w, "{}::", seg.name)?;
371 write!(w, "{}{}", HRef::new(did, &last.name), last.params)?;
375 fn primitive_link(f: &mut fmt::Formatter,
376 prim: clean::PrimitiveType,
377 name: &str) -> fmt::Result {
379 let mut needs_termination = false;
380 match m.primitive_locations.get(&prim) {
381 Some(&LOCAL_CRATE) => {
382 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
383 let len = if len == 0 {0} else {len - 1};
384 write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
385 repeat("../").take(len).collect::<String>(),
387 needs_termination = true;
390 let path = &m.paths[&DefId {
392 index: CRATE_DEF_INDEX,
394 let loc = match m.extern_locations[&cnum] {
395 (_, render::Remote(ref s)) => Some(s.to_string()),
396 (_, render::Local) => {
397 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
398 Some(repeat("../").take(len).collect::<String>())
400 (_, render::Unknown) => None,
404 write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
406 path.0.first().unwrap(),
408 needs_termination = true;
415 write!(f, "{}", name)?;
416 if needs_termination {
422 /// Helper to render type parameters
423 fn tybounds(w: &mut fmt::Formatter,
424 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
426 Some(ref params) => {
427 for param in params {
429 write!(w, "{}", *param)?;
438 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
439 HRef { did: did, text: text }
443 impl<'a> fmt::Display for HRef<'a> {
444 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
445 match href(self.did) {
446 Some((url, shortty, fqp)) => {
447 write!(f, "<a class='{}' href='{}' title='{}'>{}</a>",
448 shortty, url, fqp.join("::"), self.text)
450 _ => write!(f, "{}", self.text),
455 impl fmt::Display for clean::Type {
456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 clean::Generic(ref name) => {
461 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
462 // Paths like T::Output and Self::Output should be rendered with all segments
463 resolved_path(f, did, path, is_generic)?;
464 tybounds(f, typarams)
466 clean::Infer => write!(f, "_"),
467 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
468 clean::BareFunction(ref decl) => {
469 write!(f, "{}{}fn{}{}",
470 UnsafetySpace(decl.unsafety),
472 "" => " extern ".to_string(),
473 "\"Rust\"" => "".to_string(),
474 s => format!(" extern {} ", s)
479 clean::Tuple(ref typs) => {
481 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
483 primitive_link(f, clean::PrimitiveTuple, "(")?;
484 write!(f, "{},", one)?;
485 primitive_link(f, clean::PrimitiveTuple, ")")
488 primitive_link(f, clean::PrimitiveTuple, "(")?;
489 write!(f, "{}", CommaSep(&many))?;
490 primitive_link(f, clean::PrimitiveTuple, ")")
494 clean::Vector(ref t) => {
495 primitive_link(f, clean::Slice, &format!("["))?;
497 primitive_link(f, clean::Slice, &format!("]"))
499 clean::FixedVector(ref t, ref s) => {
500 primitive_link(f, clean::PrimitiveType::Array, "[")?;
502 primitive_link(f, clean::PrimitiveType::Array,
503 &format!("; {}]", *s))
505 clean::Bottom => f.write_str("!"),
506 clean::RawPointer(m, ref t) => {
508 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
509 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
510 &format!("*{}{}", RawMutableSpace(m), t))
513 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
514 &format!("*{}", RawMutableSpace(m)))?;
519 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
521 Some(ref l) => format!("{} ", *l),
524 let m = MutableSpace(mutability);
526 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
529 primitive_link(f, clean::Slice,
530 &format!("&{}{}[{}]", lt, m, **bt)),
532 primitive_link(f, clean::Slice, &format!("&{}{}[", lt, m))?;
533 write!(f, "{}", **bt)?;
534 primitive_link(f, clean::Slice, "]")
539 write!(f, "&{}{}{}", lt, m, **ty)
543 clean::PolyTraitRef(ref bounds) => {
544 for (i, bound) in bounds.iter().enumerate() {
548 write!(f, "{}", *bound)?;
552 // It's pretty unsightly to look at `<A as B>::C` in output, and
553 // we've got hyperlinking on our side, so try to avoid longer
554 // notation as much as possible by making `C` a hyperlink to trait
555 // `B` to disambiguate.
557 // FIXME: this is still a lossy conversion and there should probably
558 // be a better way of representing this in general? Most of
559 // the ugliness comes from inlining across crates where
560 // everything comes in as a fully resolved QPath (hard to
565 trait_: box clean::ResolvedPath { did, ref typarams, .. },
567 write!(f, "{}::", self_type)?;
568 let path = clean::Path::singleton(name.clone());
569 resolved_path(f, did, &path, false)?;
571 // FIXME: `typarams` are not rendered, and this seems bad?
575 clean::QPath { ref name, ref self_type, ref trait_ } => {
576 write!(f, "<{} as {}>::{}", self_type, trait_, name)
578 clean::Unique(..) => {
579 panic!("should have been cleaned")
585 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
586 write!(f, "impl{} ", i.generics)?;
587 if let Some(ref ty) = i.trait_ {
589 if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
591 write!(f, "{}", *ty)?;
593 write!(f, "{}", ty.trait_name().unwrap())?;
597 write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
601 impl fmt::Display for clean::Impl {
602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
603 fmt_impl(self, f, true)
607 // The difference from above is that trait is not hyperlinked.
608 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
609 fmt_impl(i, f, false)
612 impl fmt::Display for clean::Arguments {
613 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614 for (i, input) in self.values.iter().enumerate() {
615 if i > 0 { write!(f, ", ")?; }
616 if !input.name.is_empty() {
617 write!(f, "{}: ", input.name)?;
619 write!(f, "{}", input.type_)?;
625 impl fmt::Display for clean::FunctionRetTy {
626 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
628 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
629 clean::Return(ref ty) => write!(f, " -> {}", ty),
630 clean::DefaultReturn => Ok(()),
631 clean::NoReturn => write!(f, " -> !")
636 impl fmt::Display for clean::FnDecl {
637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
639 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
641 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
646 impl<'a> fmt::Display for Method<'a> {
647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
648 let Method(selfty, d) = *self;
649 let mut args = String::new();
651 clean::SelfStatic => {},
652 clean::SelfValue => args.push_str("self"),
653 clean::SelfBorrowed(Some(ref lt), mtbl) => {
654 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
656 clean::SelfBorrowed(None, mtbl) => {
657 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
659 clean::SelfExplicit(ref typ) => {
660 args.push_str(&format!("self: {}", *typ));
663 for (i, input) in d.inputs.values.iter().enumerate() {
664 if i > 0 || !args.is_empty() { args.push_str(", "); }
665 if !input.name.is_empty() {
666 args.push_str(&format!("{}: ", input.name));
668 args.push_str(&format!("{}", input.type_));
670 write!(f, "({args}){arrow}", args = args, arrow = d.output)
674 impl<'a> fmt::Display for VisSpace<'a> {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
677 Some(clean::Public) => write!(f, "pub "),
678 Some(clean::Inherited) | None => Ok(())
683 impl fmt::Display for UnsafetySpace {
684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
686 hir::Unsafety::Unsafe => write!(f, "unsafe "),
687 hir::Unsafety::Normal => Ok(())
692 impl fmt::Display for ConstnessSpace {
693 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
695 hir::Constness::Const => write!(f, "const "),
696 hir::Constness::NotConst => Ok(())
701 impl fmt::Display for clean::Import {
702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704 clean::SimpleImport(ref name, ref src) => {
705 if *name == src.path.last_name() {
706 write!(f, "use {};", *src)
708 write!(f, "use {} as {};", *src, *name)
711 clean::GlobImport(ref src) => {
712 write!(f, "use {}::*;", *src)
714 clean::ImportList(ref src, ref names) => {
715 write!(f, "use {}::{{", *src)?;
716 for (i, n) in names.iter().enumerate() {
720 write!(f, "{}", *n)?;
728 impl fmt::Display for clean::ImportSource {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731 Some(did) => resolved_path(f, did, &self.path, true),
733 for (i, seg) in self.path.segments.iter().enumerate() {
737 write!(f, "{}", seg.name)?;
745 impl fmt::Display for clean::ViewListIdent {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
749 let path = clean::Path::singleton(self.name.clone());
750 resolved_path(f, did, &path, false)?;
752 _ => write!(f, "{}", self.name)?,
755 if let Some(ref name) = self.rename {
756 write!(f, " as {}", name)?;
762 impl fmt::Display for clean::TypeBinding {
763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
764 write!(f, "{}={}", self.name, self.ty)
768 impl fmt::Display for MutableSpace {
769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
771 MutableSpace(clean::Immutable) => Ok(()),
772 MutableSpace(clean::Mutable) => write!(f, "mut "),
777 impl fmt::Display for RawMutableSpace {
778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
780 RawMutableSpace(clean::Immutable) => write!(f, "const "),
781 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
786 impl fmt::Display for AbiSpace {
787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
790 Abi::C => write!(f, "extern "),
791 abi => write!(f, "extern {} ", abi),