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);
60 impl<'a> VisSpace<'a> {
61 pub fn get(self) -> &'a Option<clean::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 { write!(f, ", ")?; }
82 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() {
95 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 f.write_str("<")?;
106 for (i, life) in self.lifetimes.iter().enumerate() {
110 write!(f, "{}", *life)?;
113 if !self.type_params.is_empty() {
114 if !self.lifetimes.is_empty() {
117 for (i, tp) in self.type_params.iter().enumerate() {
121 f.write_str(&tp.name)?;
123 if !tp.bounds.is_empty() {
124 write!(f, ": {}", TyParamBounds(&tp.bounds))?;
128 Some(ref ty) => { write!(f, " = {}", ty)?; },
133 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 f.write_str(" <span class='where'>where ")?;
145 for (i, pred) in gens.where_predicates.iter().enumerate() {
150 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
152 write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
154 &clean::WherePredicate::RegionPredicate { ref lifetime,
156 write!(f, "{}: ", lifetime)?;
157 for (i, lifetime) in bounds.iter().enumerate() {
162 write!(f, "{}", lifetime)?;
165 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
166 write!(f, "{} == {}", lhs, rhs)?;
170 f.write_str("</span>")?;
175 impl fmt::Display for clean::Lifetime {
176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177 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 f.write_str("for<")?;
186 for (i, lt) in self.lifetimes.iter().enumerate() {
190 write!(f, "{}", lt)?;
192 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 f.write_str("<")?;
223 let mut comma = false;
224 for lifetime in lifetimes {
229 write!(f, "{}", *lifetime)?;
236 write!(f, "{}", *ty)?;
238 for binding in bindings {
243 write!(f, "{}", *binding)?;
245 f.write_str(">")?;
248 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
250 let mut comma = false;
256 write!(f, "{}", *ty)?;
259 if let Some(ref ty) = *output {
260 f.write_str(" -> ")?;
261 write!(f, "{}", ty)?;
269 impl fmt::Display for clean::PathSegment {
270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
271 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 {
282 for (i, seg) in self.segments.iter().enumerate() {
286 write!(f, "{}", seg)?;
292 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
294 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
298 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
299 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 match cache.extern_locations[&did.krate] {
308 (_, render::Remote(ref s)) => s.to_string(),
309 (_, render::Local) => repeat("../").take(loc.len()).collect(),
310 (_, render::Unknown) => return None,
313 for component in &fqp[..fqp.len() - 1] {
314 url.push_str(component);
318 ItemType::Module => {
319 url.push_str(fqp.last().unwrap());
320 url.push_str("/index.html");
323 url.push_str(shortty.to_static_str());
325 url.push_str(fqp.last().unwrap());
326 url.push_str(".html");
329 Some((url, shortty, fqp.to_vec()))
332 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
333 /// rendering function with the necessary arguments for linking to a local path.
334 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
335 print_all: bool) -> fmt::Result {
336 let last = path.segments.last().unwrap();
337 let rel_root = match &*path.segments[0].name {
338 "self" => Some("./".to_string()),
343 let amt = path.segments.len() - 1;
346 for seg in &path.segments[..amt] {
347 if "super" == seg.name || "self" == seg.name {
348 write!(w, "{}::", seg.name)?;
350 root.push_str(&seg.name);
352 write!(w, "<a class='mod'
353 href='{}index.html'>{}</a>::",
360 for seg in &path.segments[..amt] {
361 write!(w, "{}::", seg.name)?;
368 Some((url, shortty, fqp)) => {
369 write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
370 shortty, url, fqp.join("::"), last.name)?;
372 _ => write!(w, "{}", last.name)?,
374 write!(w, "{}", last.params)?;
378 fn primitive_link(f: &mut fmt::Formatter,
379 prim: clean::PrimitiveType,
380 name: &str) -> fmt::Result {
382 let mut needs_termination = false;
383 match m.primitive_locations.get(&prim) {
384 Some(&LOCAL_CRATE) => {
385 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
386 let len = if len == 0 {0} else {len - 1};
387 write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
388 repeat("../").take(len).collect::<String>(),
390 needs_termination = true;
393 let path = &m.paths[&DefId {
395 index: CRATE_DEF_INDEX,
397 let loc = match m.extern_locations[&cnum] {
398 (_, render::Remote(ref s)) => Some(s.to_string()),
399 (_, render::Local) => {
400 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
401 Some(repeat("../").take(len).collect::<String>())
403 (_, render::Unknown) => None,
407 write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
409 path.0.first().unwrap(),
411 needs_termination = true;
418 write!(f, "{}", name)?;
419 if needs_termination {
425 /// Helper to render type parameters
426 fn tybounds(w: &mut fmt::Formatter,
427 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
429 Some(ref params) => {
430 for param in params {
432 write!(w, "{}", *param)?;
440 impl fmt::Display for clean::Type {
441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 clean::Generic(ref name) => {
446 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
447 // Paths like T::Output and Self::Output should be rendered with all segments
448 resolved_path(f, did, path, is_generic)?;
449 tybounds(f, typarams)
451 clean::Infer => write!(f, "_"),
452 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
453 clean::BareFunction(ref decl) => {
454 write!(f, "{}{}fn{}{}",
455 UnsafetySpace(decl.unsafety),
457 "" => " extern ".to_string(),
458 "\"Rust\"" => "".to_string(),
459 s => format!(" extern {} ", s)
464 clean::Tuple(ref typs) => {
466 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
468 primitive_link(f, clean::PrimitiveTuple, "(")?;
469 write!(f, "{},", one)?;
470 primitive_link(f, clean::PrimitiveTuple, ")")
473 primitive_link(f, clean::PrimitiveTuple, "(")?;
474 write!(f, "{}", CommaSep(&many))?;
475 primitive_link(f, clean::PrimitiveTuple, ")")
479 clean::Vector(ref t) => {
480 primitive_link(f, clean::Slice, &format!("["))?;
482 primitive_link(f, clean::Slice, &format!("]"))
484 clean::FixedVector(ref t, ref s) => {
485 primitive_link(f, clean::PrimitiveType::Array, "[")?;
487 primitive_link(f, clean::PrimitiveType::Array,
488 &format!("; {}]", *s))
490 clean::Bottom => f.write_str("!"),
491 clean::RawPointer(m, ref t) => {
493 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
494 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
495 &format!("*{}{}", RawMutableSpace(m), t))
498 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
499 &format!("*{}", RawMutableSpace(m)))?;
504 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
506 Some(ref l) => format!("{} ", *l),
509 let m = MutableSpace(mutability);
511 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
514 primitive_link(f, clean::Slice,
515 &format!("&{}{}[{}]", lt, m, **bt)),
517 primitive_link(f, clean::Slice, &format!("&{}{}[", lt, m))?;
518 write!(f, "{}", **bt)?;
519 primitive_link(f, clean::Slice, "]")
524 write!(f, "&{}{}{}", lt, m, **ty)
528 clean::PolyTraitRef(ref bounds) => {
529 for (i, bound) in bounds.iter().enumerate() {
533 write!(f, "{}", *bound)?;
537 // It's pretty unsightly to look at `<A as B>::C` in output, and
538 // we've got hyperlinking on our side, so try to avoid longer
539 // notation as much as possible by making `C` a hyperlink to trait
540 // `B` to disambiguate.
542 // FIXME: this is still a lossy conversion and there should probably
543 // be a better way of representing this in general? Most of
544 // the ugliness comes from inlining across crates where
545 // everything comes in as a fully resolved QPath (hard to
550 trait_: box clean::ResolvedPath { did, ref typarams, .. },
552 write!(f, "{}::", self_type)?;
553 let path = clean::Path::singleton(name.clone());
554 resolved_path(f, did, &path, false)?;
556 // FIXME: `typarams` are not rendered, and this seems bad?
560 clean::QPath { ref name, ref self_type, ref trait_ } => {
561 write!(f, "<{} as {}>::{}", self_type, trait_, name)
563 clean::Unique(..) => {
564 panic!("should have been cleaned")
570 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
571 write!(f, "impl{} ", i.generics)?;
572 if let Some(ref ty) = i.trait_ {
574 if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
576 write!(f, "{}", *ty)?;
578 write!(f, "{}", ty.trait_name().unwrap())?;
582 write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
586 impl fmt::Display for clean::Impl {
587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
588 fmt_impl(self, f, true)
592 // The difference from above is that trait is not hyperlinked.
593 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
594 fmt_impl(i, f, false)
597 impl fmt::Display for clean::Arguments {
598 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
599 for (i, input) in self.values.iter().enumerate() {
600 if i > 0 { write!(f, ", ")?; }
601 if !input.name.is_empty() {
602 write!(f, "{}: ", input.name)?;
604 write!(f, "{}", input.type_)?;
610 impl fmt::Display for clean::FunctionRetTy {
611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
613 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
614 clean::Return(ref ty) => write!(f, " -> {}", ty),
615 clean::DefaultReturn => Ok(()),
616 clean::NoReturn => write!(f, " -> !")
621 impl fmt::Display for clean::FnDecl {
622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
624 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
626 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
631 impl<'a> fmt::Display for Method<'a> {
632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
633 let Method(selfty, d) = *self;
634 let mut args = String::new();
636 clean::SelfStatic => {},
637 clean::SelfValue => args.push_str("self"),
638 clean::SelfBorrowed(Some(ref lt), mtbl) => {
639 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
641 clean::SelfBorrowed(None, mtbl) => {
642 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
644 clean::SelfExplicit(ref typ) => {
645 args.push_str(&format!("self: {}", *typ));
648 for (i, input) in d.inputs.values.iter().enumerate() {
649 if i > 0 || !args.is_empty() { args.push_str(", "); }
650 if !input.name.is_empty() {
651 args.push_str(&format!("{}: ", input.name));
653 args.push_str(&format!("{}", input.type_));
655 write!(f, "({args}){arrow}", args = args, arrow = d.output)
659 impl<'a> fmt::Display for VisSpace<'a> {
660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
662 Some(clean::Public) => write!(f, "pub "),
663 Some(clean::Inherited) | None => Ok(())
668 impl fmt::Display for UnsafetySpace {
669 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
671 hir::Unsafety::Unsafe => write!(f, "unsafe "),
672 hir::Unsafety::Normal => Ok(())
677 impl fmt::Display for ConstnessSpace {
678 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
680 hir::Constness::Const => write!(f, "const "),
681 hir::Constness::NotConst => Ok(())
686 impl fmt::Display for clean::Import {
687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
689 clean::SimpleImport(ref name, ref src) => {
690 if *name == src.path.last_name() {
691 write!(f, "use {};", *src)
693 write!(f, "use {} as {};", *src, *name)
696 clean::GlobImport(ref src) => {
697 write!(f, "use {}::*;", *src)
699 clean::ImportList(ref src, ref names) => {
700 write!(f, "use {}::{{", *src)?;
701 for (i, n) in names.iter().enumerate() {
705 write!(f, "{}", *n)?;
713 impl fmt::Display for clean::ImportSource {
714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
716 Some(did) => resolved_path(f, did, &self.path, true),
718 for (i, seg) in self.path.segments.iter().enumerate() {
722 write!(f, "{}", seg.name)?;
730 impl fmt::Display for clean::ViewListIdent {
731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
734 let path = clean::Path::singleton(self.name.clone());
735 resolved_path(f, did, &path, false)?;
737 _ => write!(f, "{}", self.name)?,
740 if let Some(ref name) = self.rename {
741 write!(f, " as {}", name)?;
747 impl fmt::Display for clean::TypeBinding {
748 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
749 write!(f, "{}={}", self.name, self.ty)
753 impl fmt::Display for MutableSpace {
754 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
756 MutableSpace(clean::Immutable) => Ok(()),
757 MutableSpace(clean::Mutable) => write!(f, "mut "),
762 impl fmt::Display for RawMutableSpace {
763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
765 RawMutableSpace(clean::Immutable) => write!(f, "const "),
766 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
771 impl fmt::Display for AbiSpace {
772 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
775 Abi::C => write!(f, "extern "),
776 abi => write!(f, "extern {} ", abi),