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