]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render.rs
Rollup merge of #48274 - GuillaumeGomez:remove-hoedown, r=QuietMisdreavus
[rust.git] / src / librustdoc / html / render.rs
1 // Copyright 2013-2015 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.
4 //
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.
10
11 //! Rustdoc's HTML Rendering module
12 //!
13 //! This modules contains the bulk of the logic necessary for rendering a
14 //! rustdoc `clean::Crate` instance to a set of static HTML pages. This
15 //! rendering process is largely driven by the `format!` syntax extension to
16 //! perform all I/O into files and streams.
17 //!
18 //! The rendering process is largely driven by the `Context` and `Cache`
19 //! structures. The cache is pre-populated by crawling the crate in question,
20 //! and then it is shared among the various rendering threads. The cache is meant
21 //! to be a fairly large structure not implementing `Clone` (because it's shared
22 //! among threads). The context, however, should be a lightweight structure. This
23 //! is cloned per-thread and contains information about what is currently being
24 //! rendered.
25 //!
26 //! In order to speed up rendering (mostly because of markdown rendering), the
27 //! rendering process has been parallelized. This parallelization is only
28 //! exposed through the `crate` method on the context, and then also from the
29 //! fact that the shared cache is stored in TLS (and must be accessed as such).
30 //!
31 //! In addition to rendering the crate itself, this module is also responsible
32 //! for creating the corresponding search index and source file renderings.
33 //! These threads are not parallelized (they haven't been a bottleneck yet), and
34 //! both occur before the crate is rendered.
35 pub use self::ExternalLocation::*;
36
37 use std::borrow::Cow;
38 use std::cell::RefCell;
39 use std::cmp::Ordering;
40 use std::collections::{BTreeMap, HashSet};
41 use std::default::Default;
42 use std::error;
43 use std::fmt::{self, Display, Formatter, Write as FmtWrite};
44 use std::fs::{self, File, OpenOptions};
45 use std::io::prelude::*;
46 use std::io::{self, BufWriter, BufReader};
47 use std::iter::repeat;
48 use std::mem;
49 use std::path::{PathBuf, Path, Component};
50 use std::str;
51 use std::sync::Arc;
52
53 use externalfiles::ExternalHtml;
54
55 use serialize::json::{ToJson, Json, as_json};
56 use syntax::{abi, ast};
57 use syntax::codemap::FileName;
58 use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId};
59 use rustc::middle::privacy::AccessLevels;
60 use rustc::middle::stability;
61 use rustc::hir;
62 use rustc::util::nodemap::{FxHashMap, FxHashSet};
63 use rustc_data_structures::flock;
64
65 use clean::{self, AttributesExt, GetDefId, SelfTy, Mutability};
66 use doctree;
67 use fold::DocFolder;
68 use html::escape::Escape;
69 use html::format::{ConstnessSpace};
70 use html::format::{TyParamBounds, WhereClause, href, AbiSpace};
71 use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
72 use html::format::fmt_impl_for_trait_page;
73 use html::item_type::ItemType;
74 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine};
75 use html::{highlight, layout};
76
77 /// A pair of name and its optional document.
78 pub type NameDoc = (String, Option<String>);
79
80 /// Major driving force in all rustdoc rendering. This contains information
81 /// about where in the tree-like hierarchy rendering is occurring and controls
82 /// how the current page is being rendered.
83 ///
84 /// It is intended that this context is a lightweight object which can be fairly
85 /// easily cloned because it is cloned per work-job (about once per item in the
86 /// rustdoc tree).
87 #[derive(Clone)]
88 pub struct Context {
89     /// Current hierarchy of components leading down to what's currently being
90     /// rendered
91     pub current: Vec<String>,
92     /// The current destination folder of where HTML artifacts should be placed.
93     /// This changes as the context descends into the module hierarchy.
94     pub dst: PathBuf,
95     /// A flag, which when `true`, will render pages which redirect to the
96     /// real location of an item. This is used to allow external links to
97     /// publicly reused items to redirect to the right location.
98     pub render_redirect_pages: bool,
99     pub shared: Arc<SharedContext>,
100 }
101
102 pub struct SharedContext {
103     /// The path to the crate root source minus the file name.
104     /// Used for simplifying paths to the highlighted source code files.
105     pub src_root: PathBuf,
106     /// This describes the layout of each page, and is not modified after
107     /// creation of the context (contains info like the favicon and added html).
108     pub layout: layout::Layout,
109     /// This flag indicates whether [src] links should be generated or not. If
110     /// the source files are present in the html rendering, then this will be
111     /// `true`.
112     pub include_sources: bool,
113     /// The local file sources we've emitted and their respective url-paths.
114     pub local_sources: FxHashMap<PathBuf, String>,
115     /// All the passes that were run on this crate.
116     pub passes: FxHashSet<String>,
117     /// The base-URL of the issue tracker for when an item has been tagged with
118     /// an issue number.
119     pub issue_tracker_base_url: Option<String>,
120     /// The given user css file which allow to customize the generated
121     /// documentation theme.
122     pub css_file_extension: Option<PathBuf>,
123     /// The directories that have already been created in this doc run. Used to reduce the number
124     /// of spurious `create_dir_all` calls.
125     pub created_dirs: RefCell<FxHashSet<PathBuf>>,
126     /// This flag indicates whether listings of modules (in the side bar and documentation itself)
127     /// should be ordered alphabetically or in order of appearance (in the source code).
128     pub sort_modules_alphabetically: bool,
129     /// Additional themes to be added to the generated docs.
130     pub themes: Vec<PathBuf>,
131 }
132
133 impl SharedContext {
134     fn ensure_dir(&self, dst: &Path) -> io::Result<()> {
135         let mut dirs = self.created_dirs.borrow_mut();
136         if !dirs.contains(dst) {
137             fs::create_dir_all(dst)?;
138             dirs.insert(dst.to_path_buf());
139         }
140
141         Ok(())
142     }
143 }
144
145 impl SharedContext {
146     /// Returns whether the `collapse-docs` pass was run on this crate.
147     pub fn was_collapsed(&self) -> bool {
148         self.passes.contains("collapse-docs")
149     }
150
151     /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the
152     /// `collapsed_doc_value` of the given item.
153     pub fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<Cow<'a, str>> {
154         if self.was_collapsed() {
155             item.collapsed_doc_value().map(|s| s.into())
156         } else {
157             item.doc_value().map(|s| s.into())
158         }
159     }
160 }
161
162 /// Indicates where an external crate can be found.
163 pub enum ExternalLocation {
164     /// Remote URL root of the external crate
165     Remote(String),
166     /// This external crate can be found in the local doc/ folder
167     Local,
168     /// The external crate could not be found.
169     Unknown,
170 }
171
172 /// Metadata about implementations for a type or trait.
173 #[derive(Clone)]
174 pub struct Impl {
175     pub impl_item: clean::Item,
176 }
177
178 impl Impl {
179     fn inner_impl(&self) -> &clean::Impl {
180         match self.impl_item.inner {
181             clean::ImplItem(ref impl_) => impl_,
182             _ => panic!("non-impl item found in impl")
183         }
184     }
185
186     fn trait_did(&self) -> Option<DefId> {
187         self.inner_impl().trait_.def_id()
188     }
189 }
190
191 #[derive(Debug)]
192 pub struct Error {
193     file: PathBuf,
194     error: io::Error,
195 }
196
197 impl error::Error for Error {
198     fn description(&self) -> &str {
199         self.error.description()
200     }
201 }
202
203 impl Display for Error {
204     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
205         write!(f, "\"{}\": {}", self.file.display(), self.error)
206     }
207 }
208
209 impl Error {
210     pub fn new(e: io::Error, file: &Path) -> Error {
211         Error {
212             file: file.to_path_buf(),
213             error: e,
214         }
215     }
216 }
217
218 macro_rules! try_none {
219     ($e:expr, $file:expr) => ({
220         use std::io;
221         match $e {
222             Some(e) => e,
223             None => return Err(Error::new(io::Error::new(io::ErrorKind::Other, "not found"),
224                                           $file))
225         }
226     })
227 }
228
229 macro_rules! try_err {
230     ($e:expr, $file:expr) => ({
231         match $e {
232             Ok(e) => e,
233             Err(e) => return Err(Error::new(e, $file)),
234         }
235     })
236 }
237
238 /// This cache is used to store information about the `clean::Crate` being
239 /// rendered in order to provide more useful documentation. This contains
240 /// information like all implementors of a trait, all traits a type implements,
241 /// documentation for all known traits, etc.
242 ///
243 /// This structure purposefully does not implement `Clone` because it's intended
244 /// to be a fairly large and expensive structure to clone. Instead this adheres
245 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
246 /// rendering threads.
247 #[derive(Default)]
248 pub struct Cache {
249     /// Mapping of typaram ids to the name of the type parameter. This is used
250     /// when pretty-printing a type (so pretty printing doesn't have to
251     /// painfully maintain a context like this)
252     pub typarams: FxHashMap<DefId, String>,
253
254     /// Maps a type id to all known implementations for that type. This is only
255     /// recognized for intra-crate `ResolvedPath` types, and is used to print
256     /// out extra documentation on the page of an enum/struct.
257     ///
258     /// The values of the map are a list of implementations and documentation
259     /// found on that implementation.
260     pub impls: FxHashMap<DefId, Vec<Impl>>,
261
262     /// Maintains a mapping of local crate node ids to the fully qualified name
263     /// and "short type description" of that node. This is used when generating
264     /// URLs when a type is being linked to. External paths are not located in
265     /// this map because the `External` type itself has all the information
266     /// necessary.
267     pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
268
269     /// Similar to `paths`, but only holds external paths. This is only used for
270     /// generating explicit hyperlinks to other crates.
271     pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
272
273     /// This map contains information about all known traits of this crate.
274     /// Implementations of a crate should inherit the documentation of the
275     /// parent trait if no extra documentation is specified, and default methods
276     /// should show up in documentation about trait implementations.
277     pub traits: FxHashMap<DefId, clean::Trait>,
278
279     /// When rendering traits, it's often useful to be able to list all
280     /// implementors of the trait, and this mapping is exactly, that: a mapping
281     /// of trait ids to the list of known implementors of the trait
282     pub implementors: FxHashMap<DefId, Vec<Impl>>,
283
284     /// Cache of where external crate documentation can be found.
285     pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
286
287     /// Cache of where documentation for primitives can be found.
288     pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
289
290     // Note that external items for which `doc(hidden)` applies to are shown as
291     // non-reachable while local items aren't. This is because we're reusing
292     // the access levels from crateanalysis.
293     pub access_levels: Arc<AccessLevels<DefId>>,
294
295     /// The version of the crate being documented, if given fron the `--crate-version` flag.
296     pub crate_version: Option<String>,
297
298     // Private fields only used when initially crawling a crate to build a cache
299
300     stack: Vec<String>,
301     parent_stack: Vec<DefId>,
302     parent_is_trait_impl: bool,
303     search_index: Vec<IndexItem>,
304     stripped_mod: bool,
305     deref_trait_did: Option<DefId>,
306     deref_mut_trait_did: Option<DefId>,
307     owned_box_did: Option<DefId>,
308     masked_crates: FxHashSet<CrateNum>,
309
310     // In rare case where a structure is defined in one module but implemented
311     // in another, if the implementing module is parsed before defining module,
312     // then the fully qualified name of the structure isn't presented in `paths`
313     // yet when its implementation methods are being indexed. Caches such methods
314     // and their parent id here and indexes them at the end of crate parsing.
315     orphan_impl_items: Vec<(DefId, clean::Item)>,
316 }
317
318 /// Temporary storage for data obtained during `RustdocVisitor::clean()`.
319 /// Later on moved into `CACHE_KEY`.
320 #[derive(Default)]
321 pub struct RenderInfo {
322     pub inlined: FxHashSet<DefId>,
323     pub external_paths: ::core::ExternalPaths,
324     pub external_typarams: FxHashMap<DefId, String>,
325     pub deref_trait_did: Option<DefId>,
326     pub deref_mut_trait_did: Option<DefId>,
327     pub owned_box_did: Option<DefId>,
328 }
329
330 /// Helper struct to render all source code to HTML pages
331 struct SourceCollector<'a> {
332     scx: &'a mut SharedContext,
333
334     /// Root destination to place all HTML output into
335     dst: PathBuf,
336 }
337
338 /// Wrapper struct to render the source code of a file. This will do things like
339 /// adding line numbers to the left-hand side.
340 struct Source<'a>(&'a str);
341
342 // Helper structs for rendering items/sidebars and carrying along contextual
343 // information
344
345 #[derive(Copy, Clone)]
346 struct Item<'a> {
347     cx: &'a Context,
348     item: &'a clean::Item,
349 }
350
351 struct Sidebar<'a> { cx: &'a Context, item: &'a clean::Item, }
352
353 /// Struct representing one entry in the JS search index. These are all emitted
354 /// by hand to a large JS file at the end of cache-creation.
355 struct IndexItem {
356     ty: ItemType,
357     name: String,
358     path: String,
359     desc: String,
360     parent: Option<DefId>,
361     parent_idx: Option<usize>,
362     search_type: Option<IndexItemFunctionType>,
363 }
364
365 impl ToJson for IndexItem {
366     fn to_json(&self) -> Json {
367         assert_eq!(self.parent.is_some(), self.parent_idx.is_some());
368
369         let mut data = Vec::with_capacity(6);
370         data.push((self.ty as usize).to_json());
371         data.push(self.name.to_json());
372         data.push(self.path.to_json());
373         data.push(self.desc.to_json());
374         data.push(self.parent_idx.to_json());
375         data.push(self.search_type.to_json());
376
377         Json::Array(data)
378     }
379 }
380
381 /// A type used for the search index.
382 struct Type {
383     name: Option<String>,
384     generics: Option<Vec<String>>,
385 }
386
387 impl ToJson for Type {
388     fn to_json(&self) -> Json {
389         match self.name {
390             Some(ref name) => {
391                 let mut data = BTreeMap::new();
392                 data.insert("name".to_owned(), name.to_json());
393                 if let Some(ref generics) = self.generics {
394                     data.insert("generics".to_owned(), generics.to_json());
395                 }
396                 Json::Object(data)
397             },
398             None => Json::Null
399         }
400     }
401 }
402
403 /// Full type of functions/methods in the search index.
404 struct IndexItemFunctionType {
405     inputs: Vec<Type>,
406     output: Option<Type>
407 }
408
409 impl ToJson for IndexItemFunctionType {
410     fn to_json(&self) -> Json {
411         // If we couldn't figure out a type, just write `null`.
412         if self.inputs.iter().chain(self.output.iter()).any(|ref i| i.name.is_none()) {
413             Json::Null
414         } else {
415             let mut data = BTreeMap::new();
416             data.insert("inputs".to_owned(), self.inputs.to_json());
417             data.insert("output".to_owned(), self.output.to_json());
418             Json::Object(data)
419         }
420     }
421 }
422
423 thread_local!(static CACHE_KEY: RefCell<Arc<Cache>> = Default::default());
424 thread_local!(pub static CURRENT_LOCATION_KEY: RefCell<Vec<String>> = RefCell::new(Vec::new()));
425 thread_local!(pub static USED_ID_MAP: RefCell<FxHashMap<String, usize>> = RefCell::new(init_ids()));
426
427 fn init_ids() -> FxHashMap<String, usize> {
428     [
429      "main",
430      "search",
431      "help",
432      "TOC",
433      "render-detail",
434      "associated-types",
435      "associated-const",
436      "required-methods",
437      "provided-methods",
438      "implementors",
439      "implementors-list",
440      "methods",
441      "deref-methods",
442      "implementations",
443     ].into_iter().map(|id| (String::from(*id), 1)).collect()
444 }
445
446 /// This method resets the local table of used ID attributes. This is typically
447 /// used at the beginning of rendering an entire HTML page to reset from the
448 /// previous state (if any).
449 pub fn reset_ids(embedded: bool) {
450     USED_ID_MAP.with(|s| {
451         *s.borrow_mut() = if embedded {
452             init_ids()
453         } else {
454             FxHashMap()
455         };
456     });
457 }
458
459 pub fn derive_id(candidate: String) -> String {
460     USED_ID_MAP.with(|map| {
461         let id = match map.borrow_mut().get_mut(&candidate) {
462             None => candidate,
463             Some(a) => {
464                 let id = format!("{}-{}", candidate, *a);
465                 *a += 1;
466                 id
467             }
468         };
469
470         map.borrow_mut().insert(id.clone(), 1);
471         id
472     })
473 }
474
475 /// Generates the documentation for `crate` into the directory `dst`
476 pub fn run(mut krate: clean::Crate,
477            external_html: &ExternalHtml,
478            playground_url: Option<String>,
479            dst: PathBuf,
480            passes: FxHashSet<String>,
481            css_file_extension: Option<PathBuf>,
482            renderinfo: RenderInfo,
483            sort_modules_alphabetically: bool,
484            themes: Vec<PathBuf>) -> Result<(), Error> {
485     let src_root = match krate.src {
486         FileName::Real(ref p) => match p.parent() {
487             Some(p) => p.to_path_buf(),
488             None => PathBuf::new(),
489         },
490         _ => PathBuf::new(),
491     };
492     let mut scx = SharedContext {
493         src_root,
494         passes,
495         include_sources: true,
496         local_sources: FxHashMap(),
497         issue_tracker_base_url: None,
498         layout: layout::Layout {
499             logo: "".to_string(),
500             favicon: "".to_string(),
501             external_html: external_html.clone(),
502             krate: krate.name.clone(),
503         },
504         css_file_extension: css_file_extension.clone(),
505         created_dirs: RefCell::new(FxHashSet()),
506         sort_modules_alphabetically,
507         themes,
508     };
509
510     // If user passed in `--playground-url` arg, we fill in crate name here
511     if let Some(url) = playground_url {
512         markdown::PLAYGROUND.with(|slot| {
513             *slot.borrow_mut() = Some((Some(krate.name.clone()), url));
514         });
515     }
516
517     // Crawl the crate attributes looking for attributes which control how we're
518     // going to emit HTML
519     if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) {
520         for attr in attrs.lists("doc") {
521             let name = attr.name().map(|s| s.as_str());
522             match (name.as_ref().map(|s| &s[..]), attr.value_str()) {
523                 (Some("html_favicon_url"), Some(s)) => {
524                     scx.layout.favicon = s.to_string();
525                 }
526                 (Some("html_logo_url"), Some(s)) => {
527                     scx.layout.logo = s.to_string();
528                 }
529                 (Some("html_playground_url"), Some(s)) => {
530                     markdown::PLAYGROUND.with(|slot| {
531                         let name = krate.name.clone();
532                         *slot.borrow_mut() = Some((Some(name), s.to_string()));
533                     });
534                 }
535                 (Some("issue_tracker_base_url"), Some(s)) => {
536                     scx.issue_tracker_base_url = Some(s.to_string());
537                 }
538                 (Some("html_no_source"), None) if attr.is_word() => {
539                     scx.include_sources = false;
540                 }
541                 _ => {}
542             }
543         }
544     }
545     try_err!(fs::create_dir_all(&dst), &dst);
546     krate = render_sources(&dst, &mut scx, krate)?;
547     let cx = Context {
548         current: Vec::new(),
549         dst,
550         render_redirect_pages: false,
551         shared: Arc::new(scx),
552     };
553
554     // Crawl the crate to build various caches used for the output
555     let RenderInfo {
556         inlined: _,
557         external_paths,
558         external_typarams,
559         deref_trait_did,
560         deref_mut_trait_did,
561         owned_box_did,
562     } = renderinfo;
563
564     let external_paths = external_paths.into_iter()
565         .map(|(k, (v, t))| (k, (v, ItemType::from(t))))
566         .collect();
567
568     let mut cache = Cache {
569         impls: FxHashMap(),
570         external_paths,
571         paths: FxHashMap(),
572         implementors: FxHashMap(),
573         stack: Vec::new(),
574         parent_stack: Vec::new(),
575         search_index: Vec::new(),
576         parent_is_trait_impl: false,
577         extern_locations: FxHashMap(),
578         primitive_locations: FxHashMap(),
579         stripped_mod: false,
580         access_levels: krate.access_levels.clone(),
581         crate_version: krate.version.take(),
582         orphan_impl_items: Vec::new(),
583         traits: mem::replace(&mut krate.external_traits, FxHashMap()),
584         deref_trait_did,
585         deref_mut_trait_did,
586         owned_box_did,
587         masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet()),
588         typarams: external_typarams,
589     };
590
591     // Cache where all our extern crates are located
592     for &(n, ref e) in &krate.externs {
593         let src_root = match e.src {
594             FileName::Real(ref p) => match p.parent() {
595                 Some(p) => p.to_path_buf(),
596                 None => PathBuf::new(),
597             },
598             _ => PathBuf::new(),
599         };
600         cache.extern_locations.insert(n, (e.name.clone(), src_root,
601                                           extern_location(e, &cx.dst)));
602
603         let did = DefId { krate: n, index: CRATE_DEF_INDEX };
604         cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
605     }
606
607     // Cache where all known primitives have their documentation located.
608     //
609     // Favor linking to as local extern as possible, so iterate all crates in
610     // reverse topological order.
611     for &(_, ref e) in krate.externs.iter().rev() {
612         for &(def_id, prim, _) in &e.primitives {
613             cache.primitive_locations.insert(prim, def_id);
614         }
615     }
616     for &(def_id, prim, _) in &krate.primitives {
617         cache.primitive_locations.insert(prim, def_id);
618     }
619
620     cache.stack.push(krate.name.clone());
621     krate = cache.fold_crate(krate);
622
623     // Build our search index
624     let index = build_index(&krate, &mut cache);
625
626     // Freeze the cache now that the index has been built. Put an Arc into TLS
627     // for future parallelization opportunities
628     let cache = Arc::new(cache);
629     CACHE_KEY.with(|v| *v.borrow_mut() = cache.clone());
630     CURRENT_LOCATION_KEY.with(|s| s.borrow_mut().clear());
631
632     write_shared(&cx, &krate, &*cache, index)?;
633
634     // And finally render the whole crate's documentation
635     cx.krate(krate)
636 }
637
638 /// Build the search index from the collected metadata
639 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
640     let mut nodeid_to_pathid = FxHashMap();
641     let mut crate_items = Vec::with_capacity(cache.search_index.len());
642     let mut crate_paths = Vec::<Json>::new();
643
644     let Cache { ref mut search_index,
645                 ref orphan_impl_items,
646                 ref mut paths, .. } = *cache;
647
648     // Attach all orphan items to the type's definition if the type
649     // has since been learned.
650     for &(did, ref item) in orphan_impl_items {
651         if let Some(&(ref fqp, _)) = paths.get(&did) {
652             search_index.push(IndexItem {
653                 ty: item.type_(),
654                 name: item.name.clone().unwrap(),
655                 path: fqp[..fqp.len() - 1].join("::"),
656                 desc: plain_summary_line(item.doc_value()),
657                 parent: Some(did),
658                 parent_idx: None,
659                 search_type: get_index_search_type(&item),
660             });
661         }
662     }
663
664     // Reduce `NodeId` in paths into smaller sequential numbers,
665     // and prune the paths that do not appear in the index.
666     let mut lastpath = String::new();
667     let mut lastpathid = 0usize;
668
669     for item in search_index {
670         item.parent_idx = item.parent.map(|nodeid| {
671             if nodeid_to_pathid.contains_key(&nodeid) {
672                 *nodeid_to_pathid.get(&nodeid).unwrap()
673             } else {
674                 let pathid = lastpathid;
675                 nodeid_to_pathid.insert(nodeid, pathid);
676                 lastpathid += 1;
677
678                 let &(ref fqp, short) = paths.get(&nodeid).unwrap();
679                 crate_paths.push(((short as usize), fqp.last().unwrap().clone()).to_json());
680                 pathid
681             }
682         });
683
684         // Omit the parent path if it is same to that of the prior item.
685         if lastpath == item.path {
686             item.path.clear();
687         } else {
688             lastpath = item.path.clone();
689         }
690         crate_items.push(item.to_json());
691     }
692
693     let crate_doc = krate.module.as_ref().map(|module| {
694         plain_summary_line(module.doc_value())
695     }).unwrap_or(String::new());
696
697     let mut crate_data = BTreeMap::new();
698     crate_data.insert("doc".to_owned(), Json::String(crate_doc));
699     crate_data.insert("items".to_owned(), Json::Array(crate_items));
700     crate_data.insert("paths".to_owned(), Json::Array(crate_paths));
701
702     // Collect the index into a string
703     format!("searchIndex[{}] = {};",
704             as_json(&krate.name),
705             Json::Object(crate_data))
706 }
707
708 fn write_shared(cx: &Context,
709                 krate: &clean::Crate,
710                 cache: &Cache,
711                 search_index: String) -> Result<(), Error> {
712     // Write out the shared files. Note that these are shared among all rustdoc
713     // docs placed in the output directory, so this needs to be a synchronized
714     // operation with respect to all other rustdocs running around.
715     let _lock = flock::Lock::panicking_new(&cx.dst.join(".lock"), true, true, true);
716
717     // Add all the static files. These may already exist, but we just
718     // overwrite them anyway to make sure that they're fresh and up-to-date.
719
720     write(cx.dst.join("rustdoc.css"),
721           include_bytes!("static/rustdoc.css"))?;
722
723     // To avoid "main.css" to be overwritten, we'll first run over the received themes and only
724     // then we'll run over the "official" styles.
725     let mut themes: HashSet<String> = HashSet::new();
726
727     for entry in &cx.shared.themes {
728         let mut content = Vec::with_capacity(100000);
729
730         let mut f = try_err!(File::open(&entry), &entry);
731         try_err!(f.read_to_end(&mut content), &entry);
732         write(cx.dst.join(try_none!(entry.file_name(), &entry)), content.as_slice())?;
733         themes.insert(try_none!(try_none!(entry.file_stem(), &entry).to_str(), &entry).to_owned());
734     }
735
736     write(cx.dst.join("brush.svg"),
737           include_bytes!("static/brush.svg"))?;
738     write(cx.dst.join("main.css"),
739           include_bytes!("static/themes/main.css"))?;
740     themes.insert("main".to_owned());
741     write(cx.dst.join("dark.css"),
742           include_bytes!("static/themes/dark.css"))?;
743     themes.insert("dark".to_owned());
744
745     let mut themes: Vec<&String> = themes.iter().collect();
746     themes.sort();
747     // To avoid theme switch latencies as much as possible, we put everything theme related
748     // at the beginning of the html files into another js file.
749     write(cx.dst.join("theme.js"), format!(
750 r#"var themes = document.getElementById("theme-choices");
751 var themePicker = document.getElementById("theme-picker");
752 themePicker.onclick = function() {{
753     if (themes.style.display === "block") {{
754         themes.style.display = "none";
755         themePicker.style.borderBottomRightRadius = "3px";
756         themePicker.style.borderBottomLeftRadius = "3px";
757     }} else {{
758         themes.style.display = "block";
759         themePicker.style.borderBottomRightRadius = "0";
760         themePicker.style.borderBottomLeftRadius = "0";
761     }}
762 }};
763 [{}].forEach(function(item) {{
764     var but = document.createElement('button');
765     but.innerHTML = item;
766     but.onclick = function(el) {{
767         switchTheme(currentTheme, mainTheme, item);
768     }};
769     themes.appendChild(but);
770 }});
771 "#, themes.iter()
772           .map(|s| format!("\"{}\"", s))
773           .collect::<Vec<String>>()
774           .join(",")).as_bytes())?;
775
776     write(cx.dst.join("main.js"), include_bytes!("static/main.js"))?;
777     write(cx.dst.join("storage.js"), include_bytes!("static/storage.js"))?;
778
779     if let Some(ref css) = cx.shared.css_file_extension {
780         let out = cx.dst.join("theme.css");
781         try_err!(fs::copy(css, out), css);
782     }
783     write(cx.dst.join("normalize.css"),
784           include_bytes!("static/normalize.css"))?;
785     write(cx.dst.join("FiraSans-Regular.woff"),
786           include_bytes!("static/FiraSans-Regular.woff"))?;
787     write(cx.dst.join("FiraSans-Medium.woff"),
788           include_bytes!("static/FiraSans-Medium.woff"))?;
789     write(cx.dst.join("FiraSans-LICENSE.txt"),
790           include_bytes!("static/FiraSans-LICENSE.txt"))?;
791     write(cx.dst.join("Heuristica-Italic.woff"),
792           include_bytes!("static/Heuristica-Italic.woff"))?;
793     write(cx.dst.join("Heuristica-LICENSE.txt"),
794           include_bytes!("static/Heuristica-LICENSE.txt"))?;
795     write(cx.dst.join("SourceSerifPro-Regular.woff"),
796           include_bytes!("static/SourceSerifPro-Regular.woff"))?;
797     write(cx.dst.join("SourceSerifPro-Bold.woff"),
798           include_bytes!("static/SourceSerifPro-Bold.woff"))?;
799     write(cx.dst.join("SourceSerifPro-LICENSE.txt"),
800           include_bytes!("static/SourceSerifPro-LICENSE.txt"))?;
801     write(cx.dst.join("SourceCodePro-Regular.woff"),
802           include_bytes!("static/SourceCodePro-Regular.woff"))?;
803     write(cx.dst.join("SourceCodePro-Semibold.woff"),
804           include_bytes!("static/SourceCodePro-Semibold.woff"))?;
805     write(cx.dst.join("SourceCodePro-LICENSE.txt"),
806           include_bytes!("static/SourceCodePro-LICENSE.txt"))?;
807     write(cx.dst.join("LICENSE-MIT.txt"),
808           include_bytes!("static/LICENSE-MIT.txt"))?;
809     write(cx.dst.join("LICENSE-APACHE.txt"),
810           include_bytes!("static/LICENSE-APACHE.txt"))?;
811     write(cx.dst.join("COPYRIGHT.txt"),
812           include_bytes!("static/COPYRIGHT.txt"))?;
813
814     fn collect(path: &Path, krate: &str,
815                key: &str) -> io::Result<Vec<String>> {
816         let mut ret = Vec::new();
817         if path.exists() {
818             for line in BufReader::new(File::open(path)?).lines() {
819                 let line = line?;
820                 if !line.starts_with(key) {
821                     continue;
822                 }
823                 if line.starts_with(&format!(r#"{}["{}"]"#, key, krate)) {
824                     continue;
825                 }
826                 ret.push(line.to_string());
827             }
828         }
829         Ok(ret)
830     }
831
832     // Update the search index
833     let dst = cx.dst.join("search-index.js");
834     let mut all_indexes = try_err!(collect(&dst, &krate.name, "searchIndex"), &dst);
835     all_indexes.push(search_index);
836     // Sort the indexes by crate so the file will be generated identically even
837     // with rustdoc running in parallel.
838     all_indexes.sort();
839     let mut w = try_err!(File::create(&dst), &dst);
840     try_err!(writeln!(&mut w, "var searchIndex = {{}};"), &dst);
841     for index in &all_indexes {
842         try_err!(writeln!(&mut w, "{}", *index), &dst);
843     }
844     try_err!(writeln!(&mut w, "initSearch(searchIndex);"), &dst);
845
846     // Update the list of all implementors for traits
847     let dst = cx.dst.join("implementors");
848     for (&did, imps) in &cache.implementors {
849         // Private modules can leak through to this phase of rustdoc, which
850         // could contain implementations for otherwise private types. In some
851         // rare cases we could find an implementation for an item which wasn't
852         // indexed, so we just skip this step in that case.
853         //
854         // FIXME: this is a vague explanation for why this can't be a `get`, in
855         //        theory it should be...
856         let &(ref remote_path, remote_item_type) = match cache.paths.get(&did) {
857             Some(p) => p,
858             None => match cache.external_paths.get(&did) {
859                 Some(p) => p,
860                 None => continue,
861             }
862         };
863
864         let mut have_impls = false;
865         let mut implementors = format!(r#"implementors["{}"] = ["#, krate.name);
866         for imp in imps {
867             // If the trait and implementation are in the same crate, then
868             // there's no need to emit information about it (there's inlining
869             // going on). If they're in different crates then the crate defining
870             // the trait will be interested in our implementation.
871             if imp.impl_item.def_id.krate == did.krate { continue }
872             // If the implementation is from another crate then that crate
873             // should add it.
874             if !imp.impl_item.def_id.is_local() { continue }
875             have_impls = true;
876             write!(implementors, "{},", as_json(&imp.inner_impl().to_string())).unwrap();
877         }
878         implementors.push_str("];");
879
880         // Only create a js file if we have impls to add to it. If the trait is
881         // documented locally though we always create the file to avoid dead
882         // links.
883         if !have_impls && !cache.paths.contains_key(&did) {
884             continue;
885         }
886
887         let mut mydst = dst.clone();
888         for part in &remote_path[..remote_path.len() - 1] {
889             mydst.push(part);
890         }
891         try_err!(fs::create_dir_all(&mydst), &mydst);
892         mydst.push(&format!("{}.{}.js",
893                             remote_item_type.css_class(),
894                             remote_path[remote_path.len() - 1]));
895
896         let mut all_implementors = try_err!(collect(&mydst, &krate.name, "implementors"), &mydst);
897         all_implementors.push(implementors);
898         // Sort the implementors by crate so the file will be generated
899         // identically even with rustdoc running in parallel.
900         all_implementors.sort();
901
902         let mut f = try_err!(File::create(&mydst), &mydst);
903         try_err!(writeln!(&mut f, "(function() {{var implementors = {{}};"), &mydst);
904         for implementor in &all_implementors {
905             try_err!(writeln!(&mut f, "{}", *implementor), &mydst);
906         }
907         try_err!(writeln!(&mut f, "{}", r"
908             if (window.register_implementors) {
909                 window.register_implementors(implementors);
910             } else {
911                 window.pending_implementors = implementors;
912             }
913         "), &mydst);
914         try_err!(writeln!(&mut f, r"}})()"), &mydst);
915     }
916     Ok(())
917 }
918
919 fn render_sources(dst: &Path, scx: &mut SharedContext,
920                   krate: clean::Crate) -> Result<clean::Crate, Error> {
921     info!("emitting source files");
922     let dst = dst.join("src").join(&krate.name);
923     try_err!(fs::create_dir_all(&dst), &dst);
924     let mut folder = SourceCollector {
925         dst,
926         scx,
927     };
928     Ok(folder.fold_crate(krate))
929 }
930
931 /// Writes the entire contents of a string to a destination, not attempting to
932 /// catch any errors.
933 fn write(dst: PathBuf, contents: &[u8]) -> Result<(), Error> {
934     Ok(try_err!(fs::write(&dst, contents), &dst))
935 }
936
937 /// Takes a path to a source file and cleans the path to it. This canonicalizes
938 /// things like ".." to components which preserve the "top down" hierarchy of a
939 /// static HTML tree. Each component in the cleaned path will be passed as an
940 /// argument to `f`. The very last component of the path (ie the file name) will
941 /// be passed to `f` if `keep_filename` is true, and ignored otherwise.
942 // FIXME (#9639): The closure should deal with &[u8] instead of &str
943 // FIXME (#9639): This is too conservative, rejecting non-UTF-8 paths
944 fn clean_srcpath<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F) where
945     F: FnMut(&str),
946 {
947     // make it relative, if possible
948     let p = p.strip_prefix(src_root).unwrap_or(p);
949
950     let mut iter = p.components().peekable();
951
952     while let Some(c) = iter.next() {
953         if !keep_filename && iter.peek().is_none() {
954             break;
955         }
956
957         match c {
958             Component::ParentDir => f("up"),
959             Component::Normal(c) => f(c.to_str().unwrap()),
960             _ => continue,
961         }
962     }
963 }
964
965 /// Attempts to find where an external crate is located, given that we're
966 /// rendering in to the specified source destination.
967 fn extern_location(e: &clean::ExternalCrate, dst: &Path) -> ExternalLocation {
968     // See if there's documentation generated into the local directory
969     let local_location = dst.join(&e.name);
970     if local_location.is_dir() {
971         return Local;
972     }
973
974     // Failing that, see if there's an attribute specifying where to find this
975     // external crate
976     e.attrs.lists("doc")
977      .filter(|a| a.check_name("html_root_url"))
978      .filter_map(|a| a.value_str())
979      .map(|url| {
980         let mut url = url.to_string();
981         if !url.ends_with("/") {
982             url.push('/')
983         }
984         Remote(url)
985     }).next().unwrap_or(Unknown) // Well, at least we tried.
986 }
987
988 impl<'a> DocFolder for SourceCollector<'a> {
989     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
990         // If we're including source files, and we haven't seen this file yet,
991         // then we need to render it out to the filesystem.
992         if self.scx.include_sources
993             // skip all invalid or macro spans
994             && item.source.filename.is_real()
995             // skip non-local items
996             && item.def_id.is_local() {
997
998             // If it turns out that we couldn't read this file, then we probably
999             // can't read any of the files (generating html output from json or
1000             // something like that), so just don't include sources for the
1001             // entire crate. The other option is maintaining this mapping on a
1002             // per-file basis, but that's probably not worth it...
1003             self.scx
1004                 .include_sources = match self.emit_source(&item.source.filename) {
1005                 Ok(()) => true,
1006                 Err(e) => {
1007                     println!("warning: source code was requested to be rendered, \
1008                               but processing `{}` had an error: {}",
1009                              item.source.filename, e);
1010                     println!("         skipping rendering of source code");
1011                     false
1012                 }
1013             };
1014         }
1015         self.fold_item_recur(item)
1016     }
1017 }
1018
1019 impl<'a> SourceCollector<'a> {
1020     /// Renders the given filename into its corresponding HTML source file.
1021     fn emit_source(&mut self, filename: &FileName) -> io::Result<()> {
1022         let p = match *filename {
1023             FileName::Real(ref file) => file,
1024             _ => return Ok(()),
1025         };
1026         if self.scx.local_sources.contains_key(&**p) {
1027             // We've already emitted this source
1028             return Ok(());
1029         }
1030
1031         let contents = fs::read_string(&p)?;
1032
1033         // Remove the utf-8 BOM if any
1034         let contents = if contents.starts_with("\u{feff}") {
1035             &contents[3..]
1036         } else {
1037             &contents[..]
1038         };
1039
1040         // Create the intermediate directories
1041         let mut cur = self.dst.clone();
1042         let mut root_path = String::from("../../");
1043         let mut href = String::new();
1044         clean_srcpath(&self.scx.src_root, &p, false, |component| {
1045             cur.push(component);
1046             fs::create_dir_all(&cur).unwrap();
1047             root_path.push_str("../");
1048             href.push_str(component);
1049             href.push('/');
1050         });
1051         let mut fname = p.file_name().expect("source has no filename")
1052                          .to_os_string();
1053         fname.push(".html");
1054         cur.push(&fname);
1055         href.push_str(&fname.to_string_lossy());
1056
1057         let mut w = BufWriter::new(File::create(&cur)?);
1058         let title = format!("{} -- source", cur.file_name().unwrap()
1059                                                .to_string_lossy());
1060         let desc = format!("Source to the Rust file `{}`.", filename);
1061         let page = layout::Page {
1062             title: &title,
1063             css_class: "source",
1064             root_path: &root_path,
1065             description: &desc,
1066             keywords: BASIC_KEYWORDS,
1067         };
1068         layout::render(&mut w, &self.scx.layout,
1069                        &page, &(""), &Source(contents),
1070                        self.scx.css_file_extension.is_some(),
1071                        &self.scx.themes)?;
1072         w.flush()?;
1073         self.scx.local_sources.insert(p.clone(), href);
1074         Ok(())
1075     }
1076 }
1077
1078 impl DocFolder for Cache {
1079     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
1080         // If this is a stripped module,
1081         // we don't want it or its children in the search index.
1082         let orig_stripped_mod = match item.inner {
1083             clean::StrippedItem(box clean::ModuleItem(..)) => {
1084                 mem::replace(&mut self.stripped_mod, true)
1085             }
1086             _ => self.stripped_mod,
1087         };
1088
1089         // If the impl is from a masked crate or references something from a
1090         // masked crate then remove it completely.
1091         if let clean::ImplItem(ref i) = item.inner {
1092             if self.masked_crates.contains(&item.def_id.krate) ||
1093                i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) ||
1094                i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate)) {
1095                 return None;
1096             }
1097         }
1098
1099         // Register any generics to their corresponding string. This is used
1100         // when pretty-printing types.
1101         if let Some(generics) = item.inner.generics() {
1102             self.generics(generics);
1103         }
1104
1105         // Propagate a trait method's documentation to all implementors of the
1106         // trait.
1107         if let clean::TraitItem(ref t) = item.inner {
1108             self.traits.entry(item.def_id).or_insert_with(|| t.clone());
1109         }
1110
1111         // Collect all the implementors of traits.
1112         if let clean::ImplItem(ref i) = item.inner {
1113             if let Some(did) = i.trait_.def_id() {
1114                 self.implementors.entry(did).or_insert(vec![]).push(Impl {
1115                     impl_item: item.clone(),
1116                 });
1117             }
1118         }
1119
1120         // Index this method for searching later on.
1121         if let Some(ref s) = item.name {
1122             let (parent, is_inherent_impl_item) = match item.inner {
1123                 clean::StrippedItem(..) => ((None, None), false),
1124                 clean::AssociatedConstItem(..) |
1125                 clean::TypedefItem(_, true) if self.parent_is_trait_impl => {
1126                     // skip associated items in trait impls
1127                     ((None, None), false)
1128                 }
1129                 clean::AssociatedTypeItem(..) |
1130                 clean::TyMethodItem(..) |
1131                 clean::StructFieldItem(..) |
1132                 clean::VariantItem(..) => {
1133                     ((Some(*self.parent_stack.last().unwrap()),
1134                       Some(&self.stack[..self.stack.len() - 1])),
1135                      false)
1136                 }
1137                 clean::MethodItem(..) | clean::AssociatedConstItem(..) => {
1138                     if self.parent_stack.is_empty() {
1139                         ((None, None), false)
1140                     } else {
1141                         let last = self.parent_stack.last().unwrap();
1142                         let did = *last;
1143                         let path = match self.paths.get(&did) {
1144                             // The current stack not necessarily has correlation
1145                             // for where the type was defined. On the other
1146                             // hand, `paths` always has the right
1147                             // information if present.
1148                             Some(&(ref fqp, ItemType::Trait)) |
1149                             Some(&(ref fqp, ItemType::Struct)) |
1150                             Some(&(ref fqp, ItemType::Union)) |
1151                             Some(&(ref fqp, ItemType::Enum)) =>
1152                                 Some(&fqp[..fqp.len() - 1]),
1153                             Some(..) => Some(&*self.stack),
1154                             None => None
1155                         };
1156                         ((Some(*last), path), true)
1157                     }
1158                 }
1159                 _ => ((None, Some(&*self.stack)), false)
1160             };
1161
1162             match parent {
1163                 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
1164                     debug_assert!(!item.is_stripped());
1165
1166                     // A crate has a module at its root, containing all items,
1167                     // which should not be indexed. The crate-item itself is
1168                     // inserted later on when serializing the search-index.
1169                     if item.def_id.index != CRATE_DEF_INDEX {
1170                         self.search_index.push(IndexItem {
1171                             ty: item.type_(),
1172                             name: s.to_string(),
1173                             path: path.join("::").to_string(),
1174                             desc: plain_summary_line(item.doc_value()),
1175                             parent,
1176                             parent_idx: None,
1177                             search_type: get_index_search_type(&item),
1178                         });
1179                     }
1180                 }
1181                 (Some(parent), None) if is_inherent_impl_item => {
1182                     // We have a parent, but we don't know where they're
1183                     // defined yet. Wait for later to index this item.
1184                     self.orphan_impl_items.push((parent, item.clone()));
1185                 }
1186                 _ => {}
1187             }
1188         }
1189
1190         // Keep track of the fully qualified path for this item.
1191         let pushed = match item.name {
1192             Some(ref n) if !n.is_empty() => {
1193                 self.stack.push(n.to_string());
1194                 true
1195             }
1196             _ => false,
1197         };
1198
1199         match item.inner {
1200             clean::StructItem(..) | clean::EnumItem(..) |
1201             clean::TypedefItem(..) | clean::TraitItem(..) |
1202             clean::FunctionItem(..) | clean::ModuleItem(..) |
1203             clean::ForeignFunctionItem(..) | clean::ForeignStaticItem(..) |
1204             clean::ConstantItem(..) | clean::StaticItem(..) |
1205             clean::UnionItem(..) | clean::ForeignTypeItem | clean::MacroItem(..)
1206             if !self.stripped_mod => {
1207                 // Re-exported items mean that the same id can show up twice
1208                 // in the rustdoc ast that we're looking at. We know,
1209                 // however, that a re-exported item doesn't show up in the
1210                 // `public_items` map, so we can skip inserting into the
1211                 // paths map if there was already an entry present and we're
1212                 // not a public item.
1213                 if
1214                     !self.paths.contains_key(&item.def_id) ||
1215                     self.access_levels.is_public(item.def_id)
1216                 {
1217                     self.paths.insert(item.def_id,
1218                                       (self.stack.clone(), item.type_()));
1219                 }
1220             }
1221             // Link variants to their parent enum because pages aren't emitted
1222             // for each variant.
1223             clean::VariantItem(..) if !self.stripped_mod => {
1224                 let mut stack = self.stack.clone();
1225                 stack.pop();
1226                 self.paths.insert(item.def_id, (stack, ItemType::Enum));
1227             }
1228
1229             clean::PrimitiveItem(..) if item.visibility.is_some() => {
1230                 self.paths.insert(item.def_id, (self.stack.clone(),
1231                                                 item.type_()));
1232             }
1233
1234             _ => {}
1235         }
1236
1237         // Maintain the parent stack
1238         let orig_parent_is_trait_impl = self.parent_is_trait_impl;
1239         let parent_pushed = match item.inner {
1240             clean::TraitItem(..) | clean::EnumItem(..) | clean::ForeignTypeItem |
1241             clean::StructItem(..) | clean::UnionItem(..) => {
1242                 self.parent_stack.push(item.def_id);
1243                 self.parent_is_trait_impl = false;
1244                 true
1245             }
1246             clean::ImplItem(ref i) => {
1247                 self.parent_is_trait_impl = i.trait_.is_some();
1248                 match i.for_ {
1249                     clean::ResolvedPath{ did, .. } => {
1250                         self.parent_stack.push(did);
1251                         true
1252                     }
1253                     ref t => {
1254                         let prim_did = t.primitive_type().and_then(|t| {
1255                             self.primitive_locations.get(&t).cloned()
1256                         });
1257                         match prim_did {
1258                             Some(did) => {
1259                                 self.parent_stack.push(did);
1260                                 true
1261                             }
1262                             None => false,
1263                         }
1264                     }
1265                 }
1266             }
1267             _ => false
1268         };
1269
1270         // Once we've recursively found all the generics, hoard off all the
1271         // implementations elsewhere.
1272         let ret = self.fold_item_recur(item).and_then(|item| {
1273             if let clean::Item { inner: clean::ImplItem(_), .. } = item {
1274                 // Figure out the id of this impl. This may map to a
1275                 // primitive rather than always to a struct/enum.
1276                 // Note: matching twice to restrict the lifetime of the `i` borrow.
1277                 let mut dids = FxHashSet();
1278                 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
1279                     match i.for_ {
1280                         clean::ResolvedPath { did, .. } |
1281                         clean::BorrowedRef {
1282                             type_: box clean::ResolvedPath { did, .. }, ..
1283                         } => {
1284                             dids.insert(did);
1285                         }
1286                         ref t => {
1287                             let did = t.primitive_type().and_then(|t| {
1288                                 self.primitive_locations.get(&t).cloned()
1289                             });
1290
1291                             if let Some(did) = did {
1292                                 dids.insert(did);
1293                             }
1294                         }
1295                     }
1296
1297                     if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
1298                         for bound in generics {
1299                             if let Some(did) = bound.def_id() {
1300                                 dids.insert(did);
1301                             }
1302                         }
1303                     }
1304                 } else {
1305                     unreachable!()
1306                 };
1307                 for did in dids {
1308                     self.impls.entry(did).or_insert(vec![]).push(Impl {
1309                         impl_item: item.clone(),
1310                     });
1311                 }
1312                 None
1313             } else {
1314                 Some(item)
1315             }
1316         });
1317
1318         if pushed { self.stack.pop().unwrap(); }
1319         if parent_pushed { self.parent_stack.pop().unwrap(); }
1320         self.stripped_mod = orig_stripped_mod;
1321         self.parent_is_trait_impl = orig_parent_is_trait_impl;
1322         ret
1323     }
1324 }
1325
1326 impl<'a> Cache {
1327     fn generics(&mut self, generics: &clean::Generics) {
1328         for param in &generics.params {
1329             if let clean::GenericParam::Type(ref typ) = *param {
1330                 self.typarams.insert(typ.did, typ.name.clone());
1331             }
1332         }
1333     }
1334 }
1335
1336 impl Context {
1337     /// String representation of how to get back to the root path of the 'doc/'
1338     /// folder in terms of a relative URL.
1339     fn root_path(&self) -> String {
1340         repeat("../").take(self.current.len()).collect::<String>()
1341     }
1342
1343     /// Recurse in the directory structure and change the "root path" to make
1344     /// sure it always points to the top (relatively).
1345     fn recurse<T, F>(&mut self, s: String, f: F) -> T where
1346         F: FnOnce(&mut Context) -> T,
1347     {
1348         if s.is_empty() {
1349             panic!("Unexpected empty destination: {:?}", self.current);
1350         }
1351         let prev = self.dst.clone();
1352         self.dst.push(&s);
1353         self.current.push(s);
1354
1355         info!("Recursing into {}", self.dst.display());
1356
1357         let ret = f(self);
1358
1359         info!("Recursed; leaving {}", self.dst.display());
1360
1361         // Go back to where we were at
1362         self.dst = prev;
1363         self.current.pop().unwrap();
1364
1365         ret
1366     }
1367
1368     /// Main method for rendering a crate.
1369     ///
1370     /// This currently isn't parallelized, but it'd be pretty easy to add
1371     /// parallelization to this function.
1372     fn krate(self, mut krate: clean::Crate) -> Result<(), Error> {
1373         let mut item = match krate.module.take() {
1374             Some(i) => i,
1375             None => return Ok(()),
1376         };
1377         item.name = Some(krate.name);
1378
1379         // Render the crate documentation
1380         let mut work = vec![(self, item)];
1381
1382         while let Some((mut cx, item)) = work.pop() {
1383             cx.item(item, |cx, item| {
1384                 work.push((cx.clone(), item))
1385             })?
1386         }
1387         Ok(())
1388     }
1389
1390     fn render_item(&self,
1391                    writer: &mut io::Write,
1392                    it: &clean::Item,
1393                    pushname: bool)
1394                    -> io::Result<()> {
1395         // A little unfortunate that this is done like this, but it sure
1396         // does make formatting *a lot* nicer.
1397         CURRENT_LOCATION_KEY.with(|slot| {
1398             *slot.borrow_mut() = self.current.clone();
1399         });
1400
1401         let mut title = if it.is_primitive() {
1402             // No need to include the namespace for primitive types
1403             String::new()
1404         } else {
1405             self.current.join("::")
1406         };
1407         if pushname {
1408             if !title.is_empty() {
1409                 title.push_str("::");
1410             }
1411             title.push_str(it.name.as_ref().unwrap());
1412         }
1413         title.push_str(" - Rust");
1414         let tyname = it.type_().css_class();
1415         let desc = if it.is_crate() {
1416             format!("API documentation for the Rust `{}` crate.",
1417                     self.shared.layout.krate)
1418         } else {
1419             format!("API documentation for the Rust `{}` {} in crate `{}`.",
1420                     it.name.as_ref().unwrap(), tyname, self.shared.layout.krate)
1421         };
1422         let keywords = make_item_keywords(it);
1423         let page = layout::Page {
1424             css_class: tyname,
1425             root_path: &self.root_path(),
1426             title: &title,
1427             description: &desc,
1428             keywords: &keywords,
1429         };
1430
1431         reset_ids(true);
1432
1433         if !self.render_redirect_pages {
1434             layout::render(writer, &self.shared.layout, &page,
1435                            &Sidebar{ cx: self, item: it },
1436                            &Item{ cx: self, item: it },
1437                            self.shared.css_file_extension.is_some(),
1438                            &self.shared.themes)?;
1439         } else {
1440             let mut url = self.root_path();
1441             if let Some(&(ref names, ty)) = cache().paths.get(&it.def_id) {
1442                 for name in &names[..names.len() - 1] {
1443                     url.push_str(name);
1444                     url.push_str("/");
1445                 }
1446                 url.push_str(&item_path(ty, names.last().unwrap()));
1447                 layout::redirect(writer, &url)?;
1448             }
1449         }
1450         Ok(())
1451     }
1452
1453     /// Non-parallelized version of rendering an item. This will take the input
1454     /// item, render its contents, and then invoke the specified closure with
1455     /// all sub-items which need to be rendered.
1456     ///
1457     /// The rendering driver uses this closure to queue up more work.
1458     fn item<F>(&mut self, item: clean::Item, mut f: F) -> Result<(), Error> where
1459         F: FnMut(&mut Context, clean::Item),
1460     {
1461         // Stripped modules survive the rustdoc passes (i.e. `strip-private`)
1462         // if they contain impls for public types. These modules can also
1463         // contain items such as publicly re-exported structures.
1464         //
1465         // External crates will provide links to these structures, so
1466         // these modules are recursed into, but not rendered normally
1467         // (a flag on the context).
1468         if !self.render_redirect_pages {
1469             self.render_redirect_pages = item.is_stripped();
1470         }
1471
1472         if item.is_mod() {
1473             // modules are special because they add a namespace. We also need to
1474             // recurse into the items of the module as well.
1475             let name = item.name.as_ref().unwrap().to_string();
1476             let mut item = Some(item);
1477             self.recurse(name, |this| {
1478                 let item = item.take().unwrap();
1479
1480                 let mut buf = Vec::new();
1481                 this.render_item(&mut buf, &item, false).unwrap();
1482                 // buf will be empty if the module is stripped and there is no redirect for it
1483                 if !buf.is_empty() {
1484                     try_err!(this.shared.ensure_dir(&this.dst), &this.dst);
1485                     let joint_dst = this.dst.join("index.html");
1486                     let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1487                     try_err!(dst.write_all(&buf), &joint_dst);
1488                 }
1489
1490                 let m = match item.inner {
1491                     clean::StrippedItem(box clean::ModuleItem(m)) |
1492                     clean::ModuleItem(m) => m,
1493                     _ => unreachable!()
1494                 };
1495
1496                 // Render sidebar-items.js used throughout this module.
1497                 if !this.render_redirect_pages {
1498                     let items = this.build_sidebar_items(&m);
1499                     let js_dst = this.dst.join("sidebar-items.js");
1500                     let mut js_out = BufWriter::new(try_err!(File::create(&js_dst), &js_dst));
1501                     try_err!(write!(&mut js_out, "initSidebarItems({});",
1502                                     as_json(&items)), &js_dst);
1503                 }
1504
1505                 for item in m.items {
1506                     f(this,item);
1507                 }
1508
1509                 Ok(())
1510             })?;
1511         } else if item.name.is_some() {
1512             let mut buf = Vec::new();
1513             self.render_item(&mut buf, &item, true).unwrap();
1514             // buf will be empty if the item is stripped and there is no redirect for it
1515             if !buf.is_empty() {
1516                 let name = item.name.as_ref().unwrap();
1517                 let item_type = item.type_();
1518                 let file_name = &item_path(item_type, name);
1519                 try_err!(self.shared.ensure_dir(&self.dst), &self.dst);
1520                 let joint_dst = self.dst.join(file_name);
1521                 let mut dst = try_err!(File::create(&joint_dst), &joint_dst);
1522                 try_err!(dst.write_all(&buf), &joint_dst);
1523
1524                 // Redirect from a sane URL using the namespace to Rustdoc's
1525                 // URL for the page.
1526                 let redir_name = format!("{}.{}.html", name, item_type.name_space());
1527                 let redir_dst = self.dst.join(redir_name);
1528                 if let Ok(redirect_out) = OpenOptions::new().create_new(true)
1529                                                                 .write(true)
1530                                                                 .open(&redir_dst) {
1531                     let mut redirect_out = BufWriter::new(redirect_out);
1532                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1533                 }
1534
1535                 // If the item is a macro, redirect from the old macro URL (with !)
1536                 // to the new one (without).
1537                 // FIXME(#35705) remove this redirect.
1538                 if item_type == ItemType::Macro {
1539                     let redir_name = format!("{}.{}!.html", item_type, name);
1540                     let redir_dst = self.dst.join(redir_name);
1541                     let redirect_out = try_err!(File::create(&redir_dst), &redir_dst);
1542                     let mut redirect_out = BufWriter::new(redirect_out);
1543                     try_err!(layout::redirect(&mut redirect_out, file_name), &redir_dst);
1544                 }
1545             }
1546         }
1547         Ok(())
1548     }
1549
1550     fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> {
1551         // BTreeMap instead of HashMap to get a sorted output
1552         let mut map = BTreeMap::new();
1553         for item in &m.items {
1554             if item.is_stripped() { continue }
1555
1556             let short = item.type_().css_class();
1557             let myname = match item.name {
1558                 None => continue,
1559                 Some(ref s) => s.to_string(),
1560             };
1561             let short = short.to_string();
1562             map.entry(short).or_insert(vec![])
1563                 .push((myname, Some(plain_summary_line(item.doc_value()))));
1564         }
1565
1566         if self.shared.sort_modules_alphabetically {
1567             for (_, items) in &mut map {
1568                 items.sort();
1569             }
1570         }
1571         map
1572     }
1573 }
1574
1575 impl<'a> Item<'a> {
1576     /// Generate a url appropriate for an `href` attribute back to the source of
1577     /// this item.
1578     ///
1579     /// The url generated, when clicked, will redirect the browser back to the
1580     /// original source code.
1581     ///
1582     /// If `None` is returned, then a source link couldn't be generated. This
1583     /// may happen, for example, with externally inlined items where the source
1584     /// of their crate documentation isn't known.
1585     fn src_href(&self) -> Option<String> {
1586         let mut root = self.cx.root_path();
1587
1588         let cache = cache();
1589         let mut path = String::new();
1590
1591         // We can safely ignore macros from other libraries
1592         let file = match self.item.source.filename {
1593             FileName::Real(ref path) => path,
1594             _ => return None,
1595         };
1596
1597         let (krate, path) = if self.item.def_id.is_local() {
1598             if let Some(path) = self.cx.shared.local_sources.get(file) {
1599                 (&self.cx.shared.layout.krate, path)
1600             } else {
1601                 return None;
1602             }
1603         } else {
1604             let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) {
1605                 Some(&(ref name, ref src, Local)) => (name, src),
1606                 Some(&(ref name, ref src, Remote(ref s))) => {
1607                     root = s.to_string();
1608                     (name, src)
1609                 }
1610                 Some(&(_, _, Unknown)) | None => return None,
1611             };
1612
1613             clean_srcpath(&src_root, file, false, |component| {
1614                 path.push_str(component);
1615                 path.push('/');
1616             });
1617             let mut fname = file.file_name().expect("source has no filename")
1618                                 .to_os_string();
1619             fname.push(".html");
1620             path.push_str(&fname.to_string_lossy());
1621             (krate, &path)
1622         };
1623
1624         let lines = if self.item.source.loline == self.item.source.hiline {
1625             format!("{}", self.item.source.loline)
1626         } else {
1627             format!("{}-{}", self.item.source.loline, self.item.source.hiline)
1628         };
1629         Some(format!("{root}src/{krate}/{path}#{lines}",
1630                      root = Escape(&root),
1631                      krate = krate,
1632                      path = path,
1633                      lines = lines))
1634     }
1635 }
1636
1637 impl<'a> fmt::Display for Item<'a> {
1638     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1639         debug_assert!(!self.item.is_stripped());
1640         // Write the breadcrumb trail header for the top
1641         write!(fmt, "\n<h1 class='fqn'><span class='in-band'>")?;
1642         match self.item.inner {
1643             clean::ModuleItem(ref m) => if m.is_crate {
1644                     write!(fmt, "Crate ")?;
1645                 } else {
1646                     write!(fmt, "Module ")?;
1647                 },
1648             clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => write!(fmt, "Function ")?,
1649             clean::TraitItem(..) => write!(fmt, "Trait ")?,
1650             clean::StructItem(..) => write!(fmt, "Struct ")?,
1651             clean::UnionItem(..) => write!(fmt, "Union ")?,
1652             clean::EnumItem(..) => write!(fmt, "Enum ")?,
1653             clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
1654             clean::MacroItem(..) => write!(fmt, "Macro ")?,
1655             clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
1656             clean::StaticItem(..) | clean::ForeignStaticItem(..) => write!(fmt, "Static ")?,
1657             clean::ConstantItem(..) => write!(fmt, "Constant ")?,
1658             clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
1659             _ => {
1660                 // We don't generate pages for any other type.
1661                 unreachable!();
1662             }
1663         }
1664         if !self.item.is_primitive() {
1665             let cur = &self.cx.current;
1666             let amt = if self.item.is_mod() { cur.len() - 1 } else { cur.len() };
1667             for (i, component) in cur.iter().enumerate().take(amt) {
1668                 write!(fmt, "<a href='{}index.html'>{}</a>::<wbr>",
1669                        repeat("../").take(cur.len() - i - 1)
1670                                     .collect::<String>(),
1671                        component)?;
1672             }
1673         }
1674         write!(fmt, "<a class=\"{}\" href=''>{}</a>",
1675                self.item.type_(), self.item.name.as_ref().unwrap())?;
1676
1677         write!(fmt, "</span>")?; // in-band
1678         write!(fmt, "<span class='out-of-band'>")?;
1679         if let Some(version) = self.item.stable_since() {
1680             write!(fmt, "<span class='since' title='Stable since Rust version {0}'>{0}</span>",
1681                    version)?;
1682         }
1683         write!(fmt,
1684                r##"<span id='render-detail'>
1685                    <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
1686                        [<span class='inner'>&#x2212;</span>]
1687                    </a>
1688                </span>"##)?;
1689
1690         // Write `src` tag
1691         //
1692         // When this item is part of a `pub use` in a downstream crate, the
1693         // [src] link in the downstream documentation will actually come back to
1694         // this page, and this link will be auto-clicked. The `id` attribute is
1695         // used to find the link to auto-click.
1696         if self.cx.shared.include_sources && !self.item.is_primitive() {
1697             if let Some(l) = self.src_href() {
1698                 write!(fmt, "<a class='srclink' href='{}' title='{}'>[src]</a>",
1699                        l, "goto source code")?;
1700             }
1701         }
1702
1703         write!(fmt, "</span>")?; // out-of-band
1704
1705         write!(fmt, "</h1>\n")?;
1706
1707         match self.item.inner {
1708             clean::ModuleItem(ref m) => {
1709                 item_module(fmt, self.cx, self.item, &m.items)
1710             }
1711             clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) =>
1712                 item_function(fmt, self.cx, self.item, f),
1713             clean::TraitItem(ref t) => item_trait(fmt, self.cx, self.item, t),
1714             clean::StructItem(ref s) => item_struct(fmt, self.cx, self.item, s),
1715             clean::UnionItem(ref s) => item_union(fmt, self.cx, self.item, s),
1716             clean::EnumItem(ref e) => item_enum(fmt, self.cx, self.item, e),
1717             clean::TypedefItem(ref t, _) => item_typedef(fmt, self.cx, self.item, t),
1718             clean::MacroItem(ref m) => item_macro(fmt, self.cx, self.item, m),
1719             clean::PrimitiveItem(ref p) => item_primitive(fmt, self.cx, self.item, p),
1720             clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) =>
1721                 item_static(fmt, self.cx, self.item, i),
1722             clean::ConstantItem(ref c) => item_constant(fmt, self.cx, self.item, c),
1723             clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
1724             _ => {
1725                 // We don't generate pages for any other type.
1726                 unreachable!();
1727             }
1728         }
1729     }
1730 }
1731
1732 fn item_path(ty: ItemType, name: &str) -> String {
1733     match ty {
1734         ItemType::Module => format!("{}/index.html", name),
1735         _ => format!("{}.{}.html", ty.css_class(), name),
1736     }
1737 }
1738
1739 fn full_path(cx: &Context, item: &clean::Item) -> String {
1740     let mut s = cx.current.join("::");
1741     s.push_str("::");
1742     s.push_str(item.name.as_ref().unwrap());
1743     s
1744 }
1745
1746 fn shorter<'a>(s: Option<&'a str>) -> String {
1747     match s {
1748         Some(s) => s.lines()
1749             .skip_while(|s| s.chars().all(|c| c.is_whitespace()))
1750             .take_while(|line|{
1751             (*line).chars().any(|chr|{
1752                 !chr.is_whitespace()
1753             })
1754         }).collect::<Vec<_>>().join("\n"),
1755         None => "".to_string()
1756     }
1757 }
1758
1759 #[inline]
1760 fn plain_summary_line(s: Option<&str>) -> String {
1761     let line = shorter(s).replace("\n", " ");
1762     markdown::plain_summary_line(&line[..])
1763 }
1764
1765 fn document(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1766     if let Some(ref name) = item.name {
1767         info!("Documenting {}", name);
1768     }
1769     document_stability(w, cx, item)?;
1770     let prefix = render_assoc_const_value(item);
1771     document_full(w, item, cx, &prefix)?;
1772     Ok(())
1773 }
1774
1775 /// Render md_text as markdown.
1776 fn render_markdown(w: &mut fmt::Formatter,
1777                    md_text: &str,
1778                    links: Vec<(String, String)>,
1779                    prefix: &str,)
1780                    -> fmt::Result {
1781     write!(w, "<div class='docblock'>{}{}</div>", prefix, Markdown(md_text, &links))
1782 }
1783
1784 fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLink,
1785                   prefix: &str) -> fmt::Result {
1786     if let Some(s) = item.doc_value() {
1787         let markdown = if s.contains('\n') {
1788             format!("{} [Read more]({})",
1789                     &plain_summary_line(Some(s)), naive_assoc_href(item, link))
1790         } else {
1791             format!("{}", &plain_summary_line(Some(s)))
1792         };
1793         render_markdown(w, &markdown, item.links(), prefix)?;
1794     } else if !prefix.is_empty() {
1795         write!(w, "<div class='docblock'>{}</div>", prefix)?;
1796     }
1797     Ok(())
1798 }
1799
1800 fn render_assoc_const_value(item: &clean::Item) -> String {
1801     match item.inner {
1802         clean::AssociatedConstItem(ref ty, Some(ref default)) => {
1803             highlight::render_with_highlighting(
1804                 &format!("{}: {:#} = {}", item.name.as_ref().unwrap(), ty, default),
1805                 None,
1806                 None,
1807                 None,
1808                 None,
1809             )
1810         }
1811         _ => String::new(),
1812     }
1813 }
1814
1815 fn document_full(w: &mut fmt::Formatter, item: &clean::Item,
1816                  cx: &Context, prefix: &str) -> fmt::Result {
1817     if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) {
1818         debug!("Doc block: =====\n{}\n=====", s);
1819         render_markdown(w, &*s, item.links(), prefix)?;
1820     } else if !prefix.is_empty() {
1821         write!(w, "<div class='docblock'>{}</div>", prefix)?;
1822     }
1823     Ok(())
1824 }
1825
1826 fn document_stability(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item) -> fmt::Result {
1827     let stabilities = short_stability(item, cx, true);
1828     if !stabilities.is_empty() {
1829         write!(w, "<div class='stability'>")?;
1830         for stability in stabilities {
1831             write!(w, "{}", stability)?;
1832         }
1833         write!(w, "</div>")?;
1834     }
1835     Ok(())
1836 }
1837
1838 fn name_key(name: &str) -> (&str, u64, usize) {
1839     // find number at end
1840     let split = name.bytes().rposition(|b| b < b'0' || b'9' < b).map_or(0, |s| s + 1);
1841
1842     // count leading zeroes
1843     let after_zeroes =
1844         name[split..].bytes().position(|b| b != b'0').map_or(name.len(), |extra| split + extra);
1845
1846     // sort leading zeroes last
1847     let num_zeroes = after_zeroes - split;
1848
1849     match name[split..].parse() {
1850         Ok(n) => (&name[..split], n, num_zeroes),
1851         Err(_) => (name, 0, num_zeroes),
1852     }
1853 }
1854
1855 fn item_module(w: &mut fmt::Formatter, cx: &Context,
1856                item: &clean::Item, items: &[clean::Item]) -> fmt::Result {
1857     document(w, cx, item)?;
1858
1859     let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped())
1860                                       .collect::<Vec<usize>>();
1861
1862     // the order of item types in the listing
1863     fn reorder(ty: ItemType) -> u8 {
1864         match ty {
1865             ItemType::ExternCrate     => 0,
1866             ItemType::Import          => 1,
1867             ItemType::Primitive       => 2,
1868             ItemType::Module          => 3,
1869             ItemType::Macro           => 4,
1870             ItemType::Struct          => 5,
1871             ItemType::Enum            => 6,
1872             ItemType::Constant        => 7,
1873             ItemType::Static          => 8,
1874             ItemType::Trait           => 9,
1875             ItemType::Function        => 10,
1876             ItemType::Typedef         => 12,
1877             ItemType::Union           => 13,
1878             _                         => 14 + ty as u8,
1879         }
1880     }
1881
1882     fn cmp(i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize) -> Ordering {
1883         let ty1 = i1.type_();
1884         let ty2 = i2.type_();
1885         if ty1 != ty2 {
1886             return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2))
1887         }
1888         let s1 = i1.stability.as_ref().map(|s| s.level);
1889         let s2 = i2.stability.as_ref().map(|s| s.level);
1890         match (s1, s2) {
1891             (Some(stability::Unstable), Some(stability::Stable)) => return Ordering::Greater,
1892             (Some(stability::Stable), Some(stability::Unstable)) => return Ordering::Less,
1893             _ => {}
1894         }
1895         let lhs = i1.name.as_ref().map_or("", |s| &**s);
1896         let rhs = i2.name.as_ref().map_or("", |s| &**s);
1897         name_key(lhs).cmp(&name_key(rhs))
1898     }
1899
1900     if cx.shared.sort_modules_alphabetically {
1901         indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2));
1902     }
1903     // This call is to remove re-export duplicates in cases such as:
1904     //
1905     // ```
1906     // pub mod foo {
1907     //     pub mod bar {
1908     //         pub trait Double { fn foo(); }
1909     //     }
1910     // }
1911     //
1912     // pub use foo::bar::*;
1913     // pub use foo::*;
1914     // ```
1915     //
1916     // `Double` will appear twice in the generated docs.
1917     //
1918     // FIXME: This code is quite ugly and could be improved. Small issue: DefId
1919     // can be identical even if the elements are different (mostly in imports).
1920     // So in case this is an import, we keep everything by adding a "unique id"
1921     // (which is the position in the vector).
1922     indices.dedup_by_key(|i| (items[*i].def_id,
1923                               if items[*i].name.as_ref().is_some() {
1924                                   Some(full_path(cx, &items[*i]).clone())
1925                               } else {
1926                                   None
1927                               },
1928                               items[*i].type_(),
1929                               if items[*i].is_import() {
1930                                   *i
1931                               } else {
1932                                   0
1933                               }));
1934
1935     debug!("{:?}", indices);
1936     let mut curty = None;
1937     for &idx in &indices {
1938         let myitem = &items[idx];
1939         if myitem.is_stripped() {
1940             continue;
1941         }
1942
1943         let myty = Some(myitem.type_());
1944         if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) {
1945             // Put `extern crate` and `use` re-exports in the same section.
1946             curty = myty;
1947         } else if myty != curty {
1948             if curty.is_some() {
1949                 write!(w, "</table>")?;
1950             }
1951             curty = myty;
1952             let (short, name) = match myty.unwrap() {
1953                 ItemType::ExternCrate |
1954                 ItemType::Import          => ("reexports", "Re-exports"),
1955                 ItemType::Module          => ("modules", "Modules"),
1956                 ItemType::Struct          => ("structs", "Structs"),
1957                 ItemType::Union           => ("unions", "Unions"),
1958                 ItemType::Enum            => ("enums", "Enums"),
1959                 ItemType::Function        => ("functions", "Functions"),
1960                 ItemType::Typedef         => ("types", "Type Definitions"),
1961                 ItemType::Static          => ("statics", "Statics"),
1962                 ItemType::Constant        => ("constants", "Constants"),
1963                 ItemType::Trait           => ("traits", "Traits"),
1964                 ItemType::Impl            => ("impls", "Implementations"),
1965                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
1966                 ItemType::Method          => ("methods", "Methods"),
1967                 ItemType::StructField     => ("fields", "Struct Fields"),
1968                 ItemType::Variant         => ("variants", "Variants"),
1969                 ItemType::Macro           => ("macros", "Macros"),
1970                 ItemType::Primitive       => ("primitives", "Primitive Types"),
1971                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
1972                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
1973                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
1974             };
1975             write!(w, "<h2 id='{id}' class='section-header'>\
1976                        <a href=\"#{id}\">{name}</a></h2>\n<table>",
1977                    id = derive_id(short.to_owned()), name = name)?;
1978         }
1979
1980         match myitem.inner {
1981             clean::ExternCrateItem(ref name, ref src) => {
1982                 use html::format::HRef;
1983
1984                 match *src {
1985                     Some(ref src) => {
1986                         write!(w, "<tr><td><code>{}extern crate {} as {};",
1987                                VisSpace(&myitem.visibility),
1988                                HRef::new(myitem.def_id, src),
1989                                name)?
1990                     }
1991                     None => {
1992                         write!(w, "<tr><td><code>{}extern crate {};",
1993                                VisSpace(&myitem.visibility),
1994                                HRef::new(myitem.def_id, name))?
1995                     }
1996                 }
1997                 write!(w, "</code></td></tr>")?;
1998             }
1999
2000             clean::ImportItem(ref import) => {
2001                 write!(w, "<tr><td><code>{}{}</code></td></tr>",
2002                        VisSpace(&myitem.visibility), *import)?;
2003             }
2004
2005             _ => {
2006                 if myitem.name.is_none() { continue }
2007
2008                 let stabilities = short_stability(myitem, cx, false);
2009
2010                 let stab_docs = if !stabilities.is_empty() {
2011                     stabilities.iter()
2012                                .map(|s| format!("[{}]", s))
2013                                .collect::<Vec<_>>()
2014                                .as_slice()
2015                                .join(" ")
2016                 } else {
2017                     String::new()
2018                 };
2019
2020                 let unsafety_flag = match myitem.inner {
2021                     clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func)
2022                     if func.unsafety == hir::Unsafety::Unsafe => {
2023                         "<a title='unsafe function' href='#'><sup>âš </sup></a>"
2024                     }
2025                     _ => "",
2026                 };
2027
2028                 let doc_value = myitem.doc_value().unwrap_or("");
2029                 write!(w, "
2030                        <tr class='{stab} module-item'>
2031                            <td><a class=\"{class}\" href=\"{href}\"
2032                                   title='{title_type} {title}'>{name}</a>{unsafety_flag}</td>
2033                            <td class='docblock-short'>
2034                                {stab_docs} {docs}
2035                            </td>
2036                        </tr>",
2037                        name = *myitem.name.as_ref().unwrap(),
2038                        stab_docs = stab_docs,
2039                        docs = MarkdownSummaryLine(doc_value, &myitem.links()),
2040                        class = myitem.type_(),
2041                        stab = myitem.stability_class().unwrap_or("".to_string()),
2042                        unsafety_flag = unsafety_flag,
2043                        href = item_path(myitem.type_(), myitem.name.as_ref().unwrap()),
2044                        title_type = myitem.type_(),
2045                        title = full_path(cx, myitem))?;
2046             }
2047         }
2048     }
2049
2050     if curty.is_some() {
2051         write!(w, "</table>")?;
2052     }
2053     Ok(())
2054 }
2055
2056 fn short_stability(item: &clean::Item, cx: &Context, show_reason: bool) -> Vec<String> {
2057     let mut stability = vec![];
2058
2059     if let Some(stab) = item.stability.as_ref() {
2060         let deprecated_reason = if show_reason && !stab.deprecated_reason.is_empty() {
2061             format!(": {}", stab.deprecated_reason)
2062         } else {
2063             String::new()
2064         };
2065         if !stab.deprecated_since.is_empty() {
2066             let since = if show_reason {
2067                 format!(" since {}", Escape(&stab.deprecated_since))
2068             } else {
2069                 String::new()
2070             };
2071             let text = format!("Deprecated{}{}",
2072                                since,
2073                                MarkdownHtml(&deprecated_reason));
2074             stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2075         };
2076
2077         if stab.level == stability::Unstable {
2078             if show_reason {
2079                 let unstable_extra = match (!stab.feature.is_empty(),
2080                                             &cx.shared.issue_tracker_base_url,
2081                                             stab.issue) {
2082                     (true, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2083                         format!(" (<code>{} </code><a href=\"{}{}\">#{}</a>)",
2084                                 Escape(&stab.feature), tracker_url, issue_no, issue_no),
2085                     (false, &Some(ref tracker_url), Some(issue_no)) if issue_no > 0 =>
2086                         format!(" (<a href=\"{}{}\">#{}</a>)", Escape(&tracker_url), issue_no,
2087                                 issue_no),
2088                     (true, ..) =>
2089                         format!(" (<code>{}</code>)", Escape(&stab.feature)),
2090                     _ => String::new(),
2091                 };
2092                 if stab.unstable_reason.is_empty() {
2093                     stability.push(format!("<div class='stab unstable'>\
2094                                             <span class=microscope>🔬</span> \
2095                                             This is a nightly-only experimental API. {}\
2096                                             </div>",
2097                                            unstable_extra));
2098                 } else {
2099                     let text = format!("<summary><span class=microscope>🔬</span> \
2100                                         This is a nightly-only experimental API. {}\
2101                                         </summary>{}",
2102                                        unstable_extra,
2103                                        MarkdownHtml(&stab.unstable_reason));
2104                     stability.push(format!("<div class='stab unstable'><details>{}</details></div>",
2105                                    text));
2106                 }
2107             } else {
2108                 stability.push(format!("<div class='stab unstable'>Experimental</div>"))
2109             }
2110         };
2111     } else if let Some(depr) = item.deprecation.as_ref() {
2112         let note = if show_reason && !depr.note.is_empty() {
2113             format!(": {}", depr.note)
2114         } else {
2115             String::new()
2116         };
2117         let since = if show_reason && !depr.since.is_empty() {
2118             format!(" since {}", Escape(&depr.since))
2119         } else {
2120             String::new()
2121         };
2122
2123         let text = format!("Deprecated{}{}", since, MarkdownHtml(&note));
2124         stability.push(format!("<div class='stab deprecated'>{}</div>", text))
2125     }
2126
2127     if let Some(ref cfg) = item.attrs.cfg {
2128         stability.push(format!("<div class='stab portability'>{}</div>", if show_reason {
2129             cfg.render_long_html()
2130         } else {
2131             cfg.render_short_html()
2132         }));
2133     }
2134
2135     stability
2136 }
2137
2138 struct Initializer<'a>(&'a str);
2139
2140 impl<'a> fmt::Display for Initializer<'a> {
2141     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2142         let Initializer(s) = *self;
2143         if s.is_empty() { return Ok(()); }
2144         write!(f, "<code> = </code>")?;
2145         write!(f, "<code>{}</code>", Escape(s))
2146     }
2147 }
2148
2149 fn item_constant(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2150                  c: &clean::Constant) -> fmt::Result {
2151     write!(w, "<pre class='rust const'>")?;
2152     render_attributes(w, it)?;
2153     write!(w, "{vis}const \
2154                {name}: {typ}{init}</pre>",
2155            vis = VisSpace(&it.visibility),
2156            name = it.name.as_ref().unwrap(),
2157            typ = c.type_,
2158            init = Initializer(&c.expr))?;
2159     document(w, cx, it)
2160 }
2161
2162 fn item_static(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2163                s: &clean::Static) -> fmt::Result {
2164     write!(w, "<pre class='rust static'>")?;
2165     render_attributes(w, it)?;
2166     write!(w, "{vis}static {mutability}\
2167                {name}: {typ}{init}</pre>",
2168            vis = VisSpace(&it.visibility),
2169            mutability = MutableSpace(s.mutability),
2170            name = it.name.as_ref().unwrap(),
2171            typ = s.type_,
2172            init = Initializer(&s.expr))?;
2173     document(w, cx, it)
2174 }
2175
2176 fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2177                  f: &clean::Function) -> fmt::Result {
2178     let name_len = format!("{}{}{}{:#}fn {}{:#}",
2179                            VisSpace(&it.visibility),
2180                            ConstnessSpace(f.constness),
2181                            UnsafetySpace(f.unsafety),
2182                            AbiSpace(f.abi),
2183                            it.name.as_ref().unwrap(),
2184                            f.generics).len();
2185     write!(w, "{}<pre class='rust fn'>", render_spotlight_traits(it)?)?;
2186     render_attributes(w, it)?;
2187     write!(w,
2188            "{vis}{constness}{unsafety}{abi}fn {name}{generics}{decl}{where_clause}</pre>",
2189            vis = VisSpace(&it.visibility),
2190            constness = ConstnessSpace(f.constness),
2191            unsafety = UnsafetySpace(f.unsafety),
2192            abi = AbiSpace(f.abi),
2193            name = it.name.as_ref().unwrap(),
2194            generics = f.generics,
2195            where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
2196            decl = Method {
2197               decl: &f.decl,
2198               name_len,
2199               indent: 0,
2200            })?;
2201     document(w, cx, it)
2202 }
2203
2204 fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2205               t: &clean::Trait) -> fmt::Result {
2206     let mut bounds = String::new();
2207     let mut bounds_plain = String::new();
2208     if !t.bounds.is_empty() {
2209         if !bounds.is_empty() {
2210             bounds.push(' ');
2211             bounds_plain.push(' ');
2212         }
2213         bounds.push_str(": ");
2214         bounds_plain.push_str(": ");
2215         for (i, p) in t.bounds.iter().enumerate() {
2216             if i > 0 {
2217                 bounds.push_str(" + ");
2218                 bounds_plain.push_str(" + ");
2219             }
2220             bounds.push_str(&format!("{}", *p));
2221             bounds_plain.push_str(&format!("{:#}", *p));
2222         }
2223     }
2224
2225     // Output the trait definition
2226     write!(w, "<pre class='rust trait'>")?;
2227     render_attributes(w, it)?;
2228     write!(w, "{}{}{}trait {}{}{}",
2229            VisSpace(&it.visibility),
2230            UnsafetySpace(t.unsafety),
2231            if t.is_auto { "auto " } else { "" },
2232            it.name.as_ref().unwrap(),
2233            t.generics,
2234            bounds)?;
2235
2236     if !t.generics.where_predicates.is_empty() {
2237         write!(w, "{}", WhereClause { gens: &t.generics, indent: 0, end_newline: true })?;
2238     } else {
2239         write!(w, " ")?;
2240     }
2241
2242     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
2243     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
2244     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
2245     let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>();
2246
2247     if t.items.is_empty() {
2248         write!(w, "{{ }}")?;
2249     } else {
2250         // FIXME: we should be using a derived_id for the Anchors here
2251         write!(w, "{{\n")?;
2252         for t in &types {
2253             write!(w, "    ")?;
2254             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2255             write!(w, ";\n")?;
2256         }
2257         if !types.is_empty() && !consts.is_empty() {
2258             w.write_str("\n")?;
2259         }
2260         for t in &consts {
2261             write!(w, "    ")?;
2262             render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait)?;
2263             write!(w, ";\n")?;
2264         }
2265         if !consts.is_empty() && !required.is_empty() {
2266             w.write_str("\n")?;
2267         }
2268         for (pos, m) in required.iter().enumerate() {
2269             write!(w, "    ")?;
2270             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2271             write!(w, ";\n")?;
2272
2273             if pos < required.len() - 1 {
2274                write!(w, "<div class='item-spacer'></div>")?;
2275             }
2276         }
2277         if !required.is_empty() && !provided.is_empty() {
2278             w.write_str("\n")?;
2279         }
2280         for (pos, m) in provided.iter().enumerate() {
2281             write!(w, "    ")?;
2282             render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait)?;
2283             match m.inner {
2284                 clean::MethodItem(ref inner) if !inner.generics.where_predicates.is_empty() => {
2285                     write!(w, ",\n    {{ ... }}\n")?;
2286                 },
2287                 _ => {
2288                     write!(w, " {{ ... }}\n")?;
2289                 },
2290             }
2291             if pos < provided.len() - 1 {
2292                write!(w, "<div class='item-spacer'></div>")?;
2293             }
2294         }
2295         write!(w, "}}")?;
2296     }
2297     write!(w, "</pre>")?;
2298
2299     // Trait documentation
2300     document(w, cx, it)?;
2301
2302     fn trait_item(w: &mut fmt::Formatter, cx: &Context, m: &clean::Item, t: &clean::Item)
2303                   -> fmt::Result {
2304         let name = m.name.as_ref().unwrap();
2305         let item_type = m.type_();
2306         let id = derive_id(format!("{}.{}", item_type, name));
2307         let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
2308         write!(w, "{extra}<h3 id='{id}' class='method'>\
2309                    <span id='{ns_id}' class='invisible'><code>",
2310                extra = render_spotlight_traits(m)?,
2311                id = id,
2312                ns_id = ns_id)?;
2313         render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl)?;
2314         write!(w, "</code>")?;
2315         render_stability_since(w, m, t)?;
2316         write!(w, "</span></h3>")?;
2317         document(w, cx, m)?;
2318         Ok(())
2319     }
2320
2321     if !types.is_empty() {
2322         write!(w, "
2323             <h2 id='associated-types' class='small-section-header'>
2324               Associated Types<a href='#associated-types' class='anchor'></a>
2325             </h2>
2326             <div class='methods'>
2327         ")?;
2328         for t in &types {
2329             trait_item(w, cx, *t, it)?;
2330         }
2331         write!(w, "</div>")?;
2332     }
2333
2334     if !consts.is_empty() {
2335         write!(w, "
2336             <h2 id='associated-const' class='small-section-header'>
2337               Associated Constants<a href='#associated-const' class='anchor'></a>
2338             </h2>
2339             <div class='methods'>
2340         ")?;
2341         for t in &consts {
2342             trait_item(w, cx, *t, it)?;
2343         }
2344         write!(w, "</div>")?;
2345     }
2346
2347     // Output the documentation for each function individually
2348     if !required.is_empty() {
2349         write!(w, "
2350             <h2 id='required-methods' class='small-section-header'>
2351               Required Methods<a href='#required-methods' class='anchor'></a>
2352             </h2>
2353             <div class='methods'>
2354         ")?;
2355         for m in &required {
2356             trait_item(w, cx, *m, it)?;
2357         }
2358         write!(w, "</div>")?;
2359     }
2360     if !provided.is_empty() {
2361         write!(w, "
2362             <h2 id='provided-methods' class='small-section-header'>
2363               Provided Methods<a href='#provided-methods' class='anchor'></a>
2364             </h2>
2365             <div class='methods'>
2366         ")?;
2367         for m in &provided {
2368             trait_item(w, cx, *m, it)?;
2369         }
2370         write!(w, "</div>")?;
2371     }
2372
2373     // If there are methods directly on this trait object, render them here.
2374     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2375
2376     let cache = cache();
2377     let impl_header = "
2378         <h2 id='implementors' class='small-section-header'>
2379           Implementors<a href='#implementors' class='anchor'></a>
2380         </h2>
2381         <ul class='item-list' id='implementors-list'>
2382     ";
2383     if let Some(implementors) = cache.implementors.get(&it.def_id) {
2384         // The DefId is for the first Type found with that name. The bool is
2385         // if any Types with the same name but different DefId have been found.
2386         let mut implementor_dups: FxHashMap<&str, (DefId, bool)> = FxHashMap();
2387         for implementor in implementors {
2388             match implementor.inner_impl().for_ {
2389                 clean::ResolvedPath { ref path, did, is_generic: false, .. } |
2390                 clean::BorrowedRef {
2391                     type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. },
2392                     ..
2393                 } => {
2394                     let &mut (prev_did, ref mut has_duplicates) =
2395                         implementor_dups.entry(path.last_name()).or_insert((did, false));
2396                     if prev_did != did {
2397                         *has_duplicates = true;
2398                     }
2399                 }
2400                 _ => {}
2401             }
2402         }
2403
2404         let (local, foreign) = implementors.iter()
2405             .partition::<Vec<_>, _>(|i| i.inner_impl().for_.def_id()
2406                                          .map_or(true, |d| cache.paths.contains_key(&d)));
2407
2408         if !foreign.is_empty() {
2409             write!(w, "
2410                 <h2 id='foreign-impls' class='small-section-header'>
2411                   Implementations on Foreign Types<a href='#foreign-impls' class='anchor'></a>
2412                 </h2>
2413             ")?;
2414
2415             for implementor in foreign {
2416                 let assoc_link = AssocItemLink::GotoSource(
2417                     implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods
2418                 );
2419                 render_impl(w, cx, &implementor, assoc_link,
2420                             RenderMode::Normal, implementor.impl_item.stable_since(), false)?;
2421             }
2422         }
2423
2424         write!(w, "{}", impl_header)?;
2425
2426         for implementor in local {
2427             write!(w, "<li>")?;
2428             if let Some(l) = (Item { cx, item: &implementor.impl_item }).src_href() {
2429                 write!(w, "<div class='out-of-band'>")?;
2430                 write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
2431                             l, "goto source code")?;
2432                 write!(w, "</div>")?;
2433             }
2434             write!(w, "<code>")?;
2435             // If there's already another implementor that has the same abbridged name, use the
2436             // full path, for example in `std::iter::ExactSizeIterator`
2437             let use_absolute = match implementor.inner_impl().for_ {
2438                 clean::ResolvedPath { ref path, is_generic: false, .. } |
2439                 clean::BorrowedRef {
2440                     type_: box clean::ResolvedPath { ref path, is_generic: false, .. },
2441                     ..
2442                 } => implementor_dups[path.last_name()].1,
2443                 _ => false,
2444             };
2445             fmt_impl_for_trait_page(&implementor.inner_impl(), w, use_absolute)?;
2446             for it in &implementor.inner_impl().items {
2447                 if let clean::TypedefItem(ref tydef, _) = it.inner {
2448                     write!(w, "<span class=\"where fmt-newline\">  ")?;
2449                     assoc_type(w, it, &vec![], Some(&tydef.type_), AssocItemLink::Anchor(None))?;
2450                     write!(w, ";</span>")?;
2451                 }
2452             }
2453             writeln!(w, "</code></li>")?;
2454         }
2455     } else {
2456         // even without any implementations to write in, we still want the heading and list, so the
2457         // implementors javascript file pulled in below has somewhere to write the impls into
2458         write!(w, "{}", impl_header)?;
2459     }
2460     write!(w, "</ul>")?;
2461     write!(w, r#"<script type="text/javascript" async
2462                          src="{root_path}/implementors/{path}/{ty}.{name}.js">
2463                  </script>"#,
2464            root_path = vec![".."; cx.current.len()].join("/"),
2465            path = if it.def_id.is_local() {
2466                cx.current.join("/")
2467            } else {
2468                let (ref path, _) = cache.external_paths[&it.def_id];
2469                path[..path.len() - 1].join("/")
2470            },
2471            ty = it.type_().css_class(),
2472            name = *it.name.as_ref().unwrap())?;
2473     Ok(())
2474 }
2475
2476 fn naive_assoc_href(it: &clean::Item, link: AssocItemLink) -> String {
2477     use html::item_type::ItemType::*;
2478
2479     let name = it.name.as_ref().unwrap();
2480     let ty = match it.type_() {
2481         Typedef | AssociatedType => AssociatedType,
2482         s@_ => s,
2483     };
2484
2485     let anchor = format!("#{}.{}", ty, name);
2486     match link {
2487         AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2488         AssocItemLink::Anchor(None) => anchor,
2489         AssocItemLink::GotoSource(did, _) => {
2490             href(did).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor)
2491         }
2492     }
2493 }
2494
2495 fn assoc_const(w: &mut fmt::Formatter,
2496                it: &clean::Item,
2497                ty: &clean::Type,
2498                _default: Option<&String>,
2499                link: AssocItemLink) -> fmt::Result {
2500     write!(w, "{}const <a href='{}' class=\"constant\"><b>{}</b></a>: {}",
2501            VisSpace(&it.visibility),
2502            naive_assoc_href(it, link),
2503            it.name.as_ref().unwrap(),
2504            ty)?;
2505     Ok(())
2506 }
2507
2508 fn assoc_type<W: fmt::Write>(w: &mut W, it: &clean::Item,
2509                              bounds: &Vec<clean::TyParamBound>,
2510                              default: Option<&clean::Type>,
2511                              link: AssocItemLink) -> fmt::Result {
2512     write!(w, "type <a href='{}' class=\"type\">{}</a>",
2513            naive_assoc_href(it, link),
2514            it.name.as_ref().unwrap())?;
2515     if !bounds.is_empty() {
2516         write!(w, ": {}", TyParamBounds(bounds))?
2517     }
2518     if let Some(default) = default {
2519         write!(w, " = {}", default)?;
2520     }
2521     Ok(())
2522 }
2523
2524 fn render_stability_since_raw<'a>(w: &mut fmt::Formatter,
2525                                   ver: Option<&'a str>,
2526                                   containing_ver: Option<&'a str>) -> fmt::Result {
2527     if let Some(v) = ver {
2528         if containing_ver != ver && v.len() > 0 {
2529             write!(w, "<div class='since' title='Stable since Rust version {0}'>{0}</div>",
2530                    v)?
2531         }
2532     }
2533     Ok(())
2534 }
2535
2536 fn render_stability_since(w: &mut fmt::Formatter,
2537                           item: &clean::Item,
2538                           containing_item: &clean::Item) -> fmt::Result {
2539     render_stability_since_raw(w, item.stable_since(), containing_item.stable_since())
2540 }
2541
2542 fn render_assoc_item(w: &mut fmt::Formatter,
2543                      item: &clean::Item,
2544                      link: AssocItemLink,
2545                      parent: ItemType) -> fmt::Result {
2546     fn method(w: &mut fmt::Formatter,
2547               meth: &clean::Item,
2548               unsafety: hir::Unsafety,
2549               constness: hir::Constness,
2550               abi: abi::Abi,
2551               g: &clean::Generics,
2552               d: &clean::FnDecl,
2553               link: AssocItemLink,
2554               parent: ItemType)
2555               -> fmt::Result {
2556         let name = meth.name.as_ref().unwrap();
2557         let anchor = format!("#{}.{}", meth.type_(), name);
2558         let href = match link {
2559             AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
2560             AssocItemLink::Anchor(None) => anchor,
2561             AssocItemLink::GotoSource(did, provided_methods) => {
2562                 // We're creating a link from an impl-item to the corresponding
2563                 // trait-item and need to map the anchored type accordingly.
2564                 let ty = if provided_methods.contains(name) {
2565                     ItemType::Method
2566                 } else {
2567                     ItemType::TyMethod
2568                 };
2569
2570                 href(did).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor)
2571             }
2572         };
2573         let mut head_len = format!("{}{}{}{:#}fn {}{:#}",
2574                                    VisSpace(&meth.visibility),
2575                                    ConstnessSpace(constness),
2576                                    UnsafetySpace(unsafety),
2577                                    AbiSpace(abi),
2578                                    name,
2579                                    *g).len();
2580         let (indent, end_newline) = if parent == ItemType::Trait {
2581             head_len += 4;
2582             (4, false)
2583         } else {
2584             (0, true)
2585         };
2586         write!(w, "{}{}{}{}fn <a href='{href}' class='fnname'>{name}</a>\
2587                    {generics}{decl}{where_clause}",
2588                VisSpace(&meth.visibility),
2589                ConstnessSpace(constness),
2590                UnsafetySpace(unsafety),
2591                AbiSpace(abi),
2592                href = href,
2593                name = name,
2594                generics = *g,
2595                decl = Method {
2596                    decl: d,
2597                    name_len: head_len,
2598                    indent,
2599                },
2600                where_clause = WhereClause {
2601                    gens: g,
2602                    indent,
2603                    end_newline,
2604                })
2605     }
2606     match item.inner {
2607         clean::StrippedItem(..) => Ok(()),
2608         clean::TyMethodItem(ref m) => {
2609             method(w, item, m.unsafety, hir::Constness::NotConst,
2610                    m.abi, &m.generics, &m.decl, link, parent)
2611         }
2612         clean::MethodItem(ref m) => {
2613             method(w, item, m.unsafety, m.constness,
2614                    m.abi, &m.generics, &m.decl, link, parent)
2615         }
2616         clean::AssociatedConstItem(ref ty, ref default) => {
2617             assoc_const(w, item, ty, default.as_ref(), link)
2618         }
2619         clean::AssociatedTypeItem(ref bounds, ref default) => {
2620             assoc_type(w, item, bounds, default.as_ref(), link)
2621         }
2622         _ => panic!("render_assoc_item called on non-associated-item")
2623     }
2624 }
2625
2626 fn item_struct(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2627                s: &clean::Struct) -> fmt::Result {
2628     write!(w, "<pre class='rust struct'>")?;
2629     render_attributes(w, it)?;
2630     render_struct(w,
2631                   it,
2632                   Some(&s.generics),
2633                   s.struct_type,
2634                   &s.fields,
2635                   "",
2636                   true)?;
2637     write!(w, "</pre>")?;
2638
2639     document(w, cx, it)?;
2640     let mut fields = s.fields.iter().filter_map(|f| {
2641         match f.inner {
2642             clean::StructFieldItem(ref ty) => Some((f, ty)),
2643             _ => None,
2644         }
2645     }).peekable();
2646     if let doctree::Plain = s.struct_type {
2647         if fields.peek().is_some() {
2648             write!(w, "<h2 id='fields' class='fields small-section-header'>
2649                        Fields<a href='#fields' class='anchor'></a></h2>")?;
2650             for (field, ty) in fields {
2651                 let id = derive_id(format!("{}.{}",
2652                                            ItemType::StructField,
2653                                            field.name.as_ref().unwrap()));
2654                 let ns_id = derive_id(format!("{}.{}",
2655                                               field.name.as_ref().unwrap(),
2656                                               ItemType::StructField.name_space()));
2657                 write!(w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">
2658                            <a href=\"#{id}\" class=\"anchor field\"></a>
2659                            <span id=\"{ns_id}\" class='invisible'>
2660                            <code>{name}: {ty}</code>
2661                            </span></span>",
2662                        item_type = ItemType::StructField,
2663                        id = id,
2664                        ns_id = ns_id,
2665                        name = field.name.as_ref().unwrap(),
2666                        ty = ty)?;
2667                 if let Some(stability_class) = field.stability_class() {
2668                     write!(w, "<span class='stab {stab}'></span>",
2669                         stab = stability_class)?;
2670                 }
2671                 document(w, cx, field)?;
2672             }
2673         }
2674     }
2675     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2676 }
2677
2678 fn item_union(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2679                s: &clean::Union) -> fmt::Result {
2680     write!(w, "<pre class='rust union'>")?;
2681     render_attributes(w, it)?;
2682     render_union(w,
2683                  it,
2684                  Some(&s.generics),
2685                  &s.fields,
2686                  "",
2687                  true)?;
2688     write!(w, "</pre>")?;
2689
2690     document(w, cx, it)?;
2691     let mut fields = s.fields.iter().filter_map(|f| {
2692         match f.inner {
2693             clean::StructFieldItem(ref ty) => Some((f, ty)),
2694             _ => None,
2695         }
2696     }).peekable();
2697     if fields.peek().is_some() {
2698         write!(w, "<h2 id='fields' class='fields small-section-header'>
2699                    Fields<a href='#fields' class='anchor'></a></h2>")?;
2700         for (field, ty) in fields {
2701             write!(w, "<span id='{shortty}.{name}' class=\"{shortty}\"><code>{name}: {ty}</code>
2702                        </span>",
2703                    shortty = ItemType::StructField,
2704                    name = field.name.as_ref().unwrap(),
2705                    ty = ty)?;
2706             if let Some(stability_class) = field.stability_class() {
2707                 write!(w, "<span class='stab {stab}'></span>",
2708                     stab = stability_class)?;
2709             }
2710             document(w, cx, field)?;
2711         }
2712     }
2713     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
2714 }
2715
2716 fn item_enum(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
2717              e: &clean::Enum) -> fmt::Result {
2718     write!(w, "<pre class='rust enum'>")?;
2719     render_attributes(w, it)?;
2720     write!(w, "{}enum {}{}{}",
2721            VisSpace(&it.visibility),
2722            it.name.as_ref().unwrap(),
2723            e.generics,
2724            WhereClause { gens: &e.generics, indent: 0, end_newline: true })?;
2725     if e.variants.is_empty() && !e.variants_stripped {
2726         write!(w, " {{}}")?;
2727     } else {
2728         write!(w, " {{\n")?;
2729         for v in &e.variants {
2730             write!(w, "    ")?;
2731             let name = v.name.as_ref().unwrap();
2732             match v.inner {
2733                 clean::VariantItem(ref var) => {
2734                     match var.kind {
2735                         clean::VariantKind::CLike => write!(w, "{}", name)?,
2736                         clean::VariantKind::Tuple(ref tys) => {
2737                             write!(w, "{}(", name)?;
2738                             for (i, ty) in tys.iter().enumerate() {
2739                                 if i > 0 {
2740                                     write!(w, ",&nbsp;")?
2741                                 }
2742                                 write!(w, "{}", *ty)?;
2743                             }
2744                             write!(w, ")")?;
2745                         }
2746                         clean::VariantKind::Struct(ref s) => {
2747                             render_struct(w,
2748                                           v,
2749                                           None,
2750                                           s.struct_type,
2751                                           &s.fields,
2752                                           "    ",
2753                                           false)?;
2754                         }
2755                     }
2756                 }
2757                 _ => unreachable!()
2758             }
2759             write!(w, ",\n")?;
2760         }
2761
2762         if e.variants_stripped {
2763             write!(w, "    // some variants omitted\n")?;
2764         }
2765         write!(w, "}}")?;
2766     }
2767     write!(w, "</pre>")?;
2768
2769     document(w, cx, it)?;
2770     if !e.variants.is_empty() {
2771         write!(w, "<h2 id='variants' class='variants small-section-header'>
2772                    Variants<a href='#variants' class='anchor'></a></h2>\n")?;
2773         for variant in &e.variants {
2774             let id = derive_id(format!("{}.{}",
2775                                        ItemType::Variant,
2776                                        variant.name.as_ref().unwrap()));
2777             let ns_id = derive_id(format!("{}.{}",
2778                                           variant.name.as_ref().unwrap(),
2779                                           ItemType::Variant.name_space()));
2780             write!(w, "<span id=\"{id}\" class=\"variant small-section-header\">\
2781                        <a href=\"#{id}\" class=\"anchor field\"></a>\
2782                        <span id='{ns_id}' class='invisible'><code>{name}",
2783                    id = id,
2784                    ns_id = ns_id,
2785                    name = variant.name.as_ref().unwrap())?;
2786             if let clean::VariantItem(ref var) = variant.inner {
2787                 if let clean::VariantKind::Tuple(ref tys) = var.kind {
2788                     write!(w, "(")?;
2789                     for (i, ty) in tys.iter().enumerate() {
2790                         if i > 0 {
2791                             write!(w, ",&nbsp;")?;
2792                         }
2793                         write!(w, "{}", *ty)?;
2794                     }
2795                     write!(w, ")")?;
2796                 }
2797             }
2798             write!(w, "</code></span></span>")?;
2799             document(w, cx, variant)?;
2800
2801             use clean::{Variant, VariantKind};
2802             if let clean::VariantItem(Variant {
2803                 kind: VariantKind::Struct(ref s)
2804             }) = variant.inner {
2805                 let variant_id = derive_id(format!("{}.{}.fields",
2806                                                    ItemType::Variant,
2807                                                    variant.name.as_ref().unwrap()));
2808                 write!(w, "<span class='docblock autohide sub-variant' id='{id}'>",
2809                        id = variant_id)?;
2810                 write!(w, "<h3 class='fields'>Fields of <code>{name}</code></h3>\n
2811                            <table>", name = variant.name.as_ref().unwrap())?;
2812                 for field in &s.fields {
2813                     use clean::StructFieldItem;
2814                     if let StructFieldItem(ref ty) = field.inner {
2815                         let id = derive_id(format!("variant.{}.field.{}",
2816                                                    variant.name.as_ref().unwrap(),
2817                                                    field.name.as_ref().unwrap()));
2818                         let ns_id = derive_id(format!("{}.{}.{}.{}",
2819                                                       variant.name.as_ref().unwrap(),
2820                                                       ItemType::Variant.name_space(),
2821                                                       field.name.as_ref().unwrap(),
2822                                                       ItemType::StructField.name_space()));
2823                         write!(w, "<tr><td \
2824                                    id='{id}'>\
2825                                    <span id='{ns_id}' class='invisible'>\
2826                                    <code>{f}:&nbsp;{t}</code></span></td><td>",
2827                                id = id,
2828                                ns_id = ns_id,
2829                                f = field.name.as_ref().unwrap(),
2830                                t = *ty)?;
2831                         document(w, cx, field)?;
2832                         write!(w, "</td></tr>")?;
2833                     }
2834                 }
2835                 write!(w, "</table></span>")?;
2836             }
2837             render_stability_since(w, variant, it)?;
2838         }
2839     }
2840     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)?;
2841     Ok(())
2842 }
2843
2844 fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
2845     let name = attr.name();
2846
2847     if attr.is_word() {
2848         Some(format!("{}", name))
2849     } else if let Some(v) = attr.value_str() {
2850         Some(format!("{} = {:?}", name, v.as_str()))
2851     } else if let Some(values) = attr.meta_item_list() {
2852         let display: Vec<_> = values.iter().filter_map(|attr| {
2853             attr.meta_item().and_then(|mi| render_attribute(mi))
2854         }).collect();
2855
2856         if display.len() > 0 {
2857             Some(format!("{}({})", name, display.join(", ")))
2858         } else {
2859             None
2860         }
2861     } else {
2862         None
2863     }
2864 }
2865
2866 const ATTRIBUTE_WHITELIST: &'static [&'static str] = &[
2867     "export_name",
2868     "lang",
2869     "link_section",
2870     "must_use",
2871     "no_mangle",
2872     "repr",
2873     "unsafe_destructor_blind_to_params"
2874 ];
2875
2876 fn render_attributes(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
2877     let mut attrs = String::new();
2878
2879     for attr in &it.attrs.other_attrs {
2880         let name = attr.name().unwrap();
2881         if !ATTRIBUTE_WHITELIST.contains(&&*name.as_str()) {
2882             continue;
2883         }
2884         if let Some(s) = render_attribute(&attr.meta().unwrap()) {
2885             attrs.push_str(&format!("#[{}]\n", s));
2886         }
2887     }
2888     if attrs.len() > 0 {
2889         write!(w, "<div class=\"docblock attributes\">{}</div>", &attrs)?;
2890     }
2891     Ok(())
2892 }
2893
2894 fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
2895                  g: Option<&clean::Generics>,
2896                  ty: doctree::StructType,
2897                  fields: &[clean::Item],
2898                  tab: &str,
2899                  structhead: bool) -> fmt::Result {
2900     write!(w, "{}{}{}",
2901            VisSpace(&it.visibility),
2902            if structhead {"struct "} else {""},
2903            it.name.as_ref().unwrap())?;
2904     if let Some(g) = g {
2905         write!(w, "{}", g)?
2906     }
2907     match ty {
2908         doctree::Plain => {
2909             if let Some(g) = g {
2910                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?
2911             }
2912             let mut has_visible_fields = false;
2913             write!(w, " {{")?;
2914             for field in fields {
2915                 if let clean::StructFieldItem(ref ty) = field.inner {
2916                     write!(w, "\n{}    {}{}: {},",
2917                            tab,
2918                            VisSpace(&field.visibility),
2919                            field.name.as_ref().unwrap(),
2920                            *ty)?;
2921                     has_visible_fields = true;
2922                 }
2923             }
2924
2925             if has_visible_fields {
2926                 if it.has_stripped_fields().unwrap() {
2927                     write!(w, "\n{}    // some fields omitted", tab)?;
2928                 }
2929                 write!(w, "\n{}", tab)?;
2930             } else if it.has_stripped_fields().unwrap() {
2931                 // If there are no visible fields we can just display
2932                 // `{ /* fields omitted */ }` to save space.
2933                 write!(w, " /* fields omitted */ ")?;
2934             }
2935             write!(w, "}}")?;
2936         }
2937         doctree::Tuple => {
2938             write!(w, "(")?;
2939             for (i, field) in fields.iter().enumerate() {
2940                 if i > 0 {
2941                     write!(w, ", ")?;
2942                 }
2943                 match field.inner {
2944                     clean::StrippedItem(box clean::StructFieldItem(..)) => {
2945                         write!(w, "_")?
2946                     }
2947                     clean::StructFieldItem(ref ty) => {
2948                         write!(w, "{}{}", VisSpace(&field.visibility), *ty)?
2949                     }
2950                     _ => unreachable!()
2951                 }
2952             }
2953             write!(w, ")")?;
2954             if let Some(g) = g {
2955                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2956             }
2957             write!(w, ";")?;
2958         }
2959         doctree::Unit => {
2960             // Needed for PhantomData.
2961             if let Some(g) = g {
2962                 write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: false })?
2963             }
2964             write!(w, ";")?;
2965         }
2966     }
2967     Ok(())
2968 }
2969
2970 fn render_union(w: &mut fmt::Formatter, it: &clean::Item,
2971                 g: Option<&clean::Generics>,
2972                 fields: &[clean::Item],
2973                 tab: &str,
2974                 structhead: bool) -> fmt::Result {
2975     write!(w, "{}{}{}",
2976            VisSpace(&it.visibility),
2977            if structhead {"union "} else {""},
2978            it.name.as_ref().unwrap())?;
2979     if let Some(g) = g {
2980         write!(w, "{}", g)?;
2981         write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true })?;
2982     }
2983
2984     write!(w, " {{\n{}", tab)?;
2985     for field in fields {
2986         if let clean::StructFieldItem(ref ty) = field.inner {
2987             write!(w, "    {}{}: {},\n{}",
2988                    VisSpace(&field.visibility),
2989                    field.name.as_ref().unwrap(),
2990                    *ty,
2991                    tab)?;
2992         }
2993     }
2994
2995     if it.has_stripped_fields().unwrap() {
2996         write!(w, "    // some fields omitted\n{}", tab)?;
2997     }
2998     write!(w, "}}")?;
2999     Ok(())
3000 }
3001
3002 #[derive(Copy, Clone)]
3003 enum AssocItemLink<'a> {
3004     Anchor(Option<&'a str>),
3005     GotoSource(DefId, &'a FxHashSet<String>),
3006 }
3007
3008 impl<'a> AssocItemLink<'a> {
3009     fn anchor(&self, id: &'a String) -> Self {
3010         match *self {
3011             AssocItemLink::Anchor(_) => { AssocItemLink::Anchor(Some(&id)) },
3012             ref other => *other,
3013         }
3014     }
3015 }
3016
3017 enum AssocItemRender<'a> {
3018     All,
3019     DerefFor { trait_: &'a clean::Type, type_: &'a clean::Type, deref_mut_: bool }
3020 }
3021
3022 #[derive(Copy, Clone, PartialEq)]
3023 enum RenderMode {
3024     Normal,
3025     ForDeref { mut_: bool },
3026 }
3027
3028 fn render_assoc_items(w: &mut fmt::Formatter,
3029                       cx: &Context,
3030                       containing_item: &clean::Item,
3031                       it: DefId,
3032                       what: AssocItemRender) -> fmt::Result {
3033     let c = cache();
3034     let v = match c.impls.get(&it) {
3035         Some(v) => v,
3036         None => return Ok(()),
3037     };
3038     let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| {
3039         i.inner_impl().trait_.is_none()
3040     });
3041     if !non_trait.is_empty() {
3042         let render_mode = match what {
3043             AssocItemRender::All => {
3044                 write!(w, "
3045                     <h2 id='methods' class='small-section-header'>
3046                       Methods<a href='#methods' class='anchor'></a>
3047                     </h2>
3048                 ")?;
3049                 RenderMode::Normal
3050             }
3051             AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => {
3052                 write!(w, "
3053                     <h2 id='deref-methods' class='small-section-header'>
3054                       Methods from {}&lt;Target = {}&gt;<a href='#deref-methods' class='anchor'></a>
3055                     </h2>
3056                 ", trait_, type_)?;
3057                 RenderMode::ForDeref { mut_: deref_mut_ }
3058             }
3059         };
3060         for i in &non_trait {
3061             render_impl(w, cx, i, AssocItemLink::Anchor(None), render_mode,
3062                         containing_item.stable_since(), true)?;
3063         }
3064     }
3065     if let AssocItemRender::DerefFor { .. } = what {
3066         return Ok(());
3067     }
3068     if !traits.is_empty() {
3069         let deref_impl = traits.iter().find(|t| {
3070             t.inner_impl().trait_.def_id() == c.deref_trait_did
3071         });
3072         if let Some(impl_) = deref_impl {
3073             let has_deref_mut = traits.iter().find(|t| {
3074                 t.inner_impl().trait_.def_id() == c.deref_mut_trait_did
3075             }).is_some();
3076             render_deref_methods(w, cx, impl_, containing_item, has_deref_mut)?;
3077         }
3078         write!(w, "
3079             <h2 id='implementations' class='small-section-header'>
3080               Trait Implementations<a href='#implementations' class='anchor'></a>
3081             </h2>
3082         ")?;
3083         for i in &traits {
3084             let did = i.trait_did().unwrap();
3085             let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods);
3086             render_impl(w, cx, i, assoc_link,
3087                         RenderMode::Normal, containing_item.stable_since(), true)?;
3088         }
3089     }
3090     Ok(())
3091 }
3092
3093 fn render_deref_methods(w: &mut fmt::Formatter, cx: &Context, impl_: &Impl,
3094                         container_item: &clean::Item, deref_mut: bool) -> fmt::Result {
3095     let deref_type = impl_.inner_impl().trait_.as_ref().unwrap();
3096     let target = impl_.inner_impl().items.iter().filter_map(|item| {
3097         match item.inner {
3098             clean::TypedefItem(ref t, true) => Some(&t.type_),
3099             _ => None,
3100         }
3101     }).next().expect("Expected associated type binding");
3102     let what = AssocItemRender::DerefFor { trait_: deref_type, type_: target,
3103                                            deref_mut_: deref_mut };
3104     if let Some(did) = target.def_id() {
3105         render_assoc_items(w, cx, container_item, did, what)
3106     } else {
3107         if let Some(prim) = target.primitive_type() {
3108             if let Some(&did) = cache().primitive_locations.get(&prim) {
3109                 render_assoc_items(w, cx, container_item, did, what)?;
3110             }
3111         }
3112         Ok(())
3113     }
3114 }
3115
3116 fn should_render_item(item: &clean::Item, deref_mut_: bool) -> bool {
3117     let self_type_opt = match item.inner {
3118         clean::MethodItem(ref method) => method.decl.self_type(),
3119         clean::TyMethodItem(ref method) => method.decl.self_type(),
3120         _ => None
3121     };
3122
3123     if let Some(self_ty) = self_type_opt {
3124         let (by_mut_ref, by_box, by_value) = match self_ty {
3125             SelfTy::SelfBorrowed(_, mutability) |
3126             SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => {
3127                 (mutability == Mutability::Mutable, false, false)
3128             },
3129             SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => {
3130                 (false, Some(did) == cache().owned_box_did, false)
3131             },
3132             SelfTy::SelfValue => (false, false, true),
3133             _ => (false, false, false),
3134         };
3135
3136         (deref_mut_ || !by_mut_ref) && !by_box && !by_value
3137     } else {
3138         false
3139     }
3140 }
3141
3142 fn render_spotlight_traits(item: &clean::Item) -> Result<String, fmt::Error> {
3143     let mut out = String::new();
3144
3145     match item.inner {
3146         clean::FunctionItem(clean::Function { ref decl, .. }) |
3147         clean::TyMethodItem(clean::TyMethod { ref decl, .. }) |
3148         clean::MethodItem(clean::Method { ref decl, .. }) |
3149         clean::ForeignFunctionItem(clean::Function { ref decl, .. }) => {
3150             out = spotlight_decl(decl)?;
3151         }
3152         _ => {}
3153     }
3154
3155     Ok(out)
3156 }
3157
3158 fn spotlight_decl(decl: &clean::FnDecl) -> Result<String, fmt::Error> {
3159     let mut out = String::new();
3160     let mut trait_ = String::new();
3161
3162     if let Some(did) = decl.output.def_id() {
3163         let c = cache();
3164         if let Some(impls) = c.impls.get(&did) {
3165             for i in impls {
3166                 let impl_ = i.inner_impl();
3167                 if impl_.trait_.def_id().map_or(false, |d| c.traits[&d].is_spotlight) {
3168                     if out.is_empty() {
3169                         out.push_str(
3170                             &format!("<h3 class=\"important\">Important traits for {}</h3>\
3171                                       <code class=\"content\">",
3172                                      impl_.for_));
3173                         trait_.push_str(&format!("{}", impl_.for_));
3174                     }
3175
3176                     //use the "where" class here to make it small
3177                     out.push_str(&format!("<span class=\"where fmt-newline\">{}</span>", impl_));
3178                     let t_did = impl_.trait_.def_id().unwrap();
3179                     for it in &impl_.items {
3180                         if let clean::TypedefItem(ref tydef, _) = it.inner {
3181                             out.push_str("<span class=\"where fmt-newline\">    ");
3182                             assoc_type(&mut out, it, &vec![],
3183                                        Some(&tydef.type_),
3184                                        AssocItemLink::GotoSource(t_did, &FxHashSet()))?;
3185                             out.push_str(";</span>");
3186                         }
3187                     }
3188                 }
3189             }
3190         }
3191     }
3192
3193     if !out.is_empty() {
3194         out.insert_str(0, &format!("<div class=\"important-traits\"><div class='tooltip'>ⓘ\
3195                                     <span class='tooltiptext'>Important traits for {}</span></div>\
3196                                     <div class=\"content hidden\">",
3197                                    trait_));
3198         out.push_str("</code></div></div>");
3199     }
3200
3201     Ok(out)
3202 }
3203
3204 fn render_impl(w: &mut fmt::Formatter, cx: &Context, i: &Impl, link: AssocItemLink,
3205                render_mode: RenderMode, outer_version: Option<&str>,
3206                show_def_docs: bool) -> fmt::Result {
3207     if render_mode == RenderMode::Normal {
3208         let id = derive_id(match i.inner_impl().trait_ {
3209             Some(ref t) => format!("impl-{}", small_url_encode(&format!("{:#}", t))),
3210             None => "impl".to_string(),
3211         });
3212         write!(w, "<h3 id='{}' class='impl'><span class='in-band'><code>{}</code>",
3213                id, i.inner_impl())?;
3214         write!(w, "<a href='#{}' class='anchor'></a>", id)?;
3215         write!(w, "</span><span class='out-of-band'>")?;
3216         let since = i.impl_item.stability.as_ref().map(|s| &s.since[..]);
3217         if let Some(l) = (Item { item: &i.impl_item, cx: cx }).src_href() {
3218             write!(w, "<div class='ghost'></div>")?;
3219             render_stability_since_raw(w, since, outer_version)?;
3220             write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3221                    l, "goto source code")?;
3222         } else {
3223             render_stability_since_raw(w, since, outer_version)?;
3224         }
3225         write!(w, "</span>")?;
3226         write!(w, "</h3>\n")?;
3227         if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) {
3228             write!(w, "<div class='docblock'>{}</div>",
3229                    Markdown(&*dox, &i.impl_item.links()))?;
3230         }
3231     }
3232
3233     fn doc_impl_item(w: &mut fmt::Formatter, cx: &Context, item: &clean::Item,
3234                      link: AssocItemLink, render_mode: RenderMode,
3235                      is_default_item: bool, outer_version: Option<&str>,
3236                      trait_: Option<&clean::Trait>, show_def_docs: bool) -> fmt::Result {
3237         let item_type = item.type_();
3238         let name = item.name.as_ref().unwrap();
3239
3240         let render_method_item: bool = match render_mode {
3241             RenderMode::Normal => true,
3242             RenderMode::ForDeref { mut_: deref_mut_ } => should_render_item(&item, deref_mut_),
3243         };
3244
3245         match item.inner {
3246             clean::MethodItem(clean::Method { ref decl, .. }) |
3247             clean::TyMethodItem(clean::TyMethod{ ref decl, .. }) => {
3248                 // Only render when the method is not static or we allow static methods
3249                 if render_method_item {
3250                     let id = derive_id(format!("{}.{}", item_type, name));
3251                     let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3252                     write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3253                     write!(w, "{}", spotlight_decl(decl)?)?;
3254                     write!(w, "<span id='{}' class='invisible'>", ns_id)?;
3255                     write!(w, "<code>")?;
3256                     render_assoc_item(w, item, link.anchor(&id), ItemType::Impl)?;
3257                     write!(w, "</code>")?;
3258                     if let Some(l) = (Item { cx, item }).src_href() {
3259                         write!(w, "</span><span class='out-of-band'>")?;
3260                         write!(w, "<div class='ghost'></div>")?;
3261                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3262                         write!(w, "<a class='srclink' href='{}' title='{}'>[src]</a>",
3263                                l, "goto source code")?;
3264                     } else {
3265                         render_stability_since_raw(w, item.stable_since(), outer_version)?;
3266                     }
3267                     write!(w, "</span></h4>\n")?;
3268                 }
3269             }
3270             clean::TypedefItem(ref tydef, _) => {
3271                 let id = derive_id(format!("{}.{}", ItemType::AssociatedType, name));
3272                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3273                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3274                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3275                 assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id))?;
3276                 write!(w, "</code></span></h4>\n")?;
3277             }
3278             clean::AssociatedConstItem(ref ty, ref default) => {
3279                 let id = derive_id(format!("{}.{}", item_type, name));
3280                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3281                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3282                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3283                 assoc_const(w, item, ty, default.as_ref(), link.anchor(&id))?;
3284                 write!(w, "</code></span></h4>\n")?;
3285             }
3286             clean::AssociatedTypeItem(ref bounds, ref default) => {
3287                 let id = derive_id(format!("{}.{}", item_type, name));
3288                 let ns_id = derive_id(format!("{}.{}", name, item_type.name_space()));
3289                 write!(w, "<h4 id='{}' class=\"{}\">", id, item_type)?;
3290                 write!(w, "<span id='{}' class='invisible'><code>", ns_id)?;
3291                 assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id))?;
3292                 write!(w, "</code></span></h4>\n")?;
3293             }
3294             clean::StrippedItem(..) => return Ok(()),
3295             _ => panic!("can't make docs for trait item with name {:?}", item.name)
3296         }
3297
3298         if render_method_item || render_mode == RenderMode::Normal {
3299             let prefix = render_assoc_const_value(item);
3300
3301             if !is_default_item {
3302                 if let Some(t) = trait_ {
3303                     // The trait item may have been stripped so we might not
3304                     // find any documentation or stability for it.
3305                     if let Some(it) = t.items.iter().find(|i| i.name == item.name) {
3306                         // We need the stability of the item from the trait
3307                         // because impls can't have a stability.
3308                         document_stability(w, cx, it)?;
3309                         if item.doc_value().is_some() {
3310                             document_full(w, item, cx, &prefix)?;
3311                         } else if show_def_docs {
3312                             // In case the item isn't documented,
3313                             // provide short documentation from the trait.
3314                             document_short(w, it, link, &prefix)?;
3315                         }
3316                     }
3317                 } else {
3318                     document_stability(w, cx, item)?;
3319                     if show_def_docs {
3320                         document_full(w, item, cx, &prefix)?;
3321                     }
3322                 }
3323             } else {
3324                 document_stability(w, cx, item)?;
3325                 if show_def_docs {
3326                     document_short(w, item, link, &prefix)?;
3327                 }
3328             }
3329         }
3330         Ok(())
3331     }
3332
3333     let traits = &cache().traits;
3334     let trait_ = i.trait_did().map(|did| &traits[&did]);
3335
3336     if !show_def_docs {
3337         write!(w, "<span class='docblock autohide'>")?;
3338     }
3339
3340     write!(w, "<div class='impl-items'>")?;
3341     for trait_item in &i.inner_impl().items {
3342         doc_impl_item(w, cx, trait_item, link, render_mode,
3343                       false, outer_version, trait_, show_def_docs)?;
3344     }
3345
3346     fn render_default_items(w: &mut fmt::Formatter,
3347                             cx: &Context,
3348                             t: &clean::Trait,
3349                             i: &clean::Impl,
3350                             render_mode: RenderMode,
3351                             outer_version: Option<&str>,
3352                             show_def_docs: bool) -> fmt::Result {
3353         for trait_item in &t.items {
3354             let n = trait_item.name.clone();
3355             if i.items.iter().find(|m| m.name == n).is_some() {
3356                 continue;
3357             }
3358             let did = i.trait_.as_ref().unwrap().def_id().unwrap();
3359             let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods);
3360
3361             doc_impl_item(w, cx, trait_item, assoc_link, render_mode, true,
3362                           outer_version, None, show_def_docs)?;
3363         }
3364         Ok(())
3365     }
3366
3367     // If we've implemented a trait, then also emit documentation for all
3368     // default items which weren't overridden in the implementation block.
3369     if let Some(t) = trait_ {
3370         render_default_items(w, cx, t, &i.inner_impl(),
3371                              render_mode, outer_version, show_def_docs)?;
3372     }
3373     write!(w, "</div>")?;
3374
3375     if !show_def_docs {
3376         write!(w, "</span>")?;
3377     }
3378
3379     Ok(())
3380 }
3381
3382 fn item_typedef(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3383                 t: &clean::Typedef) -> fmt::Result {
3384     write!(w, "<pre class='rust typedef'>")?;
3385     render_attributes(w, it)?;
3386     write!(w, "type {}{}{where_clause} = {type_};</pre>",
3387            it.name.as_ref().unwrap(),
3388            t.generics,
3389            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
3390            type_ = t.type_)?;
3391
3392     document(w, cx, it)?;
3393
3394     // Render any items associated directly to this alias, as otherwise they
3395     // won't be visible anywhere in the docs. It would be nice to also show
3396     // associated items from the aliased type (see discussion in #32077), but
3397     // we need #14072 to make sense of the generics.
3398     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3399 }
3400
3401 fn item_foreign_type(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item) -> fmt::Result {
3402     writeln!(w, "<pre class='rust foreigntype'>extern {{")?;
3403     render_attributes(w, it)?;
3404     write!(
3405         w,
3406         "    {}type {};\n}}</pre>",
3407         VisSpace(&it.visibility),
3408         it.name.as_ref().unwrap(),
3409     )?;
3410
3411     document(w, cx, it)?;
3412
3413     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3414 }
3415
3416 impl<'a> fmt::Display for Sidebar<'a> {
3417     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3418         let cx = self.cx;
3419         let it = self.item;
3420         let parentlen = cx.current.len() - if it.is_mod() {1} else {0};
3421         let mut should_close = false;
3422
3423         if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union()
3424             || it.is_enum() || it.is_mod() || it.is_typedef()
3425         {
3426             write!(fmt, "<p class='location'>")?;
3427             match it.inner {
3428                 clean::StructItem(..) => write!(fmt, "Struct ")?,
3429                 clean::TraitItem(..) => write!(fmt, "Trait ")?,
3430                 clean::PrimitiveItem(..) => write!(fmt, "Primitive Type ")?,
3431                 clean::UnionItem(..) => write!(fmt, "Union ")?,
3432                 clean::EnumItem(..) => write!(fmt, "Enum ")?,
3433                 clean::TypedefItem(..) => write!(fmt, "Type Definition ")?,
3434                 clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
3435                 clean::ModuleItem(..) => if it.is_crate() {
3436                     write!(fmt, "Crate ")?;
3437                 } else {
3438                     write!(fmt, "Module ")?;
3439                 },
3440                 _ => (),
3441             }
3442             write!(fmt, "{}", it.name.as_ref().unwrap())?;
3443             write!(fmt, "</p>")?;
3444
3445             if it.is_crate() {
3446                 if let Some(ref version) = cache().crate_version {
3447                     write!(fmt,
3448                            "<div class='block version'>\
3449                             <p>Version {}</p>\
3450                             </div>",
3451                            version)?;
3452                 }
3453             }
3454
3455             write!(fmt, "<div class=\"sidebar-elems\">")?;
3456             should_close = true;
3457             match it.inner {
3458                 clean::StructItem(ref s) => sidebar_struct(fmt, it, s)?,
3459                 clean::TraitItem(ref t) => sidebar_trait(fmt, it, t)?,
3460                 clean::PrimitiveItem(ref p) => sidebar_primitive(fmt, it, p)?,
3461                 clean::UnionItem(ref u) => sidebar_union(fmt, it, u)?,
3462                 clean::EnumItem(ref e) => sidebar_enum(fmt, it, e)?,
3463                 clean::TypedefItem(ref t, _) => sidebar_typedef(fmt, it, t)?,
3464                 clean::ModuleItem(ref m) => sidebar_module(fmt, it, &m.items)?,
3465                 clean::ForeignTypeItem => sidebar_foreign_type(fmt, it)?,
3466                 _ => (),
3467             }
3468         }
3469
3470         // The sidebar is designed to display sibling functions, modules and
3471         // other miscellaneous information. since there are lots of sibling
3472         // items (and that causes quadratic growth in large modules),
3473         // we refactor common parts into a shared JavaScript file per module.
3474         // still, we don't move everything into JS because we want to preserve
3475         // as much HTML as possible in order to allow non-JS-enabled browsers
3476         // to navigate the documentation (though slightly inefficiently).
3477
3478         write!(fmt, "<p class='location'>")?;
3479         for (i, name) in cx.current.iter().take(parentlen).enumerate() {
3480             if i > 0 {
3481                 write!(fmt, "::<wbr>")?;
3482             }
3483             write!(fmt, "<a href='{}index.html'>{}</a>",
3484                    &cx.root_path()[..(cx.current.len() - i - 1) * 3],
3485                    *name)?;
3486         }
3487         write!(fmt, "</p>")?;
3488
3489         // Sidebar refers to the enclosing module, not this module.
3490         let relpath = if it.is_mod() { "../" } else { "" };
3491         write!(fmt,
3492                "<script>window.sidebarCurrent = {{\
3493                    name: '{name}', \
3494                    ty: '{ty}', \
3495                    relpath: '{path}'\
3496                 }};</script>",
3497                name = it.name.as_ref().map(|x| &x[..]).unwrap_or(""),
3498                ty = it.type_().css_class(),
3499                path = relpath)?;
3500         if parentlen == 0 {
3501             // There is no sidebar-items.js beyond the crate root path
3502             // FIXME maybe dynamic crate loading can be merged here
3503         } else {
3504             write!(fmt, "<script defer src=\"{path}sidebar-items.js\"></script>",
3505                    path = relpath)?;
3506         }
3507         if should_close {
3508             // Closes sidebar-elems div.
3509             write!(fmt, "</div>")?;
3510         }
3511
3512         Ok(())
3513     }
3514 }
3515
3516 fn get_methods(i: &clean::Impl, for_deref: bool) -> Vec<String> {
3517     i.items.iter().filter_map(|item| {
3518         match item.name {
3519             // Maybe check with clean::Visibility::Public as well?
3520             Some(ref name) if !name.is_empty() && item.visibility.is_some() && item.is_method() => {
3521                 if !for_deref || should_render_item(item, false) {
3522                     Some(format!("<a href=\"#method.{name}\">{name}</a>", name = name))
3523                 } else {
3524                     None
3525                 }
3526             }
3527             _ => None,
3528         }
3529     }).collect::<Vec<_>>()
3530 }
3531
3532 // The point is to url encode any potential character from a type with genericity.
3533 fn small_url_encode(s: &str) -> String {
3534     s.replace("<", "%3C")
3535      .replace(">", "%3E")
3536      .replace(" ", "%20")
3537      .replace("?", "%3F")
3538      .replace("'", "%27")
3539      .replace("&", "%26")
3540      .replace(",", "%2C")
3541      .replace(":", "%3A")
3542      .replace(";", "%3B")
3543      .replace("[", "%5B")
3544      .replace("]", "%5D")
3545      .replace("\"", "%22")
3546 }
3547
3548 fn sidebar_assoc_items(it: &clean::Item) -> String {
3549     let mut out = String::new();
3550     let c = cache();
3551     if let Some(v) = c.impls.get(&it.def_id) {
3552         let ret = v.iter()
3553                    .filter(|i| i.inner_impl().trait_.is_none())
3554                    .flat_map(|i| get_methods(i.inner_impl(), false))
3555                    .collect::<String>();
3556         if !ret.is_empty() {
3557             out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
3558                                    </a><div class=\"sidebar-links\">{}</div>", ret));
3559         }
3560
3561         if v.iter().any(|i| i.inner_impl().trait_.is_some()) {
3562             if let Some(impl_) = v.iter()
3563                                   .filter(|i| i.inner_impl().trait_.is_some())
3564                                   .find(|i| i.inner_impl().trait_.def_id() == c.deref_trait_did) {
3565                 if let Some(target) = impl_.inner_impl().items.iter().filter_map(|item| {
3566                     match item.inner {
3567                         clean::TypedefItem(ref t, true) => Some(&t.type_),
3568                         _ => None,
3569                     }
3570                 }).next() {
3571                     let inner_impl = target.def_id().or(target.primitive_type().and_then(|prim| {
3572                         c.primitive_locations.get(&prim).cloned()
3573                     })).and_then(|did| c.impls.get(&did));
3574                     if let Some(impls) = inner_impl {
3575                         out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");
3576                         out.push_str(&format!("Methods from {}&lt;Target={}&gt;",
3577                                               Escape(&format!("{:#}",
3578                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
3579                                               Escape(&format!("{:#}", target))));
3580                         out.push_str("</a>");
3581                         let ret = impls.iter()
3582                                        .filter(|i| i.inner_impl().trait_.is_none())
3583                                        .flat_map(|i| get_methods(i.inner_impl(), true))
3584                                        .collect::<String>();
3585                         out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3586                     }
3587                 }
3588             }
3589             let mut links = HashSet::new();
3590             let ret = v.iter()
3591                        .filter_map(|i| {
3592                            let is_negative_impl = is_negative_impl(i.inner_impl());
3593                            if let Some(ref i) = i.inner_impl().trait_ {
3594                                let i_display = format!("{:#}", i);
3595                                let out = Escape(&i_display);
3596                                let encoded = small_url_encode(&format!("{:#}", i));
3597                                let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
3598                                                        encoded,
3599                                                        if is_negative_impl { "!" } else { "" },
3600                                                        out);
3601                                if !links.contains(&generated) && links.insert(generated.clone()) {
3602                                    Some(generated)
3603                                } else {
3604                                    None
3605                                }
3606                            } else {
3607                                None
3608                            }
3609                        })
3610                        .collect::<String>();
3611             if !ret.is_empty() {
3612                 out.push_str("<a class=\"sidebar-title\" href=\"#implementations\">\
3613                               Trait Implementations</a>");
3614                 out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
3615             }
3616         }
3617     }
3618
3619     out
3620 }
3621
3622 fn sidebar_struct(fmt: &mut fmt::Formatter, it: &clean::Item,
3623                   s: &clean::Struct) -> fmt::Result {
3624     let mut sidebar = String::new();
3625     let fields = get_struct_fields_name(&s.fields);
3626
3627     if !fields.is_empty() {
3628         if let doctree::Plain = s.struct_type {
3629             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3630                                        <div class=\"sidebar-links\">{}</div>", fields));
3631         }
3632     }
3633
3634     sidebar.push_str(&sidebar_assoc_items(it));
3635
3636     if !sidebar.is_empty() {
3637         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3638     }
3639     Ok(())
3640 }
3641
3642 fn extract_for_impl_name(item: &clean::Item) -> Option<(String, String)> {
3643     match item.inner {
3644         clean::ItemEnum::ImplItem(ref i) => {
3645             if let Some(ref trait_) = i.trait_ {
3646                 Some((format!("{:#}", i.for_), format!("{:#}", trait_)))
3647             } else {
3648                 None
3649             }
3650         },
3651         _ => None,
3652     }
3653 }
3654
3655 fn is_negative_impl(i: &clean::Impl) -> bool {
3656     i.polarity == Some(clean::ImplPolarity::Negative)
3657 }
3658
3659 fn sidebar_trait(fmt: &mut fmt::Formatter, it: &clean::Item,
3660                  t: &clean::Trait) -> fmt::Result {
3661     let mut sidebar = String::new();
3662
3663     let types = t.items
3664                  .iter()
3665                  .filter_map(|m| {
3666                      match m.name {
3667                          Some(ref name) if m.is_associated_type() => {
3668                              Some(format!("<a href=\"#associatedtype.{name}\">{name}</a>",
3669                                           name=name))
3670                          }
3671                          _ => None,
3672                      }
3673                  })
3674                  .collect::<String>();
3675     let consts = t.items
3676                   .iter()
3677                   .filter_map(|m| {
3678                       match m.name {
3679                           Some(ref name) if m.is_associated_const() => {
3680                               Some(format!("<a href=\"#associatedconstant.{name}\">{name}</a>",
3681                                            name=name))
3682                           }
3683                           _ => None,
3684                       }
3685                   })
3686                   .collect::<String>();
3687     let required = t.items
3688                     .iter()
3689                     .filter_map(|m| {
3690                         match m.name {
3691                             Some(ref name) if m.is_ty_method() => {
3692                                 Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
3693                                              name=name))
3694                             }
3695                             _ => None,
3696                         }
3697                     })
3698                     .collect::<String>();
3699     let provided = t.items
3700                     .iter()
3701                     .filter_map(|m| {
3702                         match m.name {
3703                             Some(ref name) if m.is_method() => {
3704                                 Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
3705                             }
3706                             _ => None,
3707                         }
3708                     })
3709                     .collect::<String>();
3710
3711     if !types.is_empty() {
3712         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
3713                                    Associated Types</a><div class=\"sidebar-links\">{}</div>",
3714                                   types));
3715     }
3716     if !consts.is_empty() {
3717         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-const\">\
3718                                    Associated Constants</a><div class=\"sidebar-links\">{}</div>",
3719                                   consts));
3720     }
3721     if !required.is_empty() {
3722         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
3723                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
3724                                   required));
3725     }
3726     if !provided.is_empty() {
3727         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
3728                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
3729                                   provided));
3730     }
3731
3732     let c = cache();
3733
3734     if let Some(implementors) = c.implementors.get(&it.def_id) {
3735         let res = implementors.iter()
3736                               .filter(|i| i.inner_impl().for_.def_id()
3737                                            .map_or(false, |d| !c.paths.contains_key(&d)))
3738                               .filter_map(|i| {
3739                                   match extract_for_impl_name(&i.impl_item) {
3740                                       Some((ref name, ref url)) => {
3741                                           Some(format!("<a href=\"#impl-{}\">{}</a>",
3742                                                       small_url_encode(url),
3743                                                       Escape(name)))
3744                                       }
3745                                       _ => None,
3746                                   }
3747                               })
3748                               .collect::<String>();
3749         if !res.is_empty() {
3750             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
3751                                        Implementations on Foreign Types</a><div \
3752                                        class=\"sidebar-links\">{}</div>",
3753                                       res));
3754         }
3755     }
3756
3757     sidebar.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>");
3758
3759     sidebar.push_str(&sidebar_assoc_items(it));
3760
3761     write!(fmt, "<div class=\"block items\">{}</div>", sidebar)
3762 }
3763
3764 fn sidebar_primitive(fmt: &mut fmt::Formatter, it: &clean::Item,
3765                      _p: &clean::PrimitiveType) -> fmt::Result {
3766     let sidebar = sidebar_assoc_items(it);
3767
3768     if !sidebar.is_empty() {
3769         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3770     }
3771     Ok(())
3772 }
3773
3774 fn sidebar_typedef(fmt: &mut fmt::Formatter, it: &clean::Item,
3775                    _t: &clean::Typedef) -> fmt::Result {
3776     let sidebar = sidebar_assoc_items(it);
3777
3778     if !sidebar.is_empty() {
3779         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3780     }
3781     Ok(())
3782 }
3783
3784 fn get_struct_fields_name(fields: &[clean::Item]) -> String {
3785     fields.iter()
3786           .filter(|f| if let clean::StructFieldItem(..) = f.inner {
3787               true
3788           } else {
3789               false
3790           })
3791           .filter_map(|f| match f.name {
3792               Some(ref name) => Some(format!("<a href=\"#structfield.{name}\">\
3793                                               {name}</a>", name=name)),
3794               _ => None,
3795           })
3796           .collect()
3797 }
3798
3799 fn sidebar_union(fmt: &mut fmt::Formatter, it: &clean::Item,
3800                  u: &clean::Union) -> fmt::Result {
3801     let mut sidebar = String::new();
3802     let fields = get_struct_fields_name(&u.fields);
3803
3804     if !fields.is_empty() {
3805         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\
3806                                    <div class=\"sidebar-links\">{}</div>", fields));
3807     }
3808
3809     sidebar.push_str(&sidebar_assoc_items(it));
3810
3811     if !sidebar.is_empty() {
3812         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3813     }
3814     Ok(())
3815 }
3816
3817 fn sidebar_enum(fmt: &mut fmt::Formatter, it: &clean::Item,
3818                 e: &clean::Enum) -> fmt::Result {
3819     let mut sidebar = String::new();
3820
3821     let variants = e.variants.iter()
3822                              .filter_map(|v| match v.name {
3823                                  Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}\
3824                                                                  </a>", name = name)),
3825                                  _ => None,
3826                              })
3827                              .collect::<String>();
3828     if !variants.is_empty() {
3829         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\
3830                                    <div class=\"sidebar-links\">{}</div>", variants));
3831     }
3832
3833     sidebar.push_str(&sidebar_assoc_items(it));
3834
3835     if !sidebar.is_empty() {
3836         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3837     }
3838     Ok(())
3839 }
3840
3841 fn sidebar_module(fmt: &mut fmt::Formatter, _it: &clean::Item,
3842                   items: &[clean::Item]) -> fmt::Result {
3843     let mut sidebar = String::new();
3844
3845     if items.iter().any(|it| it.type_() == ItemType::ExternCrate ||
3846                              it.type_() == ItemType::Import) {
3847         sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3848                                   id = "reexports",
3849                                   name = "Re-exports"));
3850     }
3851
3852     // ordering taken from item_module, reorder, where it prioritized elements in a certain order
3853     // to print its headings
3854     for &myty in &[ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct,
3855                    ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait,
3856                    ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl,
3857                    ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant,
3858                    ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] {
3859         if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) {
3860             let (short, name) = match myty {
3861                 ItemType::ExternCrate |
3862                 ItemType::Import          => ("reexports", "Re-exports"),
3863                 ItemType::Module          => ("modules", "Modules"),
3864                 ItemType::Struct          => ("structs", "Structs"),
3865                 ItemType::Union           => ("unions", "Unions"),
3866                 ItemType::Enum            => ("enums", "Enums"),
3867                 ItemType::Function        => ("functions", "Functions"),
3868                 ItemType::Typedef         => ("types", "Type Definitions"),
3869                 ItemType::Static          => ("statics", "Statics"),
3870                 ItemType::Constant        => ("constants", "Constants"),
3871                 ItemType::Trait           => ("traits", "Traits"),
3872                 ItemType::Impl            => ("impls", "Implementations"),
3873                 ItemType::TyMethod        => ("tymethods", "Type Methods"),
3874                 ItemType::Method          => ("methods", "Methods"),
3875                 ItemType::StructField     => ("fields", "Struct Fields"),
3876                 ItemType::Variant         => ("variants", "Variants"),
3877                 ItemType::Macro           => ("macros", "Macros"),
3878                 ItemType::Primitive       => ("primitives", "Primitive Types"),
3879                 ItemType::AssociatedType  => ("associated-types", "Associated Types"),
3880                 ItemType::AssociatedConst => ("associated-consts", "Associated Constants"),
3881                 ItemType::ForeignType     => ("foreign-types", "Foreign Types"),
3882             };
3883             sidebar.push_str(&format!("<li><a href=\"#{id}\">{name}</a></li>",
3884                                       id = short,
3885                                       name = name));
3886         }
3887     }
3888
3889     if !sidebar.is_empty() {
3890         write!(fmt, "<div class=\"block items\"><ul>{}</ul></div>", sidebar)?;
3891     }
3892     Ok(())
3893 }
3894
3895 fn sidebar_foreign_type(fmt: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
3896     let sidebar = sidebar_assoc_items(it);
3897     if !sidebar.is_empty() {
3898         write!(fmt, "<div class=\"block items\">{}</div>", sidebar)?;
3899     }
3900     Ok(())
3901 }
3902
3903 impl<'a> fmt::Display for Source<'a> {
3904     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
3905         let Source(s) = *self;
3906         let lines = s.lines().count();
3907         let mut cols = 0;
3908         let mut tmp = lines;
3909         while tmp > 0 {
3910             cols += 1;
3911             tmp /= 10;
3912         }
3913         write!(fmt, "<pre class=\"line-numbers\">")?;
3914         for i in 1..lines + 1 {
3915             write!(fmt, "<span id=\"{0}\">{0:1$}</span>\n", i, cols)?;
3916         }
3917         write!(fmt, "</pre>")?;
3918         write!(fmt, "{}",
3919                highlight::render_with_highlighting(s, None, None, None, None))?;
3920         Ok(())
3921     }
3922 }
3923
3924 fn item_macro(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
3925               t: &clean::Macro) -> fmt::Result {
3926     w.write_str(&highlight::render_with_highlighting(&t.source,
3927                                                      Some("macro"),
3928                                                      None,
3929                                                      None,
3930                                                      None))?;
3931     document(w, cx, it)
3932 }
3933
3934 fn item_primitive(w: &mut fmt::Formatter, cx: &Context,
3935                   it: &clean::Item,
3936                   _p: &clean::PrimitiveType) -> fmt::Result {
3937     document(w, cx, it)?;
3938     render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
3939 }
3940
3941 const BASIC_KEYWORDS: &'static str = "rust, rustlang, rust-lang";
3942
3943 fn make_item_keywords(it: &clean::Item) -> String {
3944     format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap())
3945 }
3946
3947 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
3948     let decl = match item.inner {
3949         clean::FunctionItem(ref f) => &f.decl,
3950         clean::MethodItem(ref m) => &m.decl,
3951         clean::TyMethodItem(ref m) => &m.decl,
3952         _ => return None
3953     };
3954
3955     let inputs = decl.inputs.values.iter().map(|arg| get_index_type(&arg.type_)).collect();
3956     let output = match decl.output {
3957         clean::FunctionRetTy::Return(ref return_type) => Some(get_index_type(return_type)),
3958         _ => None
3959     };
3960
3961     Some(IndexItemFunctionType { inputs: inputs, output: output })
3962 }
3963
3964 fn get_index_type(clean_type: &clean::Type) -> Type {
3965     let t = Type {
3966         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
3967         generics: get_generics(clean_type),
3968     };
3969     t
3970 }
3971
3972 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
3973     match *clean_type {
3974         clean::ResolvedPath { ref path, .. } => {
3975             let segments = &path.segments;
3976             let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
3977                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
3978                 clean_type, accept_generic
3979             ));
3980             Some(path_segment.name.clone())
3981         }
3982         clean::Generic(ref s) if accept_generic => Some(s.clone()),
3983         clean::Primitive(ref p) => Some(format!("{:?}", p)),
3984         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
3985         // FIXME: add all from clean::Type.
3986         _ => None
3987     }
3988 }
3989
3990 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
3991     clean_type.generics()
3992               .and_then(|types| {
3993                   let r = types.iter()
3994                                .filter_map(|t| get_index_type_name(t, false))
3995                                .map(|s| s.to_ascii_lowercase())
3996                                .collect::<Vec<_>>();
3997                   if r.is_empty() {
3998                       None
3999                   } else {
4000                       Some(r)
4001                   }
4002               })
4003 }
4004
4005 pub fn cache() -> Arc<Cache> {
4006     CACHE_KEY.with(|c| c.borrow().clone())
4007 }
4008
4009 #[cfg(test)]
4010 #[test]
4011 fn test_unique_id() {
4012     let input = ["foo", "examples", "examples", "method.into_iter","examples",
4013                  "method.into_iter", "foo", "main", "search", "methods",
4014                  "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
4015     let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
4016                     "method.into_iter-1", "foo-1", "main-1", "search-1", "methods-1",
4017                     "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
4018
4019     let test = || {
4020         let actual: Vec<String> = input.iter().map(|s| derive_id(s.to_string())).collect();
4021         assert_eq!(&actual[..], expected);
4022     };
4023     test();
4024     reset_ids(true);
4025     test();
4026 }
4027
4028 #[cfg(test)]
4029 #[test]
4030 fn test_name_key() {
4031     assert_eq!(name_key("0"), ("", 0, 1));
4032     assert_eq!(name_key("123"), ("", 123, 0));
4033     assert_eq!(name_key("Fruit"), ("Fruit", 0, 0));
4034     assert_eq!(name_key("Fruit0"), ("Fruit", 0, 1));
4035     assert_eq!(name_key("Fruit0000"), ("Fruit", 0, 4));
4036     assert_eq!(name_key("Fruit01"), ("Fruit", 1, 1));
4037     assert_eq!(name_key("Fruit10"), ("Fruit", 10, 0));
4038     assert_eq!(name_key("Fruit123"), ("Fruit", 123, 0));
4039 }
4040
4041 #[cfg(test)]
4042 #[test]
4043 fn test_name_sorting() {
4044     let names = ["Apple",
4045                  "Banana",
4046                  "Fruit", "Fruit0", "Fruit00",
4047                  "Fruit1", "Fruit01",
4048                  "Fruit2", "Fruit02",
4049                  "Fruit20",
4050                  "Fruit100",
4051                  "Pear"];
4052     let mut sorted = names.to_owned();
4053     sorted.sort_by_key(|&s| name_key(s));
4054     assert_eq!(names, sorted);
4055 }