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