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