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