]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Rollup merge of #81173 - lukaslueg:intersperse_docs, r=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 init(
129         krate: clean::Crate,
130         options: RenderOptions,
131         _render_info: RenderInfo,
132         _edition: Edition,
133         _cache: &mut Cache,
134         tcx: TyCtxt<'tcx>,
135     ) -> Result<(Self, clean::Crate), Error> {
136         debug!("Initializing json renderer");
137         Ok((
138             JsonRenderer {
139                 tcx,
140                 index: Rc::new(RefCell::new(FxHashMap::default())),
141                 out_path: options.output,
142             },
143             krate,
144         ))
145     }
146
147     /// Inserts an item into the index. This should be used rather than directly calling insert on
148     /// the hashmap because certain items (traits and types) need to have their mappings for trait
149     /// implementations filled out before they're inserted.
150     fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
151         // Flatten items that recursively store other items
152         item.kind.inner_items().for_each(|i| self.item(i.clone(), cache).unwrap());
153
154         let id = item.def_id;
155         if let Some(mut new_item) = self.convert_item(item) {
156             if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
157                 t.implementors = self.get_trait_implementors(id, cache)
158             } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
159                 s.impls = self.get_impls(id, cache)
160             } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
161                 e.impls = self.get_impls(id, cache)
162             }
163             let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
164             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
165             // to make sure the items are unique.
166             if let Some(old_item) = removed {
167                 assert_eq!(old_item, new_item);
168             }
169         }
170
171         Ok(())
172     }
173
174     fn mod_item_in(
175         &mut self,
176         item: &clean::Item,
177         _module_name: &str,
178         cache: &Cache,
179     ) -> 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(), cache).unwrap(),
186                     ExternCrateItem(_, _) => self.item(item.clone(), cache).unwrap(),
187                     ImplItem(i) => {
188                         i.items.iter().for_each(|i| self.item(i.clone(), cache).unwrap())
189                     }
190                     _ => {}
191                 }
192             }
193         }
194         self.item(item.clone(), cache).unwrap();
195         Ok(())
196     }
197
198     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
199         Ok(())
200     }
201
202     fn after_krate(
203         &mut self,
204         krate: &clean::Crate,
205         cache: &Cache,
206         _diag: &rustc_errors::Handler,
207     ) -> Result<(), Error> {
208         debug!("Done with crate");
209         let mut index = (*self.index).clone().into_inner();
210         index.extend(self.get_trait_items(cache));
211         let output = types::Crate {
212             root: types::Id(String::from("0:0")),
213             crate_version: krate.version.clone(),
214             includes_private: cache.document_private,
215             index,
216             paths: cache
217                 .paths
218                 .clone()
219                 .into_iter()
220                 .chain(cache.external_paths.clone().into_iter())
221                 .map(|(k, (path, kind))| {
222                     (
223                         k.into(),
224                         types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
225                     )
226                 })
227                 .collect(),
228             external_crates: cache
229                 .extern_locations
230                 .iter()
231                 .map(|(k, v)| {
232                     (
233                         k.as_u32(),
234                         types::ExternalCrate {
235                             name: v.0.to_string(),
236                             html_root_url: match &v.2 {
237                                 ExternalLocation::Remote(s) => Some(s.clone()),
238                                 _ => None,
239                             },
240                         },
241                     )
242                 })
243                 .collect(),
244             format_version: 1,
245         };
246         let mut p = self.out_path.clone();
247         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
248         p.set_extension("json");
249         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
250         serde_json::ser::to_writer(&file, &output).unwrap();
251         Ok(())
252     }
253 }