1 //! Rustdoc's JSON backend
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.
9 use std::cell::RefCell;
10 use std::fs::{create_dir_all, File};
11 use std::io::{BufWriter, Write};
12 use std::path::PathBuf;
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;
21 use rustdoc_json_types as types;
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};
34 pub(crate) struct JsonRenderer<'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.
44 impl<'tcx> JsonRenderer<'tcx> {
45 fn sess(&self) -> &'tcx Session {
49 fn get_trait_implementors(&mut self, id: DefId) -> Vec<types::Id> {
50 Rc::clone(&self.cache)
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)
66 fn get_impls(&mut self, id: DefId) -> Vec<types::Id> {
67 Rc::clone(&self.cache)
74 let item = &i.impl_item;
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
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;
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))
101 fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
102 Rc::clone(&self.cache)
105 .filter_map(|(&id, trait_item)| {
106 // only need to synthesize items for external traits
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);
115 crate_id: id.krate.as_u32(),
124 .expect("Trait should either be in local or external paths")
128 .map(|s| s.to_string()),
129 visibility: types::Visibility::Public,
130 inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)),
132 docs: Default::default(),
133 links: Default::default(),
134 attrs: Default::default(),
135 deprecation: Default::default(),
146 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
147 fn descr() -> &'static str {
151 const RUN_ON_MODULE: bool = false;
155 options: RenderOptions,
158 ) -> Result<(Self, clean::Crate), Error> {
159 debug!("Initializing json renderer");
163 index: Rc::new(RefCell::new(FxHashMap::default())),
164 out_path: options.output,
165 cache: Rc::new(cache),
171 fn make_child_renderer(&self) -> Self {
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);
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());
187 // Flatten items that recursively store other items
188 item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
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());
198 types::ItemEnum::Struct(ref mut s) => {
199 s.impls = self.get_impls(item_id.expect_def_id());
202 types::ItemEnum::Enum(ref mut e) => {
203 e.impls = self.get_impls(item_id.expect_def_id());
206 types::ItemEnum::Union(ref mut u) => {
207 u.impls = self.get_impls(item_id.expect_def_id());
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,
234 .insert(from_item_id_with_name(item_id, self.tcx, name), new_item.clone());
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.
243 assert_eq!(old_item, new_item);
251 fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> {
252 unreachable!("RUN_ON_MODULE = false should never call mod_item_in")
255 fn after_krate(&mut self) -> Result<(), Error> {
256 debug!("Done with crate");
258 for primitive in Rc::clone(&self.cache).primitive_locations.values() {
259 self.get_impls(*primitive);
262 let e = ExternalCrate { crate_num: LOCAL_CRATE };
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(),
279 .chain(self.cache.external_paths.clone().into_iter())
280 .map(|(k, (path, kind))| {
282 from_item_id(k.into(), self.tcx),
284 crate_id: k.krate.as_u32(),
285 path: path.iter().map(|s| s.to_string()).collect(),
286 kind: kind.into_tcx(self.tcx),
291 external_crates: self
295 .map(|(crate_num, external_location)| {
296 let e = ExternalCrate { crate_num: *crate_num };
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()),
309 format_version: types::FORMAT_VERSION,
311 let out_dir = self.out_path.clone();
312 try_err!(create_dir_all(&out_dir), 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);
324 fn cache(&self) -> &Cache {