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 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 if !cache.access_levels.is_doc_reachable(did) {
305 match cache.extern_locations[&did.krate] {
306 (_, render::Remote(ref s)) => s.to_string(),
307 (_, render::Local) => repeat("../").take(loc.len()).collect(),
308 (_, render::Unknown) => return None,
311 for component in &fqp[..fqp.len() - 1] {
312 url.push_str(component);
316 ItemType::Module => {
317 url.push_str(fqp.last().unwrap());
318 url.push_str("/index.html");
321 url.push_str(shortty.to_static_str());
323 url.push_str(fqp.last().unwrap());
324 url.push_str(".html");
327 Some((url, shortty, fqp.to_vec()))
330 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
331 /// rendering function with the necessary arguments for linking to a local path.
332 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
333 print_all: bool) -> fmt::Result {
334 let last = path.segments.last().unwrap();
335 let rel_root = match &*path.segments[0].name {
336 "self" => Some("./".to_string()),
341 let amt = path.segments.len() - 1;
344 for seg in &path.segments[..amt] {
345 if "super" == seg.name || "self" == seg.name {
346 write!(w, "{}::", seg.name)?;
348 root.push_str(&seg.name);
350 write!(w, "<a class='mod'
351 href='{}index.html'>{}</a>::",
358 for seg in &path.segments[..amt] {
359 write!(w, "{}::", seg.name)?;
366 Some((url, shortty, fqp)) => {
367 write!(w, "<a class='{}' href='{}' title='{}'>{}</a>",
368 shortty, url, fqp.join("::"), last.name)?;
370 _ => write!(w, "{}", last.name)?,
372 write!(w, "{}", last.params)?;
376 fn primitive_link(f: &mut fmt::Formatter,
377 prim: clean::PrimitiveType,
378 name: &str) -> fmt::Result {
380 let mut needs_termination = false;
381 match m.primitive_locations.get(&prim) {
382 Some(&LOCAL_CRATE) => {
383 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
384 let len = if len == 0 {0} else {len - 1};
385 write!(f, "<a class='primitive' href='{}primitive.{}.html'>",
386 repeat("../").take(len).collect::<String>(),
388 needs_termination = true;
391 let path = &m.paths[&DefId {
393 index: CRATE_DEF_INDEX,
395 let loc = match m.extern_locations[&cnum] {
396 (_, render::Remote(ref s)) => Some(s.to_string()),
397 (_, render::Local) => {
398 let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len());
399 Some(repeat("../").take(len).collect::<String>())
401 (_, render::Unknown) => None,
405 write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
407 path.0.first().unwrap(),
409 needs_termination = true;
416 write!(f, "{}", name)?;
417 if needs_termination {
423 /// Helper to render type parameters
424 fn tybounds(w: &mut fmt::Formatter,
425 typarams: &Option<Vec<clean::TyParamBound> >) -> fmt::Result {
427 Some(ref params) => {
428 for param in params {
430 write!(w, "{}", *param)?;
438 impl fmt::Display for clean::Type {
439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441 clean::Generic(ref name) => {
444 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
445 // Paths like T::Output and Self::Output should be rendered with all segments
446 resolved_path(f, did, path, is_generic)?;
447 tybounds(f, typarams)
449 clean::Infer => write!(f, "_"),
450 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
451 clean::BareFunction(ref decl) => {
452 write!(f, "{}{}fn{}{}",
453 UnsafetySpace(decl.unsafety),
455 "" => " extern ".to_string(),
456 "\"Rust\"" => "".to_string(),
457 s => format!(" extern {} ", s)
462 clean::Tuple(ref typs) => {
464 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
466 primitive_link(f, clean::PrimitiveTuple, "(")?;
467 write!(f, "{},", one)?;
468 primitive_link(f, clean::PrimitiveTuple, ")")
471 primitive_link(f, clean::PrimitiveTuple, "(")?;
472 write!(f, "{}", CommaSep(&many))?;
473 primitive_link(f, clean::PrimitiveTuple, ")")
477 clean::Vector(ref t) => {
478 primitive_link(f, clean::Slice, &format!("["))?;
480 primitive_link(f, clean::Slice, &format!("]"))
482 clean::FixedVector(ref t, ref s) => {
483 primitive_link(f, clean::PrimitiveType::Array, "[")?;
485 primitive_link(f, clean::PrimitiveType::Array,
486 &format!("; {}]", *s))
488 clean::Bottom => f.write_str("!"),
489 clean::RawPointer(m, ref t) => {
491 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
492 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
493 &format!("*{}{}", RawMutableSpace(m), t))
496 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
497 &format!("*{}", RawMutableSpace(m)))?;
502 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
504 Some(ref l) => format!("{} ", *l),
507 let m = MutableSpace(mutability);
509 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
512 primitive_link(f, clean::Slice,
513 &format!("&{}{}[{}]", lt, m, **bt)),
515 primitive_link(f, clean::Slice, &format!("&{}{}[", lt, m))?;
516 write!(f, "{}", **bt)?;
517 primitive_link(f, clean::Slice, "]")
522 write!(f, "&{}{}{}", lt, m, **ty)
526 clean::PolyTraitRef(ref bounds) => {
527 for (i, bound) in bounds.iter().enumerate() {
531 write!(f, "{}", *bound)?;
535 // It's pretty unsightly to look at `<A as B>::C` in output, and
536 // we've got hyperlinking on our side, so try to avoid longer
537 // notation as much as possible by making `C` a hyperlink to trait
538 // `B` to disambiguate.
540 // FIXME: this is still a lossy conversion and there should probably
541 // be a better way of representing this in general? Most of
542 // the ugliness comes from inlining across crates where
543 // everything comes in as a fully resolved QPath (hard to
548 trait_: box clean::ResolvedPath { did, ref typarams, .. },
550 write!(f, "{}::", self_type)?;
551 let path = clean::Path::singleton(name.clone());
552 resolved_path(f, did, &path, false)?;
554 // FIXME: `typarams` are not rendered, and this seems bad?
558 clean::QPath { ref name, ref self_type, ref trait_ } => {
559 write!(f, "<{} as {}>::{}", self_type, trait_, name)
561 clean::Unique(..) => {
562 panic!("should have been cleaned")
568 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
569 write!(f, "impl{} ", i.generics)?;
570 if let Some(ref ty) = i.trait_ {
572 if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
574 write!(f, "{}", *ty)?;
576 write!(f, "{}", ty.trait_name().unwrap())?;
580 write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
584 impl fmt::Display for clean::Impl {
585 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
586 fmt_impl(self, f, true)
590 // The difference from above is that trait is not hyperlinked.
591 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
592 fmt_impl(i, f, false)
595 impl fmt::Display for clean::Arguments {
596 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
597 for (i, input) in self.values.iter().enumerate() {
598 if i > 0 { write!(f, ", ")?; }
599 if !input.name.is_empty() {
600 write!(f, "{}: ", input.name)?;
602 write!(f, "{}", input.type_)?;
608 impl fmt::Display for clean::FunctionRetTy {
609 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
612 clean::Return(ref ty) => write!(f, " -> {}", ty),
613 clean::DefaultReturn => Ok(()),
614 clean::NoReturn => write!(f, " -> !")
619 impl fmt::Display for clean::FnDecl {
620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
622 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
624 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
629 impl<'a> fmt::Display for Method<'a> {
630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 let Method(selfty, d) = *self;
632 let mut args = String::new();
634 clean::SelfStatic => {},
635 clean::SelfValue => args.push_str("self"),
636 clean::SelfBorrowed(Some(ref lt), mtbl) => {
637 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
639 clean::SelfBorrowed(None, mtbl) => {
640 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
642 clean::SelfExplicit(ref typ) => {
643 args.push_str(&format!("self: {}", *typ));
646 for (i, input) in d.inputs.values.iter().enumerate() {
647 if i > 0 || !args.is_empty() { args.push_str(", "); }
648 if !input.name.is_empty() {
649 args.push_str(&format!("{}: ", input.name));
651 args.push_str(&format!("{}", input.type_));
653 write!(f, "({args}){arrow}", args = args, arrow = d.output)
657 impl<'a> fmt::Display for VisSpace<'a> {
658 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660 Some(clean::Public) => write!(f, "pub "),
661 Some(clean::Inherited) | None => Ok(())
666 impl fmt::Display for UnsafetySpace {
667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
669 hir::Unsafety::Unsafe => write!(f, "unsafe "),
670 hir::Unsafety::Normal => Ok(())
675 impl fmt::Display for ConstnessSpace {
676 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
678 hir::Constness::Const => write!(f, "const "),
679 hir::Constness::NotConst => Ok(())
684 impl fmt::Display for clean::Import {
685 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
687 clean::SimpleImport(ref name, ref src) => {
688 if *name == src.path.last_name() {
689 write!(f, "use {};", *src)
691 write!(f, "use {} as {};", *src, *name)
694 clean::GlobImport(ref src) => {
695 write!(f, "use {}::*;", *src)
697 clean::ImportList(ref src, ref names) => {
698 write!(f, "use {}::{{", *src)?;
699 for (i, n) in names.iter().enumerate() {
703 write!(f, "{}", *n)?;
711 impl fmt::Display for clean::ImportSource {
712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
714 Some(did) => resolved_path(f, did, &self.path, true),
716 for (i, seg) in self.path.segments.iter().enumerate() {
720 write!(f, "{}", seg.name)?;
728 impl fmt::Display for clean::ViewListIdent {
729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
732 let path = clean::Path::singleton(self.name.clone());
733 resolved_path(f, did, &path, false)?;
735 _ => write!(f, "{}", self.name)?,
738 if let Some(ref name) = self.rename {
739 write!(f, " as {}", name)?;
745 impl fmt::Display for clean::TypeBinding {
746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
747 write!(f, "{}={}", self.name, self.ty)
751 impl fmt::Display for MutableSpace {
752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
754 MutableSpace(clean::Immutable) => Ok(()),
755 MutableSpace(clean::Mutable) => write!(f, "mut "),
760 impl fmt::Display for RawMutableSpace {
761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
763 RawMutableSpace(clean::Immutable) => write!(f, "const "),
764 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
769 impl fmt::Display for AbiSpace {
770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
773 Abi::C => write!(f, "extern "),
774 abi => write!(f, "extern {} ", abi),