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