]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Rollup merge of #82767 - GuillaumeGomez:update-minifier-crate-version, r=jyn514
[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 rustdoc_json_types as types;
20
21 use crate::clean;
22 use crate::config::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<'tcx> {
41     fn sess(&self) -> &'tcx 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                     let trait_item = &trait_item.trait_;
91                     trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
92                     Some((
93                         from_def_id(id),
94                         types::Item {
95                             id: from_def_id(id),
96                             crate_id: id.krate.as_u32(),
97                             name: self
98                                 .cache
99                                 .paths
100                                 .get(&id)
101                                 .unwrap_or_else(|| {
102                                     self.cache
103                                         .external_paths
104                                         .get(&id)
105                                         .expect("Trait should either be in local or external paths")
106                                 })
107                                 .0
108                                 .last()
109                                 .map(Clone::clone),
110                             visibility: types::Visibility::Public,
111                             inner: types::ItemEnum::Trait(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         _edition: Edition,
136         cache: Cache,
137         tcx: TyCtxt<'tcx>,
138     ) -> Result<(Self, clean::Crate), Error> {
139         debug!("Initializing json renderer");
140         Ok((
141             JsonRenderer {
142                 tcx,
143                 index: Rc::new(RefCell::new(FxHashMap::default())),
144                 out_path: options.output,
145                 cache: Rc::new(cache),
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) -> Result<(), Error> {
155         // Flatten items that recursively store other items
156         item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
157
158         let id = item.def_id;
159         if let Some(mut new_item) = self.convert_item(item) {
160             if let types::ItemEnum::Trait(ref mut t) = new_item.inner {
161                 t.implementors = self.get_trait_implementors(id)
162             } else if let types::ItemEnum::Struct(ref mut s) = new_item.inner {
163                 s.impls = self.get_impls(id)
164             } else if let types::ItemEnum::Enum(ref mut e) = new_item.inner {
165                 e.impls = self.get_impls(id)
166             }
167             let removed = self.index.borrow_mut().insert(from_def_id(id), 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(&mut self, item: &clean::Item, _module_name: &str) -> Result<(), Error> {
179         use clean::types::ItemKind::*;
180         if let ModuleItem(m) = &*item.kind {
181             for item in &m.items {
182                 match &*item.kind {
183                     // These don't have names so they don't get added to the output by default
184                     ImportItem(_) => self.item(item.clone()).unwrap(),
185                     ExternCrateItem { .. } => self.item(item.clone()).unwrap(),
186                     ImplItem(i) => i.items.iter().for_each(|i| self.item(i.clone()).unwrap()),
187                     _ => {}
188                 }
189             }
190         }
191         self.item(item.clone()).unwrap();
192         Ok(())
193     }
194
195     fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
196         Ok(())
197     }
198
199     fn after_krate(
200         &mut self,
201         _krate: &clean::Crate,
202         _diag: &rustc_errors::Handler,
203     ) -> Result<(), Error> {
204         debug!("Done with crate");
205         let mut index = (*self.index).clone().into_inner();
206         index.extend(self.get_trait_items());
207         // This needs to be the default HashMap for compatibility with the public interface for
208         // rustdoc-json
209         #[allow(rustc::default_hash_types)]
210         let output = types::Crate {
211             root: types::Id(String::from("0:0")),
212             crate_version: self.cache.crate_version.clone(),
213             includes_private: self.cache.document_private,
214             index: index.into_iter().collect(),
215             paths: self
216                 .cache
217                 .paths
218                 .clone()
219                 .into_iter()
220                 .chain(self.cache.external_paths.clone().into_iter())
221                 .map(|(k, (path, kind))| {
222                     (
223                         from_def_id(k),
224                         types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
225                     )
226                 })
227                 .collect(),
228             external_crates: self
229                 .cache
230                 .extern_locations
231                 .iter()
232                 .map(|(k, v)| {
233                     (
234                         k.as_u32(),
235                         types::ExternalCrate {
236                             name: v.0.to_string(),
237                             html_root_url: match &v.2 {
238                                 ExternalLocation::Remote(s) => Some(s.clone()),
239                                 _ => None,
240                             },
241                         },
242                     )
243                 })
244                 .collect(),
245             format_version: 4,
246         };
247         let mut p = self.out_path.clone();
248         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
249         p.set_extension("json");
250         let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
251         serde_json::ser::to_writer(&file, &output).unwrap();
252         Ok(())
253     }
254
255     fn cache(&self) -> &Cache {
256         &self.cache
257     }
258 }