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;
29 use html::escape::Escape;
31 use html::render::{cache, CURRENT_LOCATION_KEY};
33 /// Helper to render an optional visibility with a space after it (if the
34 /// visibility is preset)
35 #[derive(Copy, Clone)]
36 pub struct VisSpace<'a>(pub &'a Option<clean::Visibility>);
37 /// Similarly to VisSpace, this structure is used to render a function style with a
39 #[derive(Copy, Clone)]
40 pub struct UnsafetySpace(pub hir::Unsafety);
41 /// Similarly to VisSpace, this structure is used to render a function constness
42 /// with a space after it.
43 #[derive(Copy, Clone)]
44 pub struct ConstnessSpace(pub hir::Constness);
45 /// Wrapper struct for properly emitting a method declaration.
46 pub struct Method<'a>(pub &'a clean::FnDecl);
47 /// Similar to VisSpace, but used for mutability
48 #[derive(Copy, Clone)]
49 pub struct MutableSpace(pub clean::Mutability);
50 /// Similar to VisSpace, but used for mutability
51 #[derive(Copy, Clone)]
52 pub struct RawMutableSpace(pub clean::Mutability);
53 /// Wrapper struct for emitting a where clause from Generics.
54 pub struct WhereClause<'a>(pub &'a clean::Generics);
55 /// Wrapper struct for emitting type parameter bounds.
56 pub struct TyParamBounds<'a>(pub &'a [clean::TyParamBound]);
57 /// Wrapper struct for emitting a comma-separated list of items
58 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
59 pub struct AbiSpace(pub Abi);
66 impl<'a> VisSpace<'a> {
67 pub fn get(self) -> &'a Option<clean::Visibility> {
68 let VisSpace(v) = self; v
73 pub fn get(&self) -> hir::Unsafety {
74 let UnsafetySpace(v) = *self; v
79 pub fn get(&self) -> hir::Constness {
80 let ConstnessSpace(v) = *self; v
84 impl<'a, T: fmt::Display> fmt::Display for CommaSep<'a, T> {
85 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86 for (i, item) in self.0.iter().enumerate() {
87 if i != 0 { write!(f, ", ")?; }
88 write!(f, "{}", item)?;
94 impl<'a> fmt::Display for TyParamBounds<'a> {
95 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 let &TyParamBounds(bounds) = self;
97 for (i, bound) in bounds.iter().enumerate() {
101 write!(f, "{}", *bound)?;
107 impl fmt::Display for clean::Generics {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 if self.lifetimes.is_empty() && self.type_params.is_empty() { return Ok(()) }
110 f.write_str("<")?;
112 for (i, life) in self.lifetimes.iter().enumerate() {
114 f.write_str(", ")?;
116 write!(f, "{}", *life)?;
119 if !self.type_params.is_empty() {
120 if !self.lifetimes.is_empty() {
121 f.write_str(", ")?;
123 for (i, tp) in self.type_params.iter().enumerate() {
125 f.write_str(", ")?
127 f.write_str(&tp.name)?;
129 if !tp.bounds.is_empty() {
130 write!(f, ": {}", TyParamBounds(&tp.bounds))?;
134 Some(ref ty) => { write!(f, " = {}", ty)?; },
139 f.write_str(">")?;
144 impl<'a> fmt::Display for WhereClause<'a> {
145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
146 let &WhereClause(gens) = self;
147 if gens.where_predicates.is_empty() {
150 f.write_str(" <span class='where'>where ")?;
151 for (i, pred) in gens.where_predicates.iter().enumerate() {
156 &clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => {
158 write!(f, "{}: {}", ty, TyParamBounds(bounds))?;
160 &clean::WherePredicate::RegionPredicate { ref lifetime,
162 write!(f, "{}: ", lifetime)?;
163 for (i, lifetime) in bounds.iter().enumerate() {
168 write!(f, "{}", lifetime)?;
171 &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => {
172 write!(f, "{} == {}", lhs, rhs)?;
176 f.write_str("</span>")?;
181 impl fmt::Display for clean::Lifetime {
182 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
183 f.write_str(self.get_ref())?;
188 impl fmt::Display for clean::PolyTrait {
189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190 if !self.lifetimes.is_empty() {
191 f.write_str("for<")?;
192 for (i, lt) in self.lifetimes.iter().enumerate() {
196 write!(f, "{}", lt)?;
198 f.write_str("> ")?;
200 write!(f, "{}", self.trait_)
204 impl fmt::Display for clean::TyParamBound {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
207 clean::RegionBound(ref lt) => {
210 clean::TraitBound(ref ty, modifier) => {
211 let modifier_str = match modifier {
212 hir::TraitBoundModifier::None => "",
213 hir::TraitBoundModifier::Maybe => "?",
215 write!(f, "{}{}", modifier_str, *ty)
221 impl fmt::Display for clean::PathParameters {
222 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
224 clean::PathParameters::AngleBracketed {
225 ref lifetimes, ref types, ref bindings
227 if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
228 f.write_str("<")?;
229 let mut comma = false;
230 for lifetime in lifetimes {
232 f.write_str(", ")?;
235 write!(f, "{}", *lifetime)?;
239 f.write_str(", ")?;
242 write!(f, "{}", *ty)?;
244 for binding in bindings {
246 f.write_str(", ")?;
249 write!(f, "{}", *binding)?;
251 f.write_str(">")?;
254 clean::PathParameters::Parenthesized { ref inputs, ref output } => {
256 let mut comma = false;
262 write!(f, "{}", *ty)?;
265 if let Some(ref ty) = *output {
266 f.write_str(" -> ")?;
267 write!(f, "{}", ty)?;
275 impl fmt::Display for clean::PathSegment {
276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277 f.write_str(&self.name)?;
278 write!(f, "{}", self.params)
282 impl fmt::Display for clean::Path {
283 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
288 for (i, seg) in self.segments.iter().enumerate() {
292 write!(f, "{}", seg)?;
298 pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
300 if !did.is_local() && !cache.access_levels.is_doc_reachable(did) {
304 let loc = CURRENT_LOCATION_KEY.with(|l| l.borrow().clone());
305 let &(ref fqp, shortty) = match cache.paths.get(&did) {
310 let mut url = if did.is_local() || cache.inlined.contains(&did) {
311 repeat("../").take(loc.len()).collect::<String>()
313 match cache.extern_locations[&did.krate] {
314 (_, render::Remote(ref s)) => s.to_string(),
315 (_, render::Local) => repeat("../").take(loc.len()).collect(),
316 (_, render::Unknown) => return None,
319 for component in &fqp[..fqp.len() - 1] {
320 url.push_str(component);
324 ItemType::Module => {
325 url.push_str(fqp.last().unwrap());
326 url.push_str("/index.html");
329 url.push_str(shortty.to_static_str());
331 url.push_str(fqp.last().unwrap());
332 url.push_str(".html");
335 Some((url, shortty, fqp.to_vec()))
338 /// Used when rendering a `ResolvedPath` structure. This invokes the `path`
339 /// rendering function with the necessary arguments for linking to a local path.
340 fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path,
341 print_all: bool) -> fmt::Result {
342 let last = path.segments.last().unwrap();
343 let rel_root = match &*path.segments[0].name {
344 "self" => Some("./".to_string()),
349 let amt = path.segments.len() - 1;
352 for seg in &path.segments[..amt] {
353 if "super" == seg.name || "self" == seg.name {
354 write!(w, "{}::", seg.name)?;
356 root.push_str(&seg.name);
358 write!(w, "<a class='mod'
359 href='{}index.html'>{}</a>::",
366 for seg in &path.segments[..amt] {
367 write!(w, "{}::", seg.name)?;
372 write!(w, "{}{}", HRef::new(did, &last.name), 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)?;
439 pub fn new(did: DefId, text: &'a str) -> HRef<'a> {
440 HRef { did: did, text: text }
444 impl<'a> fmt::Display for HRef<'a> {
445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446 match href(self.did) {
447 Some((url, shortty, fqp)) => {
448 write!(f, "<a class='{}' href='{}' title='{}'>{}</a>",
449 shortty, url, fqp.join("::"), self.text)
451 _ => write!(f, "{}", self.text),
456 impl fmt::Display for clean::Type {
457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
459 clean::Generic(ref name) => {
462 clean::ResolvedPath{ did, ref typarams, ref path, is_generic } => {
463 // Paths like T::Output and Self::Output should be rendered with all segments
464 resolved_path(f, did, path, is_generic)?;
465 tybounds(f, typarams)
467 clean::Infer => write!(f, "_"),
468 clean::Primitive(prim) => primitive_link(f, prim, prim.to_string()),
469 clean::BareFunction(ref decl) => {
470 write!(f, "{}{}fn{}{}",
471 UnsafetySpace(decl.unsafety),
476 clean::Tuple(ref typs) => {
478 [] => primitive_link(f, clean::PrimitiveTuple, "()"),
480 primitive_link(f, clean::PrimitiveTuple, "(")?;
481 write!(f, "{},", one)?;
482 primitive_link(f, clean::PrimitiveTuple, ")")
485 primitive_link(f, clean::PrimitiveTuple, "(")?;
486 write!(f, "{}", CommaSep(&many))?;
487 primitive_link(f, clean::PrimitiveTuple, ")")
491 clean::Vector(ref t) => {
492 primitive_link(f, clean::Slice, &format!("["))?;
494 primitive_link(f, clean::Slice, &format!("]"))
496 clean::FixedVector(ref t, ref s) => {
497 primitive_link(f, clean::PrimitiveType::Array, "[")?;
499 primitive_link(f, clean::PrimitiveType::Array,
500 &format!("; {}]", Escape(s)))
502 clean::Bottom => f.write_str("!"),
503 clean::RawPointer(m, ref t) => {
505 clean::Generic(_) | clean::ResolvedPath {is_generic: true, ..} => {
506 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
507 &format!("*{}{}", RawMutableSpace(m), t))
510 primitive_link(f, clean::PrimitiveType::PrimitiveRawPointer,
511 &format!("*{}", RawMutableSpace(m)))?;
516 clean::BorrowedRef{ lifetime: ref l, mutability, type_: ref ty} => {
518 Some(ref l) => format!("{} ", *l),
521 let m = MutableSpace(mutability);
523 clean::Vector(ref bt) => { // BorrowedRef{ ... Vector(T) } is &[T]
526 primitive_link(f, clean::Slice,
527 &format!("&{}{}[{}]", lt, m, **bt)),
529 primitive_link(f, clean::Slice, &format!("&{}{}[", lt, m))?;
530 write!(f, "{}", **bt)?;
531 primitive_link(f, clean::Slice, "]")
536 write!(f, "&{}{}{}", lt, m, **ty)
540 clean::PolyTraitRef(ref bounds) => {
541 for (i, bound) in bounds.iter().enumerate() {
545 write!(f, "{}", *bound)?;
549 // It's pretty unsightly to look at `<A as B>::C` in output, and
550 // we've got hyperlinking on our side, so try to avoid longer
551 // notation as much as possible by making `C` a hyperlink to trait
552 // `B` to disambiguate.
554 // FIXME: this is still a lossy conversion and there should probably
555 // be a better way of representing this in general? Most of
556 // the ugliness comes from inlining across crates where
557 // everything comes in as a fully resolved QPath (hard to
562 trait_: box clean::ResolvedPath { did, ref typarams, .. },
564 write!(f, "{}::", self_type)?;
565 let path = clean::Path::singleton(name.clone());
566 resolved_path(f, did, &path, false)?;
568 // FIXME: `typarams` are not rendered, and this seems bad?
572 clean::QPath { ref name, ref self_type, ref trait_ } => {
573 write!(f, "<{} as {}>::{}", self_type, trait_, name)
575 clean::Unique(..) => {
576 panic!("should have been cleaned")
582 fn fmt_impl(i: &clean::Impl, f: &mut fmt::Formatter, link_trait: bool) -> fmt::Result {
583 write!(f, "impl{} ", i.generics)?;
584 if let Some(ref ty) = i.trait_ {
586 if i.polarity == Some(clean::ImplPolarity::Negative) { "!" } else { "" })?;
588 write!(f, "{}", *ty)?;
591 clean::ResolvedPath{ typarams: None, ref path, is_generic: false, .. } => {
592 let last = path.segments.last().unwrap();
593 write!(f, "{}{}", last.name, last.params)?;
600 write!(f, "{}{}", i.for_, WhereClause(&i.generics))?;
604 impl fmt::Display for clean::Impl {
605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606 fmt_impl(self, f, true)
610 // The difference from above is that trait is not hyperlinked.
611 pub fn fmt_impl_for_trait_page(i: &clean::Impl, f: &mut fmt::Formatter) -> fmt::Result {
612 fmt_impl(i, f, false)
615 impl fmt::Display for clean::Arguments {
616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617 for (i, input) in self.values.iter().enumerate() {
618 if i > 0 { write!(f, ", ")?; }
619 if !input.name.is_empty() {
620 write!(f, "{}: ", input.name)?;
622 write!(f, "{}", input.type_)?;
628 impl fmt::Display for clean::FunctionRetTy {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
631 clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()),
632 clean::Return(ref ty) => write!(f, " -> {}", ty),
633 clean::DefaultReturn => Ok(()),
634 clean::NoReturn => write!(f, " -> !")
639 impl fmt::Display for clean::FnDecl {
640 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
642 write!(f, "({args}, ...){arrow}", args = self.inputs, arrow = self.output)
644 write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output)
649 impl<'a> fmt::Display for Method<'a> {
650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
652 let mut args = String::new();
653 for (i, input) in decl.inputs.values.iter().enumerate() {
654 if i > 0 || !args.is_empty() { args.push_str(", "); }
655 if let Some(selfty) = input.to_self() {
657 clean::SelfValue => args.push_str("self"),
658 clean::SelfBorrowed(Some(ref lt), mtbl) => {
659 args.push_str(&format!("&{} {}self", *lt, MutableSpace(mtbl)));
661 clean::SelfBorrowed(None, mtbl) => {
662 args.push_str(&format!("&{}self", MutableSpace(mtbl)));
664 clean::SelfExplicit(ref typ) => {
665 args.push_str(&format!("self: {}", *typ));
669 if !input.name.is_empty() {
670 args.push_str(&format!("{}: ", input.name));
672 args.push_str(&format!("{}", input.type_));
675 write!(f, "({args}){arrow}", args = args, arrow = decl.output)
679 impl<'a> fmt::Display for VisSpace<'a> {
680 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
682 Some(clean::Public) => write!(f, "pub "),
683 Some(clean::Inherited) | None => Ok(())
688 impl fmt::Display for UnsafetySpace {
689 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
691 hir::Unsafety::Unsafe => write!(f, "unsafe "),
692 hir::Unsafety::Normal => Ok(())
697 impl fmt::Display for ConstnessSpace {
698 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 hir::Constness::Const => write!(f, "const "),
701 hir::Constness::NotConst => Ok(())
706 impl fmt::Display for clean::Import {
707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
709 clean::SimpleImport(ref name, ref src) => {
710 if *name == src.path.last_name() {
711 write!(f, "use {};", *src)
713 write!(f, "use {} as {};", *src, *name)
716 clean::GlobImport(ref src) => {
717 write!(f, "use {}::*;", *src)
719 clean::ImportList(ref src, ref names) => {
720 write!(f, "use {}::{{", *src)?;
721 for (i, n) in names.iter().enumerate() {
725 write!(f, "{}", *n)?;
733 impl fmt::Display for clean::ImportSource {
734 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
736 Some(did) => resolved_path(f, did, &self.path, true),
738 for (i, seg) in self.path.segments.iter().enumerate() {
742 write!(f, "{}", seg.name)?;
750 impl fmt::Display for clean::ViewListIdent {
751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
754 let path = clean::Path::singleton(self.name.clone());
755 resolved_path(f, did, &path, false)?;
757 _ => write!(f, "{}", self.name)?,
760 if let Some(ref name) = self.rename {
761 write!(f, " as {}", name)?;
767 impl fmt::Display for clean::TypeBinding {
768 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
769 write!(f, "{}={}", self.name, self.ty)
773 impl fmt::Display for MutableSpace {
774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
776 MutableSpace(clean::Immutable) => Ok(()),
777 MutableSpace(clean::Mutable) => write!(f, "mut "),
782 impl fmt::Display for RawMutableSpace {
783 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
785 RawMutableSpace(clean::Immutable) => write!(f, "const "),
786 RawMutableSpace(clean::Mutable) => write!(f, "mut "),
791 impl fmt::Display for AbiSpace {
792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
795 Abi::C => write!(f, "extern "),
796 abi => write!(f, "extern "{}" ", abi.name()),