]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Auto merge of #80987 - GuillaumeGomez:remove-cache-key, r=jyn514
[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 pub mod types;
9
10 use std::cell::RefCell;
11 use std::fs::File;
12 use std::path::PathBuf;
13 use std::rc::Rc;
14
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::Session;
18 use rustc_span::edition::Edition;
19
20 use crate::clean;
21 use crate::config::{RenderInfo, RenderOptions};
22 use crate::error::Error;
23 use crate::formats::cache::Cache;
24 use crate::formats::FormatRenderer;
25 use crate::html::render::cache::ExternalLocation;
26
27 #[derive(Clone)]
28 crate struct JsonRenderer<'tcx> {
29     tcx: TyCtxt<'tcx>,
30     /// A mapping of IDs that contains all local items for this crate which gets output as a top
31     /// level field of the JSON blob.
32     index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
33     /// The directory where the blob will be written to.
34     out_path: PathBuf,
35     cache: Rc<Cache>,
36 }
37
38 impl JsonRenderer<'_> {
39     fn sess(&self) -> &Session {
40         self.tcx.sess
41     }
42
43     fn get_trait_implementors(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
44         Rc::clone(&self.cache)
45             .implementors
46             .get(&id)
47             .map(|implementors| {
48                 implementors
49                     .iter()
50                     .map(|i| {
51                         let item = &i.impl_item;
52                         self.item(item.clone()).unwrap();
53                         item.def_id.into()
54                     })
55                     .collect()
56             })
57             .unwrap_or_default()
58     }
59
60     fn get_impls(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
61         Rc::clone(&self.cache)
62             .impls
63             .get(&id)
64             .map(|impls| {
65                 impls
66                     .iter()
67                     .filter_map(|i| {
68                         let item = &i.impl_item;
69                         if item.def_id.is_local() {
70                             self.item(item.clone()).unwrap();
71                             Some(item.def_id.into())
72                         } else {
73                             None
74                         }
75                     })
76                     .collect()
77             })
78             .unwrap_or_default()
79     }
80
81     fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
82         Rc::clone(&self.cache)
83             .traits
84             .iter()
85             .filter_map(|(&id, trait_item)| {
86                 // only need to synthesize items for external traits
87                 if !id.is_local() {
88                     trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
89                     Some((
90                         id.into(),
91                         types::Item {
92                             id: id.into(),
93                             crate_id: id.krate.as_u32(),
94                             name: self
95                                 .cache
96                                 .paths
97                                 .get(&id)
98                                 .unwrap_or_else(|| {
99                                     self.cache
100                                         .external_paths
101                                         .get(&id)
102                                         .expect("Trait should either be in local or external paths")
103                                 })
104                                 .0
105                                 .last()
106                                 .map(Clone::clone),
107                             visibility: types::Visibility::Public,
108                             kind: types::ItemKind::Trait,
109                             inner: types::ItemEnum::TraitItem(trait_item.clone().into()),
110                             source: None,
111                             docs: Default::default(),
112                             links: Default::default(),
113                             attrs: Default::default(),
114                             deprecation: Default::default(),
115                         },
116                     ))
117                 } else {
118                     None
119                 }
120             })
121             .collect()
122     }
123 }
124
125 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
126     fn descr() -> &'static str {
127         "json"
128     }
129
130     fn init(
131         krate: clean::Crate,
132         options: RenderOptions,
133         _render_info: RenderInfo,
134         _edition: Edition,
135         cache: Cache,
136         tcx: TyCtxt<'tcx>,
137     ) -> Result<(Self, clean::Crate), Error> {
138         debug!("Initializing json renderer");
139         Ok((
140             JsonRenderer {
141                 tcx,
142                 index: Rc::new(RefCell::new(FxHashMap::default())),
143                 out_path: options.output,
144                 cache: Rc::new(cache),
145             },
146             krate,
147         ))
148     }
149
150     /// Inserts an item into the index. This should be used rather than directly calling insert on
151     /// the hashmap because certain items (traits and types) need to have their mappings for trait
152     /// implementations filled out before they're inserted.
153     fn item(&mut self, item: clean::Item) -> Result<(), Error> {
154         // Flatten items that recursively store other items
155         item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
156
157         let id = item.def_id;
158         if let Some(mut new_item) = self.convert_item(item) {
159             if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
160                 t.implementors = self.get_trait_implementors(id)
161             } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
162                 s.impls = self.get_impls(id)
163             } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
164                 e.impls = self.get_impls(id)
165             }
166             let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
167             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
168             // to make sure the items are unique.
169             if let Some(old_item) = removed {
170                 assert_eq!(old_item, new_item);
171             }
172         }
173
174         Ok(())
175     }
176
177     fn mod_item_in(&mut self, item: &clean::Item, _module_name: &str) -> Result<(), Error> {
178         use clean::types::ItemKind::*;
179         if let ModuleItem(m) = &*item.kind {
180             for item in &m.items {
181                 match &*item.kind {
182                     // These don't have names so they don't get added to the output by default
183                     ImportItem(_) => self.item(item.clone()).unwrap(),
184                     ExternCrateItem(_, _) => self.item(item.clone()).unwrap(),
185                     ImplItem(i) => i.items.iter().for_each(|i| self.item(i.clone()).unwrap()),
186                     _ => {}
187                 }
188             }
189         }
190         self.item(item.clone()).unwrap();
191         Ok(())
192     }
193
194     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
195         Ok(())
196     }
197
198     fn after_krate(
199         &mut self,
200         krate: &clean::Crate,
201         _diag: &rustc_errors::Handler,
202     ) -> Result<(), Error> {
203         debug!("Done with crate");
204         let mut index = (*self.index).clone().into_inner();
205         index.extend(self.get_trait_items());
206         let output = types::Crate {
207             root: types::Id(String::from("0:0")),
208             crate_version: krate.version.clone(),
209             includes_private: self.cache.document_private,
210             index,
211             paths: self
212                 .cache
213                 .paths
214                 .clone()
215                 .into_iter()
216                 .chain(self.cache.external_paths.clone().into_iter())
217                 .map(|(k, (path, kind))| {
218                     (
219                         k.into(),
220                         types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
221                     )
222                 })
223                 .collect(),
224             external_crates: self
225                 .cache
226                 .extern_locations
227                 .iter()
228                 .map(|(k, v)| {
229                     (
230                         k.as_u32(),
231                         types::ExternalCrate {
232                             name: v.0.to_string(),
233                             html_root_url: match &v.2 {
234                                 ExternalLocation::Remote(s) => Some(s.clone()),
235                                 _ => None,
236                             },
237                         },
238                     )
239                 })
240                 .collect(),
241             format_version: 2,
242         };
243         let mut p = self.out_path.clone();
244         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
245         p.set_extension("json");
246         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
247         serde_json::ser::to_writer(&file, &output).unwrap();
248         Ok(())
249     }
250
251     fn cache(&self) -> &Cache {
252         &self.cache
253     }
254 }