]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/render/cache.rs
Rollup merge of #69993 - ayushmishra2005:doc/61137-add-long-error-code-e0693, r=Dylan-DPC
[rust.git] / src / librustdoc / html / render / cache.rs
1 use crate::clean::{self, AttributesExt, GetDefId};
2 use crate::fold::DocFolder;
3 use rustc::middle::privacy::AccessLevels;
4 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX};
6 use rustc_span::source_map::FileName;
7 use rustc_span::symbol::sym;
8 use std::collections::BTreeMap;
9 use std::mem;
10 use std::path::{Path, PathBuf};
11
12 use serde::Serialize;
13
14 use super::{plain_summary_line, shorten, Impl, IndexItem, IndexItemFunctionType, ItemType};
15 use super::{RenderInfo, Type};
16
17 /// Indicates where an external crate can be found.
18 pub enum ExternalLocation {
19     /// Remote URL root of the external crate
20     Remote(String),
21     /// This external crate can be found in the local doc/ folder
22     Local,
23     /// The external crate could not be found.
24     Unknown,
25 }
26
27 /// This cache is used to store information about the `clean::Crate` being
28 /// rendered in order to provide more useful documentation. This contains
29 /// information like all implementors of a trait, all traits a type implements,
30 /// documentation for all known traits, etc.
31 ///
32 /// This structure purposefully does not implement `Clone` because it's intended
33 /// to be a fairly large and expensive structure to clone. Instead this adheres
34 /// to `Send` so it may be stored in a `Arc` instance and shared among the various
35 /// rendering threads.
36 #[derive(Default)]
37 crate struct Cache {
38     /// Maps a type ID to all known implementations for that type. This is only
39     /// recognized for intra-crate `ResolvedPath` types, and is used to print
40     /// out extra documentation on the page of an enum/struct.
41     ///
42     /// The values of the map are a list of implementations and documentation
43     /// found on that implementation.
44     pub impls: FxHashMap<DefId, Vec<Impl>>,
45
46     /// Maintains a mapping of local crate `DefId`s to the fully qualified name
47     /// and "short type description" of that node. This is used when generating
48     /// URLs when a type is being linked to. External paths are not located in
49     /// this map because the `External` type itself has all the information
50     /// necessary.
51     pub paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
52
53     /// Similar to `paths`, but only holds external paths. This is only used for
54     /// generating explicit hyperlinks to other crates.
55     pub external_paths: FxHashMap<DefId, (Vec<String>, ItemType)>,
56
57     /// Maps local `DefId`s of exported types to fully qualified paths.
58     /// Unlike 'paths', this mapping ignores any renames that occur
59     /// due to 'use' statements.
60     ///
61     /// This map is used when writing out the special 'implementors'
62     /// javascript file. By using the exact path that the type
63     /// is declared with, we ensure that each path will be identical
64     /// to the path used if the corresponding type is inlined. By
65     /// doing this, we can detect duplicate impls on a trait page, and only display
66     /// the impl for the inlined type.
67     pub exact_paths: FxHashMap<DefId, Vec<String>>,
68
69     /// This map contains information about all known traits of this crate.
70     /// Implementations of a crate should inherit the documentation of the
71     /// parent trait if no extra documentation is specified, and default methods
72     /// should show up in documentation about trait implementations.
73     pub traits: FxHashMap<DefId, clean::Trait>,
74
75     /// When rendering traits, it's often useful to be able to list all
76     /// implementors of the trait, and this mapping is exactly, that: a mapping
77     /// of trait ids to the list of known implementors of the trait
78     pub implementors: FxHashMap<DefId, Vec<Impl>>,
79
80     /// Cache of where external crate documentation can be found.
81     pub extern_locations: FxHashMap<CrateNum, (String, PathBuf, ExternalLocation)>,
82
83     /// Cache of where documentation for primitives can be found.
84     pub primitive_locations: FxHashMap<clean::PrimitiveType, DefId>,
85
86     // Note that external items for which `doc(hidden)` applies to are shown as
87     // non-reachable while local items aren't. This is because we're reusing
88     // the access levels from the privacy check pass.
89     pub access_levels: AccessLevels<DefId>,
90
91     /// The version of the crate being documented, if given from the `--crate-version` flag.
92     pub crate_version: Option<String>,
93
94     // Private fields only used when initially crawling a crate to build a cache
95     stack: Vec<String>,
96     parent_stack: Vec<DefId>,
97     parent_is_trait_impl: bool,
98     search_index: Vec<IndexItem>,
99     stripped_mod: bool,
100     pub deref_trait_did: Option<DefId>,
101     pub deref_mut_trait_did: Option<DefId>,
102     pub owned_box_did: Option<DefId>,
103     masked_crates: FxHashSet<CrateNum>,
104
105     // In rare case where a structure is defined in one module but implemented
106     // in another, if the implementing module is parsed before defining module,
107     // then the fully qualified name of the structure isn't presented in `paths`
108     // yet when its implementation methods are being indexed. Caches such methods
109     // and their parent id here and indexes them at the end of crate parsing.
110     orphan_impl_items: Vec<(DefId, clean::Item)>,
111
112     // Similarly to `orphan_impl_items`, sometimes trait impls are picked up
113     // even though the trait itself is not exported. This can happen if a trait
114     // was defined in function/expression scope, since the impl will be picked
115     // up by `collect-trait-impls` but the trait won't be scraped out in the HIR
116     // crawl. In order to prevent crashes when looking for spotlight traits or
117     // when gathering trait documentation on a type, hold impls here while
118     // folding and add them to the cache later on if we find the trait.
119     orphan_trait_impls: Vec<(DefId, FxHashSet<DefId>, Impl)>,
120
121     /// Aliases added through `#[doc(alias = "...")]`. Since a few items can have the same alias,
122     /// we need the alias element to have an array of items.
123     pub(super) aliases: FxHashMap<String, Vec<IndexItem>>,
124 }
125
126 impl Cache {
127     pub fn from_krate(
128         renderinfo: RenderInfo,
129         extern_html_root_urls: &BTreeMap<String, String>,
130         dst: &Path,
131         mut krate: clean::Crate,
132     ) -> (clean::Crate, String, Cache) {
133         // Crawl the crate to build various caches used for the output
134         let RenderInfo {
135             inlined: _,
136             external_paths,
137             exact_paths,
138             access_levels,
139             deref_trait_did,
140             deref_mut_trait_did,
141             owned_box_did,
142             ..
143         } = renderinfo;
144
145         let external_paths =
146             external_paths.into_iter().map(|(k, (v, t))| (k, (v, ItemType::from(t)))).collect();
147
148         let mut cache = Cache {
149             impls: Default::default(),
150             external_paths,
151             exact_paths,
152             paths: Default::default(),
153             implementors: Default::default(),
154             stack: Vec::new(),
155             parent_stack: Vec::new(),
156             search_index: Vec::new(),
157             parent_is_trait_impl: false,
158             extern_locations: Default::default(),
159             primitive_locations: Default::default(),
160             stripped_mod: false,
161             access_levels,
162             crate_version: krate.version.take(),
163             orphan_impl_items: Vec::new(),
164             orphan_trait_impls: Vec::new(),
165             traits: krate.external_traits.replace(Default::default()),
166             deref_trait_did,
167             deref_mut_trait_did,
168             owned_box_did,
169             masked_crates: mem::take(&mut krate.masked_crates),
170             aliases: Default::default(),
171         };
172
173         // Cache where all our extern crates are located
174         for &(n, ref e) in &krate.externs {
175             let src_root = match e.src {
176                 FileName::Real(ref p) => match p.parent() {
177                     Some(p) => p.to_path_buf(),
178                     None => PathBuf::new(),
179                 },
180                 _ => PathBuf::new(),
181             };
182             let extern_url = extern_html_root_urls.get(&e.name).map(|u| &**u);
183             cache
184                 .extern_locations
185                 .insert(n, (e.name.clone(), src_root, extern_location(e, extern_url, &dst)));
186
187             let did = DefId { krate: n, index: CRATE_DEF_INDEX };
188             cache.external_paths.insert(did, (vec![e.name.to_string()], ItemType::Module));
189         }
190
191         // Cache where all known primitives have their documentation located.
192         //
193         // Favor linking to as local extern as possible, so iterate all crates in
194         // reverse topological order.
195         for &(_, ref e) in krate.externs.iter().rev() {
196             for &(def_id, prim, _) in &e.primitives {
197                 cache.primitive_locations.insert(prim, def_id);
198             }
199         }
200         for &(def_id, prim, _) in &krate.primitives {
201             cache.primitive_locations.insert(prim, def_id);
202         }
203
204         cache.stack.push(krate.name.clone());
205         krate = cache.fold_crate(krate);
206
207         for (trait_did, dids, impl_) in cache.orphan_trait_impls.drain(..) {
208             if cache.traits.contains_key(&trait_did) {
209                 for did in dids {
210                     cache.impls.entry(did).or_insert(vec![]).push(impl_.clone());
211                 }
212             }
213         }
214
215         // Build our search index
216         let index = build_index(&krate, &mut cache);
217
218         (krate, index, cache)
219     }
220 }
221
222 impl DocFolder for Cache {
223     fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
224         if item.def_id.is_local() {
225             debug!("folding {} \"{:?}\", id {:?}", item.type_(), item.name, item.def_id);
226         }
227
228         // If this is a stripped module,
229         // we don't want it or its children in the search index.
230         let orig_stripped_mod = match item.inner {
231             clean::StrippedItem(box clean::ModuleItem(..)) => {
232                 mem::replace(&mut self.stripped_mod, true)
233             }
234             _ => self.stripped_mod,
235         };
236
237         // If the impl is from a masked crate or references something from a
238         // masked crate then remove it completely.
239         if let clean::ImplItem(ref i) = item.inner {
240             if self.masked_crates.contains(&item.def_id.krate)
241                 || i.trait_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
242                 || i.for_.def_id().map_or(false, |d| self.masked_crates.contains(&d.krate))
243             {
244                 return None;
245             }
246         }
247
248         // Propagate a trait method's documentation to all implementors of the
249         // trait.
250         if let clean::TraitItem(ref t) = item.inner {
251             self.traits.entry(item.def_id).or_insert_with(|| t.clone());
252         }
253
254         // Collect all the implementors of traits.
255         if let clean::ImplItem(ref i) = item.inner {
256             if let Some(did) = i.trait_.def_id() {
257                 if i.blanket_impl.is_none() {
258                     self.implementors
259                         .entry(did)
260                         .or_default()
261                         .push(Impl { impl_item: item.clone() });
262                 }
263             }
264         }
265
266         // Index this method for searching later on.
267         if let Some(ref s) = item.name {
268             let (parent, is_inherent_impl_item) = match item.inner {
269                 clean::StrippedItem(..) => ((None, None), false),
270                 clean::AssocConstItem(..) | clean::TypedefItem(_, true)
271                     if self.parent_is_trait_impl =>
272                 {
273                     // skip associated items in trait impls
274                     ((None, None), false)
275                 }
276                 clean::AssocTypeItem(..)
277                 | clean::TyMethodItem(..)
278                 | clean::StructFieldItem(..)
279                 | clean::VariantItem(..) => (
280                     (
281                         Some(*self.parent_stack.last().expect("parent_stack is empty")),
282                         Some(&self.stack[..self.stack.len() - 1]),
283                     ),
284                     false,
285                 ),
286                 clean::MethodItem(..) | clean::AssocConstItem(..) => {
287                     if self.parent_stack.is_empty() {
288                         ((None, None), false)
289                     } else {
290                         let last = self.parent_stack.last().expect("parent_stack is empty 2");
291                         let did = *last;
292                         let path = match self.paths.get(&did) {
293                             // The current stack not necessarily has correlation
294                             // for where the type was defined. On the other
295                             // hand, `paths` always has the right
296                             // information if present.
297                             Some(&(ref fqp, ItemType::Trait))
298                             | Some(&(ref fqp, ItemType::Struct))
299                             | Some(&(ref fqp, ItemType::Union))
300                             | Some(&(ref fqp, ItemType::Enum)) => Some(&fqp[..fqp.len() - 1]),
301                             Some(..) => Some(&*self.stack),
302                             None => None,
303                         };
304                         ((Some(*last), path), true)
305                     }
306                 }
307                 _ => ((None, Some(&*self.stack)), false),
308             };
309
310             match parent {
311                 (parent, Some(path)) if is_inherent_impl_item || (!self.stripped_mod) => {
312                     debug_assert!(!item.is_stripped());
313
314                     // A crate has a module at its root, containing all items,
315                     // which should not be indexed. The crate-item itself is
316                     // inserted later on when serializing the search-index.
317                     if item.def_id.index != CRATE_DEF_INDEX {
318                         self.search_index.push(IndexItem {
319                             ty: item.type_(),
320                             name: s.to_string(),
321                             path: path.join("::"),
322                             desc: shorten(plain_summary_line(item.doc_value())),
323                             parent,
324                             parent_idx: None,
325                             search_type: get_index_search_type(&item),
326                         });
327                     }
328                 }
329                 (Some(parent), None) if is_inherent_impl_item => {
330                     // We have a parent, but we don't know where they're
331                     // defined yet. Wait for later to index this item.
332                     self.orphan_impl_items.push((parent, item.clone()));
333                 }
334                 _ => {}
335             }
336         }
337
338         // Keep track of the fully qualified path for this item.
339         let pushed = match item.name {
340             Some(ref n) if !n.is_empty() => {
341                 self.stack.push(n.to_string());
342                 true
343             }
344             _ => false,
345         };
346
347         match item.inner {
348             clean::StructItem(..)
349             | clean::EnumItem(..)
350             | clean::TypedefItem(..)
351             | clean::TraitItem(..)
352             | clean::FunctionItem(..)
353             | clean::ModuleItem(..)
354             | clean::ForeignFunctionItem(..)
355             | clean::ForeignStaticItem(..)
356             | clean::ConstantItem(..)
357             | clean::StaticItem(..)
358             | clean::UnionItem(..)
359             | clean::ForeignTypeItem
360             | clean::MacroItem(..)
361             | clean::ProcMacroItem(..)
362             | clean::VariantItem(..)
363                 if !self.stripped_mod =>
364             {
365                 // Re-exported items mean that the same id can show up twice
366                 // in the rustdoc ast that we're looking at. We know,
367                 // however, that a re-exported item doesn't show up in the
368                 // `public_items` map, so we can skip inserting into the
369                 // paths map if there was already an entry present and we're
370                 // not a public item.
371                 if !self.paths.contains_key(&item.def_id)
372                     || self.access_levels.is_public(item.def_id)
373                 {
374                     self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
375                 }
376                 self.add_aliases(&item);
377             }
378
379             clean::PrimitiveItem(..) => {
380                 self.add_aliases(&item);
381                 self.paths.insert(item.def_id, (self.stack.clone(), item.type_()));
382             }
383
384             _ => {}
385         }
386
387         // Maintain the parent stack
388         let orig_parent_is_trait_impl = self.parent_is_trait_impl;
389         let parent_pushed = match item.inner {
390             clean::TraitItem(..)
391             | clean::EnumItem(..)
392             | clean::ForeignTypeItem
393             | clean::StructItem(..)
394             | clean::UnionItem(..)
395             | clean::VariantItem(..) => {
396                 self.parent_stack.push(item.def_id);
397                 self.parent_is_trait_impl = false;
398                 true
399             }
400             clean::ImplItem(ref i) => {
401                 self.parent_is_trait_impl = i.trait_.is_some();
402                 match i.for_ {
403                     clean::ResolvedPath { did, .. } => {
404                         self.parent_stack.push(did);
405                         true
406                     }
407                     ref t => {
408                         let prim_did = t
409                             .primitive_type()
410                             .and_then(|t| self.primitive_locations.get(&t).cloned());
411                         match prim_did {
412                             Some(did) => {
413                                 self.parent_stack.push(did);
414                                 true
415                             }
416                             None => false,
417                         }
418                     }
419                 }
420             }
421             _ => false,
422         };
423
424         // Once we've recursively found all the generics, hoard off all the
425         // implementations elsewhere.
426         let ret = self.fold_item_recur(item).and_then(|item| {
427             if let clean::Item { inner: clean::ImplItem(_), .. } = item {
428                 // Figure out the id of this impl. This may map to a
429                 // primitive rather than always to a struct/enum.
430                 // Note: matching twice to restrict the lifetime of the `i` borrow.
431                 let mut dids = FxHashSet::default();
432                 if let clean::Item { inner: clean::ImplItem(ref i), .. } = item {
433                     match i.for_ {
434                         clean::ResolvedPath { did, .. }
435                         | clean::BorrowedRef {
436                             type_: box clean::ResolvedPath { did, .. }, ..
437                         } => {
438                             dids.insert(did);
439                         }
440                         ref t => {
441                             let did = t
442                                 .primitive_type()
443                                 .and_then(|t| self.primitive_locations.get(&t).cloned());
444
445                             if let Some(did) = did {
446                                 dids.insert(did);
447                             }
448                         }
449                     }
450
451                     if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
452                         for bound in generics {
453                             if let Some(did) = bound.def_id() {
454                                 dids.insert(did);
455                             }
456                         }
457                     }
458                 } else {
459                     unreachable!()
460                 };
461                 let impl_item = Impl { impl_item: item };
462                 if impl_item.trait_did().map_or(true, |d| self.traits.contains_key(&d)) {
463                     for did in dids {
464                         self.impls.entry(did).or_insert(vec![]).push(impl_item.clone());
465                     }
466                 } else {
467                     let trait_did = impl_item.trait_did().expect("no trait did");
468                     self.orphan_trait_impls.push((trait_did, dids, impl_item));
469                 }
470                 None
471             } else {
472                 Some(item)
473             }
474         });
475
476         if pushed {
477             self.stack.pop().expect("stack already empty");
478         }
479         if parent_pushed {
480             self.parent_stack.pop().expect("parent stack already empty");
481         }
482         self.stripped_mod = orig_stripped_mod;
483         self.parent_is_trait_impl = orig_parent_is_trait_impl;
484         ret
485     }
486 }
487
488 impl Cache {
489     fn add_aliases(&mut self, item: &clean::Item) {
490         if item.def_id.index == CRATE_DEF_INDEX {
491             return;
492         }
493         if let Some(ref item_name) = item.name {
494             let path = self
495                 .paths
496                 .get(&item.def_id)
497                 .map(|p| p.0[..p.0.len() - 1].join("::"))
498                 .unwrap_or("std".to_owned());
499             for alias in item
500                 .attrs
501                 .lists(sym::doc)
502                 .filter(|a| a.check_name(sym::alias))
503                 .filter_map(|a| a.value_str().map(|s| s.to_string().replace("\"", "")))
504                 .filter(|v| !v.is_empty())
505                 .collect::<FxHashSet<_>>()
506                 .into_iter()
507             {
508                 self.aliases.entry(alias).or_insert(Vec::with_capacity(1)).push(IndexItem {
509                     ty: item.type_(),
510                     name: item_name.to_string(),
511                     path: path.clone(),
512                     desc: shorten(plain_summary_line(item.doc_value())),
513                     parent: None,
514                     parent_idx: None,
515                     search_type: get_index_search_type(&item),
516                 });
517             }
518         }
519     }
520 }
521
522 /// Attempts to find where an external crate is located, given that we're
523 /// rendering in to the specified source destination.
524 fn extern_location(
525     e: &clean::ExternalCrate,
526     extern_url: Option<&str>,
527     dst: &Path,
528 ) -> ExternalLocation {
529     use ExternalLocation::*;
530     // See if there's documentation generated into the local directory
531     let local_location = dst.join(&e.name);
532     if local_location.is_dir() {
533         return Local;
534     }
535
536     if let Some(url) = extern_url {
537         let mut url = url.to_string();
538         if !url.ends_with('/') {
539             url.push('/');
540         }
541         return Remote(url);
542     }
543
544     // Failing that, see if there's an attribute specifying where to find this
545     // external crate
546     e.attrs
547         .lists(sym::doc)
548         .filter(|a| a.check_name(sym::html_root_url))
549         .filter_map(|a| a.value_str())
550         .map(|url| {
551             let mut url = url.to_string();
552             if !url.ends_with('/') {
553                 url.push('/')
554             }
555             Remote(url)
556         })
557         .next()
558         .unwrap_or(Unknown) // Well, at least we tried.
559 }
560
561 /// Builds the search index from the collected metadata
562 fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
563     let mut defid_to_pathid = FxHashMap::default();
564     let mut crate_items = Vec::with_capacity(cache.search_index.len());
565     let mut crate_paths = vec![];
566
567     let Cache { ref mut search_index, ref orphan_impl_items, ref paths, .. } = *cache;
568
569     // Attach all orphan items to the type's definition if the type
570     // has since been learned.
571     for &(did, ref item) in orphan_impl_items {
572         if let Some(&(ref fqp, _)) = paths.get(&did) {
573             search_index.push(IndexItem {
574                 ty: item.type_(),
575                 name: item.name.clone().unwrap(),
576                 path: fqp[..fqp.len() - 1].join("::"),
577                 desc: shorten(plain_summary_line(item.doc_value())),
578                 parent: Some(did),
579                 parent_idx: None,
580                 search_type: get_index_search_type(&item),
581             });
582         }
583     }
584
585     // Reduce `DefId` in paths into smaller sequential numbers,
586     // and prune the paths that do not appear in the index.
587     let mut lastpath = String::new();
588     let mut lastpathid = 0usize;
589
590     for item in search_index {
591         item.parent_idx = item.parent.map(|defid| {
592             if defid_to_pathid.contains_key(&defid) {
593                 *defid_to_pathid.get(&defid).expect("no pathid")
594             } else {
595                 let pathid = lastpathid;
596                 defid_to_pathid.insert(defid, pathid);
597                 lastpathid += 1;
598
599                 let &(ref fqp, short) = paths.get(&defid).unwrap();
600                 crate_paths.push((short, fqp.last().unwrap().clone()));
601                 pathid
602             }
603         });
604
605         // Omit the parent path if it is same to that of the prior item.
606         if lastpath == item.path {
607             item.path.clear();
608         } else {
609             lastpath = item.path.clone();
610         }
611         crate_items.push(&*item);
612     }
613
614     let crate_doc = krate
615         .module
616         .as_ref()
617         .map(|module| shorten(plain_summary_line(module.doc_value())))
618         .unwrap_or(String::new());
619
620     #[derive(Serialize)]
621     struct CrateData<'a> {
622         doc: String,
623         #[serde(rename = "i")]
624         items: Vec<&'a IndexItem>,
625         #[serde(rename = "p")]
626         paths: Vec<(ItemType, String)>,
627     }
628
629     // Collect the index into a string
630     format!(
631         r#"searchIndex["{}"] = {};"#,
632         krate.name,
633         serde_json::to_string(&CrateData {
634             doc: crate_doc,
635             items: crate_items,
636             paths: crate_paths,
637         })
638         .expect("failed serde conversion")
639     )
640 }
641
642 fn get_index_search_type(item: &clean::Item) -> Option<IndexItemFunctionType> {
643     let (all_types, ret_types) = match item.inner {
644         clean::FunctionItem(ref f) => (&f.all_types, &f.ret_types),
645         clean::MethodItem(ref m) => (&m.all_types, &m.ret_types),
646         clean::TyMethodItem(ref m) => (&m.all_types, &m.ret_types),
647         _ => return None,
648     };
649
650     let inputs =
651         all_types.iter().map(|arg| get_index_type(&arg)).filter(|a| a.name.is_some()).collect();
652     let output = ret_types
653         .iter()
654         .map(|arg| get_index_type(&arg))
655         .filter(|a| a.name.is_some())
656         .collect::<Vec<_>>();
657     let output = if output.is_empty() { None } else { Some(output) };
658
659     Some(IndexItemFunctionType { inputs, output })
660 }
661
662 fn get_index_type(clean_type: &clean::Type) -> Type {
663     let t = Type {
664         name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()),
665         generics: get_generics(clean_type),
666     };
667     t
668 }
669
670 fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option<String> {
671     match *clean_type {
672         clean::ResolvedPath { ref path, .. } => {
673             let segments = &path.segments;
674             let path_segment = segments.iter().last().unwrap_or_else(|| panic!(
675                 "get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
676                 clean_type, accept_generic
677             ));
678             Some(path_segment.name.clone())
679         }
680         clean::Generic(ref s) if accept_generic => Some(s.clone()),
681         clean::Primitive(ref p) => Some(format!("{:?}", p)),
682         clean::BorrowedRef { ref type_, .. } => get_index_type_name(type_, accept_generic),
683         // FIXME: add all from clean::Type.
684         _ => None,
685     }
686 }
687
688 fn get_generics(clean_type: &clean::Type) -> Option<Vec<String>> {
689     clean_type.generics().and_then(|types| {
690         let r = types
691             .iter()
692             .filter_map(|t| get_index_type_name(t, false))
693             .map(|s| s.to_ascii_lowercase())
694             .collect::<Vec<_>>();
695         if r.is_empty() { None } else { Some(r) }
696     })
697 }