]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Auto merge of #81250 - sivadeilra:remove_xp_compat, r=joshtriplett,m-ou-se
[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 }
36
37 impl JsonRenderer<'_> {
38     fn sess(&self) -> &Session {
39         self.tcx.sess
40     }
41
42     fn get_trait_implementors(
43         &mut self,
44         id: rustc_span::def_id::DefId,
45         cache: &Cache,
46     ) -> Vec<types::Id> {
47         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(), cache).unwrap();
56                         item.def_id.into()
57                     })
58                     .collect()
59             })
60             .unwrap_or_default()
61     }
62
63     fn get_impls(&mut self, id: rustc_span::def_id::DefId, cache: &Cache) -> Vec<types::Id> {
64         cache
65             .impls
66             .get(&id)
67             .map(|impls| {
68                 impls
69                     .iter()
70                     .filter_map(|i| {
71                         let item = &i.impl_item;
72                         if item.def_id.is_local() {
73                             self.item(item.clone(), cache).unwrap();
74                             Some(item.def_id.into())
75                         } else {
76                             None
77                         }
78                     })
79                     .collect()
80             })
81             .unwrap_or_default()
82     }
83
84     fn get_trait_items(&mut self, cache: &Cache) -> Vec<(types::Id, types::Item)> {
85         cache
86             .traits
87             .iter()
88             .filter_map(|(&id, trait_item)| {
89                 // only need to synthesize items for external traits
90                 if !id.is_local() {
91                     trait_item.items.clone().into_iter().for_each(|i| self.item(i, cache).unwrap());
92                     Some((
93                         id.into(),
94                         types::Item {
95                             id: id.into(),
96                             crate_id: id.krate.as_u32(),
97                             name: cache
98                                 .paths
99                                 .get(&id)
100                                 .unwrap_or_else(|| {
101                                     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: &mut 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             },
147             krate,
148         ))
149     }
150
151     /// Inserts an item into the index. This should be used rather than directly calling insert on
152     /// the hashmap because certain items (traits and types) need to have their mappings for trait
153     /// implementations filled out before they're inserted.
154     fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
155         // Flatten items that recursively store other items
156         item.kind.inner_items().for_each(|i| self.item(i.clone(), cache).unwrap());
157
158         let id = item.def_id;
159         if let Some(mut new_item) = self.convert_item(item) {
160             if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
161                 t.implementors = self.get_trait_implementors(id, cache)
162             } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
163                 s.impls = self.get_impls(id, cache)
164             } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
165                 e.impls = self.get_impls(id, cache)
166             }
167             let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
168             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
169             // to make sure the items are unique.
170             if let Some(old_item) = removed {
171                 assert_eq!(old_item, new_item);
172             }
173         }
174
175         Ok(())
176     }
177
178     fn mod_item_in(
179         &mut self,
180         item: &clean::Item,
181         _module_name: &str,
182         cache: &Cache,
183     ) -> Result<(), Error> {
184         use clean::types::ItemKind::*;
185         if let ModuleItem(m) = &*item.kind {
186             for item in &m.items {
187                 match &*item.kind {
188                     // These don't have names so they don't get added to the output by default
189                     ImportItem(_) => self.item(item.clone(), cache).unwrap(),
190                     ExternCrateItem(_, _) => self.item(item.clone(), cache).unwrap(),
191                     ImplItem(i) => {
192                         i.items.iter().for_each(|i| self.item(i.clone(), cache).unwrap())
193                     }
194                     _ => {}
195                 }
196             }
197         }
198         self.item(item.clone(), cache).unwrap();
199         Ok(())
200     }
201
202     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
203         Ok(())
204     }
205
206     fn after_krate(
207         &mut self,
208         krate: &clean::Crate,
209         cache: &Cache,
210         _diag: &rustc_errors::Handler,
211     ) -> Result<(), Error> {
212         debug!("Done with crate");
213         let mut index = (*self.index).clone().into_inner();
214         index.extend(self.get_trait_items(cache));
215         let output = types::Crate {
216             root: types::Id(String::from("0:0")),
217             crate_version: krate.version.clone(),
218             includes_private: cache.document_private,
219             index,
220             paths: cache
221                 .paths
222                 .clone()
223                 .into_iter()
224                 .chain(cache.external_paths.clone().into_iter())
225                 .map(|(k, (path, kind))| {
226                     (
227                         k.into(),
228                         types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
229                     )
230                 })
231                 .collect(),
232             external_crates: cache
233                 .extern_locations
234                 .iter()
235                 .map(|(k, v)| {
236                     (
237                         k.as_u32(),
238                         types::ExternalCrate {
239                             name: v.0.to_string(),
240                             html_root_url: match &v.2 {
241                                 ExternalLocation::Remote(s) => Some(s.clone()),
242                                 _ => None,
243                             },
244                         },
245                     )
246                 })
247                 .collect(),
248             format_version: 2,
249         };
250         let mut p = self.out_path.clone();
251         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
252         p.set_extension("json");
253         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
254         serde_json::ser::to_writer(&file, &output).unwrap();
255         Ok(())
256     }
257 }