]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Rename `rustdoc::html::render::cache` to `search_index`
[rust.git] / src / librustdoc / json / mod.rs
1 //! Rustdoc's JSON backend
2 //!
3 //! This module contains the logic for rendering a crate as JSON rather than the normal static HTML
4 //! output. See [the RFC](https://github.com/rust-lang/rfcs/pull/2963) and the [`types`] module
5 //! docs for usage and details.
6
7 mod conversions;
8
9 use std::cell::RefCell;
10 use std::fs::File;
11 use std::path::PathBuf;
12 use std::rc::Rc;
13
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_hir::def_id::DefId;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::Session;
18
19 use rustdoc_json_types as types;
20
21 use crate::clean;
22 use crate::clean::ExternalCrate;
23 use crate::config::RenderOptions;
24 use crate::error::Error;
25 use crate::formats::cache::Cache;
26 use crate::formats::FormatRenderer;
27 use crate::html::render::search_index::ExternalLocation;
28 use crate::json::conversions::{from_item_id, IntoWithTcx};
29
30 #[derive(Clone)]
31 crate struct JsonRenderer<'tcx> {
32     tcx: TyCtxt<'tcx>,
33     /// A mapping of IDs that contains all local items for this crate which gets output as a top
34     /// level field of the JSON blob.
35     index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
36     /// The directory where the blob will be written to.
37     out_path: PathBuf,
38     cache: Rc<Cache>,
39 }
40
41 impl JsonRenderer<'tcx> {
42     fn sess(&self) -> &'tcx Session {
43         self.tcx.sess
44     }
45
46     fn get_trait_implementors(&mut self, id: DefId) -> Vec<types::Id> {
47         Rc::clone(&self.cache)
48             .implementors
49             .get(&id)
50             .map(|implementors| {
51                 implementors
52                     .iter()
53                     .map(|i| {
54                         let item = &i.impl_item;
55                         self.item(item.clone()).unwrap();
56                         from_item_id(item.def_id)
57                     })
58                     .collect()
59             })
60             .unwrap_or_default()
61     }
62
63     fn get_impls(&mut self, id: DefId) -> Vec<types::Id> {
64         Rc::clone(&self.cache)
65             .impls
66             .get(&id)
67             .map(|impls| {
68                 impls
69                     .iter()
70                     .filter_map(|i| {
71                         let item = &i.impl_item;
72
73                         // HACK(hkmatsumoto): For impls of primitive types, we index them
74                         // regardless of whether they're local. This is because users can
75                         // document primitive items in an arbitrary crate by using
76                         // `doc(primitive)`.
77                         let mut is_primitive_impl = false;
78                         if let clean::types::ItemKind::ImplItem(ref impl_) = *item.kind {
79                             if impl_.trait_.is_none() {
80                                 if let clean::types::Type::Primitive(_) = impl_.for_ {
81                                     is_primitive_impl = true;
82                                 }
83                             }
84                         }
85
86                         if item.def_id.is_local() || is_primitive_impl {
87                             self.item(item.clone()).unwrap();
88                             Some(from_item_id(item.def_id))
89                         } else {
90                             None
91                         }
92                     })
93                     .collect()
94             })
95             .unwrap_or_default()
96     }
97
98     fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
99         Rc::clone(&self.cache)
100             .traits
101             .iter()
102             .filter_map(|(&id, trait_item)| {
103                 // only need to synthesize items for external traits
104                 if !id.is_local() {
105                     let trait_item = &trait_item.trait_;
106                     trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
107                     Some((
108                         from_item_id(id.into()),
109                         types::Item {
110                             id: from_item_id(id.into()),
111                             crate_id: id.krate.as_u32(),
112                             name: self
113                                 .cache
114                                 .paths
115                                 .get(&id)
116                                 .unwrap_or_else(|| {
117                                     self.cache
118                                         .external_paths
119                                         .get(&id)
120                                         .expect("Trait should either be in local or external paths")
121                                 })
122                                 .0
123                                 .last()
124                                 .map(Clone::clone),
125                             visibility: types::Visibility::Public,
126                             inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)),
127                             span: None,
128                             docs: Default::default(),
129                             links: Default::default(),
130                             attrs: Default::default(),
131                             deprecation: Default::default(),
132                         },
133                     ))
134                 } else {
135                     None
136                 }
137             })
138             .collect()
139     }
140 }
141
142 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
143     fn descr() -> &'static str {
144         "json"
145     }
146
147     const RUN_ON_MODULE: bool = false;
148
149     fn init(
150         krate: clean::Crate,
151         options: RenderOptions,
152         cache: Cache,
153         tcx: TyCtxt<'tcx>,
154     ) -> Result<(Self, clean::Crate), Error> {
155         debug!("Initializing json renderer");
156         Ok((
157             JsonRenderer {
158                 tcx,
159                 index: Rc::new(RefCell::new(FxHashMap::default())),
160                 out_path: options.output,
161                 cache: Rc::new(cache),
162             },
163             krate,
164         ))
165     }
166
167     fn make_child_renderer(&self) -> Self {
168         self.clone()
169     }
170
171     /// Inserts an item into the index. This should be used rather than directly calling insert on
172     /// the hashmap because certain items (traits and types) need to have their mappings for trait
173     /// implementations filled out before they're inserted.
174     fn item(&mut self, item: clean::Item) -> Result<(), Error> {
175         // Flatten items that recursively store other items
176         item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
177
178         let id = item.def_id;
179         if let Some(mut new_item) = self.convert_item(item) {
180             if let types::ItemEnum::Trait(ref mut t) = new_item.inner {
181                 t.implementors = self.get_trait_implementors(id.expect_def_id())
182             } else if let types::ItemEnum::Struct(ref mut s) = new_item.inner {
183                 s.impls = self.get_impls(id.expect_def_id())
184             } else if let types::ItemEnum::Enum(ref mut e) = new_item.inner {
185                 e.impls = self.get_impls(id.expect_def_id())
186             } else if let types::ItemEnum::Union(ref mut u) = new_item.inner {
187                 u.impls = self.get_impls(id.expect_def_id())
188             }
189             let removed = self.index.borrow_mut().insert(from_item_id(id), new_item.clone());
190
191             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
192             // to make sure the items are unique. The main place this happens is when an item, is
193             // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod`
194             if let Some(old_item) = removed {
195                 assert_eq!(old_item, new_item);
196             }
197         }
198
199         Ok(())
200     }
201
202     fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> {
203         unreachable!("RUN_ON_MODULE = false should never call mod_item_in")
204     }
205
206     fn after_krate(&mut self) -> Result<(), Error> {
207         debug!("Done with crate");
208
209         for primitive in Rc::clone(&self.cache).primitive_locations.values() {
210             self.get_impls(*primitive);
211         }
212
213         let mut index = (*self.index).clone().into_inner();
214         index.extend(self.get_trait_items());
215         // This needs to be the default HashMap for compatibility with the public interface for
216         // rustdoc-json
217         #[allow(rustc::default_hash_types)]
218         let output = types::Crate {
219             root: types::Id(String::from("0:0")),
220             crate_version: self.cache.crate_version.clone(),
221             includes_private: self.cache.document_private,
222             index: index.into_iter().collect(),
223             paths: self
224                 .cache
225                 .paths
226                 .clone()
227                 .into_iter()
228                 .chain(self.cache.external_paths.clone().into_iter())
229                 .map(|(k, (path, kind))| {
230                     (
231                         from_item_id(k.into()),
232                         types::ItemSummary {
233                             crate_id: k.krate.as_u32(),
234                             path,
235                             kind: kind.into_tcx(self.tcx),
236                         },
237                     )
238                 })
239                 .collect(),
240             external_crates: self
241                 .cache
242                 .extern_locations
243                 .iter()
244                 .map(|(crate_num, external_location)| {
245                     let e = ExternalCrate { crate_num: *crate_num };
246                     (
247                         crate_num.as_u32(),
248                         types::ExternalCrate {
249                             name: e.name(self.tcx).to_string(),
250                             html_root_url: match external_location {
251                                 ExternalLocation::Remote(s) => Some(s.clone()),
252                                 _ => None,
253                             },
254                         },
255                     )
256                 })
257                 .collect(),
258             format_version: types::FORMAT_VERSION,
259         };
260         let mut p = self.out_path.clone();
261         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
262         p.set_extension("json");
263         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
264         serde_json::ser::to_writer(&file, &output).unwrap();
265         Ok(())
266     }
267
268     fn cache(&self) -> &Cache {
269         &self.cache
270     }
271 }