]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
merge rustc history
[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 mod import_finder;
9
10 use std::cell::RefCell;
11 use std::fs::{create_dir_all, File};
12 use std::io::{BufWriter, Write};
13 use std::path::PathBuf;
14 use std::rc::Rc;
15
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_session::Session;
20 use rustc_span::def_id::LOCAL_CRATE;
21
22 use rustdoc_json_types as types;
23
24 use crate::clean::types::{ExternalCrate, ExternalLocation};
25 use crate::clean::ItemKind;
26 use crate::config::RenderOptions;
27 use crate::docfs::PathError;
28 use crate::error::Error;
29 use crate::formats::cache::Cache;
30 use crate::formats::FormatRenderer;
31 use crate::json::conversions::{from_item_id, from_item_id_with_name, IntoWithTcx};
32 use crate::{clean, try_err};
33
34 #[derive(Clone)]
35 pub(crate) struct JsonRenderer<'tcx> {
36     tcx: TyCtxt<'tcx>,
37     /// A mapping of IDs that contains all local items for this crate which gets output as a top
38     /// level field of the JSON blob.
39     index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
40     /// The directory where the blob will be written to.
41     out_path: PathBuf,
42     cache: Rc<Cache>,
43     imported_items: FxHashSet<DefId>,
44 }
45
46 impl<'tcx> JsonRenderer<'tcx> {
47     fn sess(&self) -> &'tcx Session {
48         self.tcx.sess
49     }
50
51     fn get_trait_implementors(&mut self, id: DefId) -> Vec<types::Id> {
52         Rc::clone(&self.cache)
53             .implementors
54             .get(&id)
55             .map(|implementors| {
56                 implementors
57                     .iter()
58                     .map(|i| {
59                         let item = &i.impl_item;
60                         self.item(item.clone()).unwrap();
61                         from_item_id_with_name(item.item_id, self.tcx, item.name)
62                     })
63                     .collect()
64             })
65             .unwrap_or_default()
66     }
67
68     fn get_impls(&mut self, id: DefId) -> Vec<types::Id> {
69         Rc::clone(&self.cache)
70             .impls
71             .get(&id)
72             .map(|impls| {
73                 impls
74                     .iter()
75                     .filter_map(|i| {
76                         let item = &i.impl_item;
77
78                         // HACK(hkmatsumoto): For impls of primitive types, we index them
79                         // regardless of whether they're local. This is because users can
80                         // document primitive items in an arbitrary crate by using
81                         // `doc(primitive)`.
82                         let mut is_primitive_impl = false;
83                         if let clean::types::ItemKind::ImplItem(ref impl_) = *item.kind {
84                             if impl_.trait_.is_none() {
85                                 if let clean::types::Type::Primitive(_) = impl_.for_ {
86                                     is_primitive_impl = true;
87                                 }
88                             }
89                         }
90
91                         if item.item_id.is_local() || is_primitive_impl {
92                             self.item(item.clone()).unwrap();
93                             Some(from_item_id_with_name(item.item_id, self.tcx, item.name))
94                         } else {
95                             None
96                         }
97                     })
98                     .collect()
99             })
100             .unwrap_or_default()
101     }
102
103     fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
104         debug!("Adding foreign trait items");
105         Rc::clone(&self.cache)
106             .traits
107             .iter()
108             .filter_map(|(&id, trait_item)| {
109                 // only need to synthesize items for external traits
110                 if !id.is_local() {
111                     let trait_item = &trait_item.trait_;
112                     for item in &trait_item.items {
113                         trace!("Adding subitem to {id:?}: {:?}", item.item_id);
114                         self.item(item.clone()).unwrap();
115                     }
116                     let item_id = from_item_id(id.into(), self.tcx);
117                     Some((
118                         item_id.clone(),
119                         types::Item {
120                             id: item_id,
121                             crate_id: id.krate.as_u32(),
122                             name: self
123                                 .cache
124                                 .paths
125                                 .get(&id)
126                                 .unwrap_or_else(|| {
127                                     self.cache
128                                         .external_paths
129                                         .get(&id)
130                                         .expect("Trait should either be in local or external paths")
131                                 })
132                                 .0
133                                 .last()
134                                 .map(|s| s.to_string()),
135                             visibility: types::Visibility::Public,
136                             inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)),
137                             span: None,
138                             docs: Default::default(),
139                             links: Default::default(),
140                             attrs: Default::default(),
141                             deprecation: Default::default(),
142                         },
143                     ))
144                 } else {
145                     None
146                 }
147             })
148             .collect()
149     }
150 }
151
152 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
153     fn descr() -> &'static str {
154         "json"
155     }
156
157     const RUN_ON_MODULE: bool = false;
158
159     fn init(
160         krate: clean::Crate,
161         options: RenderOptions,
162         cache: Cache,
163         tcx: TyCtxt<'tcx>,
164     ) -> Result<(Self, clean::Crate), Error> {
165         debug!("Initializing json renderer");
166
167         let (krate, imported_items) = import_finder::get_imports(krate);
168
169         Ok((
170             JsonRenderer {
171                 tcx,
172                 index: Rc::new(RefCell::new(FxHashMap::default())),
173                 out_path: options.output,
174                 cache: Rc::new(cache),
175                 imported_items,
176             },
177             krate,
178         ))
179     }
180
181     fn make_child_renderer(&self) -> Self {
182         self.clone()
183     }
184
185     /// Inserts an item into the index. This should be used rather than directly calling insert on
186     /// the hashmap because certain items (traits and types) need to have their mappings for trait
187     /// implementations filled out before they're inserted.
188     fn item(&mut self, item: clean::Item) -> Result<(), Error> {
189         let item_type = item.type_();
190         let item_name = item.name;
191         trace!("rendering {} {:?}", item_type, item_name);
192
193         // Flatten items that recursively store other items. We include orphaned items from
194         // stripped modules and etc that are otherwise reachable.
195         if let ItemKind::StrippedItem(inner) = &*item.kind {
196             inner.inner_items().for_each(|i| self.item(i.clone()).unwrap());
197         }
198
199         // Flatten items that recursively store other items
200         item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
201
202         let name = item.name;
203         let item_id = item.item_id;
204         if let Some(mut new_item) = self.convert_item(item) {
205             let can_be_ignored = match new_item.inner {
206                 types::ItemEnum::Trait(ref mut t) => {
207                     t.implementations = self.get_trait_implementors(item_id.expect_def_id());
208                     false
209                 }
210                 types::ItemEnum::Struct(ref mut s) => {
211                     s.impls = self.get_impls(item_id.expect_def_id());
212                     false
213                 }
214                 types::ItemEnum::Enum(ref mut e) => {
215                     e.impls = self.get_impls(item_id.expect_def_id());
216                     false
217                 }
218                 types::ItemEnum::Union(ref mut u) => {
219                     u.impls = self.get_impls(item_id.expect_def_id());
220                     false
221                 }
222
223                 types::ItemEnum::Method(_)
224                 | types::ItemEnum::Module(_)
225                 | types::ItemEnum::AssocConst { .. }
226                 | types::ItemEnum::AssocType { .. }
227                 | types::ItemEnum::PrimitiveType(_) => true,
228                 types::ItemEnum::ExternCrate { .. }
229                 | types::ItemEnum::Import(_)
230                 | types::ItemEnum::StructField(_)
231                 | types::ItemEnum::Variant(_)
232                 | types::ItemEnum::Function(_)
233                 | types::ItemEnum::TraitAlias(_)
234                 | types::ItemEnum::Impl(_)
235                 | types::ItemEnum::Typedef(_)
236                 | types::ItemEnum::OpaqueTy(_)
237                 | types::ItemEnum::Constant(_)
238                 | types::ItemEnum::Static(_)
239                 | types::ItemEnum::ForeignType
240                 | types::ItemEnum::Macro(_)
241                 | types::ItemEnum::ProcMacro(_) => false,
242             };
243             let removed = self
244                 .index
245                 .borrow_mut()
246                 .insert(from_item_id_with_name(item_id, self.tcx, name), new_item.clone());
247
248             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
249             // to make sure the items are unique. The main place this happens is when an item, is
250             // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod`
251             if let Some(old_item) = removed {
252                 // In case of generic implementations (like `impl<T> Trait for T {}`), all the
253                 // inner items will be duplicated so we can ignore if they are slightly different.
254                 if !can_be_ignored {
255                     assert_eq!(old_item, new_item);
256                 }
257             }
258         }
259
260         trace!("done rendering {} {:?}", item_type, item_name);
261         Ok(())
262     }
263
264     fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> {
265         unreachable!("RUN_ON_MODULE = false should never call mod_item_in")
266     }
267
268     fn after_krate(&mut self) -> Result<(), Error> {
269         debug!("Done with crate");
270
271         debug!("Adding Primitve impls");
272         for primitive in Rc::clone(&self.cache).primitive_locations.values() {
273             self.get_impls(*primitive);
274         }
275
276         let e = ExternalCrate { crate_num: LOCAL_CRATE };
277
278         // FIXME(adotinthevoid): Remove this, as it's not consistant with not
279         // inlining foreign items.
280         let foreign_trait_items = self.get_trait_items();
281         let mut index = (*self.index).clone().into_inner();
282         index.extend(foreign_trait_items);
283
284         debug!("Constructing Output");
285         // This needs to be the default HashMap for compatibility with the public interface for
286         // rustdoc-json-types
287         #[allow(rustc::default_hash_types)]
288         let output = types::Crate {
289             root: types::Id(format!("0:0:{}", e.name(self.tcx).as_u32())),
290             crate_version: self.cache.crate_version.clone(),
291             includes_private: self.cache.document_private,
292             index: index.into_iter().collect(),
293             paths: self
294                 .cache
295                 .paths
296                 .iter()
297                 .chain(&self.cache.external_paths)
298                 .map(|(&k, &(ref path, kind))| {
299                     (
300                         from_item_id(k.into(), self.tcx),
301                         types::ItemSummary {
302                             crate_id: k.krate.as_u32(),
303                             path: path.iter().map(|s| s.to_string()).collect(),
304                             kind: kind.into_tcx(self.tcx),
305                         },
306                     )
307                 })
308                 .collect(),
309             external_crates: self
310                 .cache
311                 .extern_locations
312                 .iter()
313                 .map(|(crate_num, external_location)| {
314                     let e = ExternalCrate { crate_num: *crate_num };
315                     (
316                         crate_num.as_u32(),
317                         types::ExternalCrate {
318                             name: e.name(self.tcx).to_string(),
319                             html_root_url: match external_location {
320                                 ExternalLocation::Remote(s) => Some(s.clone()),
321                                 _ => None,
322                             },
323                         },
324                     )
325                 })
326                 .collect(),
327             format_version: types::FORMAT_VERSION,
328         };
329         let out_dir = self.out_path.clone();
330         try_err!(create_dir_all(&out_dir), out_dir);
331
332         let mut p = out_dir;
333         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
334         p.set_extension("json");
335         let mut file = BufWriter::new(try_err!(File::create(&p), p));
336         serde_json::ser::to_writer(&mut file, &output).unwrap();
337         try_err!(file.flush(), p);
338
339         Ok(())
340     }
341
342     fn cache(&self) -> &Cache {
343         &self.cache
344     }
345 }