]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/json/mod.rs
Auto merge of #100759 - fee1-dead-contrib:const_eval_select_real_intrinsic, r=oli...
[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         Rc::clone(&self.cache)
105             .traits
106             .iter()
107             .filter_map(|(&id, trait_item)| {
108                 // only need to synthesize items for external traits
109                 if !id.is_local() {
110                     let trait_item = &trait_item.trait_;
111                     for item in &trait_item.items {
112                         self.item(item.clone()).unwrap();
113                     }
114                     let item_id = from_item_id(id.into(), self.tcx);
115                     Some((
116                         item_id.clone(),
117                         types::Item {
118                             id: item_id,
119                             crate_id: id.krate.as_u32(),
120                             name: self
121                                 .cache
122                                 .paths
123                                 .get(&id)
124                                 .unwrap_or_else(|| {
125                                     self.cache
126                                         .external_paths
127                                         .get(&id)
128                                         .expect("Trait should either be in local or external paths")
129                                 })
130                                 .0
131                                 .last()
132                                 .map(|s| s.to_string()),
133                             visibility: types::Visibility::Public,
134                             inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)),
135                             span: None,
136                             docs: Default::default(),
137                             links: Default::default(),
138                             attrs: Default::default(),
139                             deprecation: Default::default(),
140                         },
141                     ))
142                 } else {
143                     None
144                 }
145             })
146             .collect()
147     }
148 }
149
150 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
151     fn descr() -> &'static str {
152         "json"
153     }
154
155     const RUN_ON_MODULE: bool = false;
156
157     fn init(
158         krate: clean::Crate,
159         options: RenderOptions,
160         cache: Cache,
161         tcx: TyCtxt<'tcx>,
162     ) -> Result<(Self, clean::Crate), Error> {
163         debug!("Initializing json renderer");
164
165         let (krate, imported_items) = import_finder::get_imports(krate);
166
167         Ok((
168             JsonRenderer {
169                 tcx,
170                 index: Rc::new(RefCell::new(FxHashMap::default())),
171                 out_path: options.output,
172                 cache: Rc::new(cache),
173                 imported_items,
174             },
175             krate,
176         ))
177     }
178
179     fn make_child_renderer(&self) -> Self {
180         self.clone()
181     }
182
183     /// Inserts an item into the index. This should be used rather than directly calling insert on
184     /// the hashmap because certain items (traits and types) need to have their mappings for trait
185     /// implementations filled out before they're inserted.
186     fn item(&mut self, item: clean::Item) -> Result<(), Error> {
187         trace!("rendering {} {:?}", item.type_(), item.name);
188
189         // Flatten items that recursively store other items. We include orphaned items from
190         // stripped modules and etc that are otherwise reachable.
191         if let ItemKind::StrippedItem(inner) = &*item.kind {
192             inner.inner_items().for_each(|i| self.item(i.clone()).unwrap());
193         }
194
195         // Flatten items that recursively store other items
196         item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
197
198         let name = item.name;
199         let item_id = item.item_id;
200         if let Some(mut new_item) = self.convert_item(item) {
201             let can_be_ignored = match new_item.inner {
202                 types::ItemEnum::Trait(ref mut t) => {
203                     t.implementations = self.get_trait_implementors(item_id.expect_def_id());
204                     false
205                 }
206                 types::ItemEnum::Struct(ref mut s) => {
207                     s.impls = self.get_impls(item_id.expect_def_id());
208                     false
209                 }
210                 types::ItemEnum::Enum(ref mut e) => {
211                     e.impls = self.get_impls(item_id.expect_def_id());
212                     false
213                 }
214                 types::ItemEnum::Union(ref mut u) => {
215                     u.impls = self.get_impls(item_id.expect_def_id());
216                     false
217                 }
218
219                 types::ItemEnum::Method(_)
220                 | types::ItemEnum::Module(_)
221                 | types::ItemEnum::AssocConst { .. }
222                 | types::ItemEnum::AssocType { .. }
223                 | types::ItemEnum::PrimitiveType(_) => true,
224                 types::ItemEnum::ExternCrate { .. }
225                 | types::ItemEnum::Import(_)
226                 | types::ItemEnum::StructField(_)
227                 | types::ItemEnum::Variant(_)
228                 | types::ItemEnum::Function(_)
229                 | types::ItemEnum::TraitAlias(_)
230                 | types::ItemEnum::Impl(_)
231                 | types::ItemEnum::Typedef(_)
232                 | types::ItemEnum::OpaqueTy(_)
233                 | types::ItemEnum::Constant(_)
234                 | types::ItemEnum::Static(_)
235                 | types::ItemEnum::ForeignType
236                 | types::ItemEnum::Macro(_)
237                 | types::ItemEnum::ProcMacro(_) => false,
238             };
239             let removed = self
240                 .index
241                 .borrow_mut()
242                 .insert(from_item_id_with_name(item_id, self.tcx, name), new_item.clone());
243
244             // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
245             // to make sure the items are unique. The main place this happens is when an item, is
246             // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod`
247             if let Some(old_item) = removed {
248                 // In case of generic implementations (like `impl<T> Trait for T {}`), all the
249                 // inner items will be duplicated so we can ignore if they are slightly different.
250                 if !can_be_ignored {
251                     assert_eq!(old_item, new_item);
252                 }
253             }
254         }
255
256         Ok(())
257     }
258
259     fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> {
260         unreachable!("RUN_ON_MODULE = false should never call mod_item_in")
261     }
262
263     fn after_krate(&mut self) -> Result<(), Error> {
264         debug!("Done with crate");
265
266         for primitive in Rc::clone(&self.cache).primitive_locations.values() {
267             self.get_impls(*primitive);
268         }
269
270         let e = ExternalCrate { crate_num: LOCAL_CRATE };
271
272         let mut index = (*self.index).clone().into_inner();
273         index.extend(self.get_trait_items());
274         // This needs to be the default HashMap for compatibility with the public interface for
275         // rustdoc-json-types
276         #[allow(rustc::default_hash_types)]
277         let output = types::Crate {
278             root: types::Id(format!("0:0:{}", e.name(self.tcx).as_u32())),
279             crate_version: self.cache.crate_version.clone(),
280             includes_private: self.cache.document_private,
281             index: index.into_iter().collect(),
282             paths: self
283                 .cache
284                 .paths
285                 .iter()
286                 .chain(&self.cache.external_paths)
287                 .map(|(&k, &(ref path, kind))| {
288                     (
289                         from_item_id(k.into(), self.tcx),
290                         types::ItemSummary {
291                             crate_id: k.krate.as_u32(),
292                             path: path.iter().map(|s| s.to_string()).collect(),
293                             kind: kind.into_tcx(self.tcx),
294                         },
295                     )
296                 })
297                 .collect(),
298             external_crates: self
299                 .cache
300                 .extern_locations
301                 .iter()
302                 .map(|(crate_num, external_location)| {
303                     let e = ExternalCrate { crate_num: *crate_num };
304                     (
305                         crate_num.as_u32(),
306                         types::ExternalCrate {
307                             name: e.name(self.tcx).to_string(),
308                             html_root_url: match external_location {
309                                 ExternalLocation::Remote(s) => Some(s.clone()),
310                                 _ => None,
311                             },
312                         },
313                     )
314                 })
315                 .collect(),
316             format_version: types::FORMAT_VERSION,
317         };
318         let out_dir = self.out_path.clone();
319         try_err!(create_dir_all(&out_dir), out_dir);
320
321         let mut p = out_dir;
322         p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
323         p.set_extension("json");
324         let mut file = BufWriter::new(try_err!(File::create(&p), p));
325         serde_json::ser::to_writer(&mut file, &output).unwrap();
326         try_err!(file.flush(), p);
327
328         Ok(())
329     }
330
331     fn cache(&self) -> &Cache {
332         &self.cache
333     }
334 }