]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Auto merge of #79780 - camelid:use-summary_opts, r=GuillaumeGomez
[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             let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
155             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
156             // to make sure the items are unique.
157             if let Some(old_item) = removed {
158                 assert_eq!(old_item, new_item);
159             }
160         }
161
162         Ok(())
163     }
164
165     fn mod_item_in(
166         &mut self,
167         item: &clean::Item,
168         _module_name: &str,
169         cache: &Cache,
170     ) -> Result<(), Error> {
171         use clean::types::ItemKind::*;
172         if let ModuleItem(m) = &item.kind {
173             for item in &m.items {
174                 match &item.kind {
175                     // These don't have names so they don't get added to the output by default
176                     ImportItem(_) => self.item(item.clone(), cache).unwrap(),
177                     ExternCrateItem(_, _) => self.item(item.clone(), cache).unwrap(),
178                     ImplItem(i) => {
179                         i.items.iter().for_each(|i| self.item(i.clone(), cache).unwrap())
180                     }
181                     _ => {}
182                 }
183             }
184         }
185         self.item(item.clone(), cache).unwrap();
186         Ok(())
187     }
188
189     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
190         Ok(())
191     }
192
193     fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
194         debug!("Done with crate");
195         let mut index = (*self.index).clone().into_inner();
196         index.extend(self.get_trait_items(cache));
197         let output = types::Crate {
198             root: types::Id(String::from("0:0")),
199             crate_version: krate.version.clone(),
200             includes_private: cache.document_private,
201             index,
202             paths: cache
203                 .paths
204                 .clone()
205                 .into_iter()
206                 .chain(cache.external_paths.clone().into_iter())
207                 .map(|(k, (path, kind))| {
208                     (
209                         k.into(),
210                         types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
211                     )
212                 })
213                 .collect(),
214             external_crates: cache
215                 .extern_locations
216                 .iter()
217                 .map(|(k, v)| {
218                     (
219                         k.as_u32(),
220                         types::ExternalCrate {
221                             name: v.0.clone(),
222                             html_root_url: match &v.2 {
223                                 ExternalLocation::Remote(s) => Some(s.clone()),
224                                 _ => None,
225                             },
226                         },
227                     )
228                 })
229                 .collect(),
230             format_version: 1,
231         };
232         let mut p = self.out_path.clone();
233         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
234         p.set_extension("json");
235         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
236         serde_json::ser::to_writer(&file, &output).unwrap();
237         Ok(())
238     }
239
240     fn after_run(&mut self, _diag: &rustc_errors::Handler) -> Result<(), Error> {
241         Ok(())
242     }
243 }