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.
10 use std::cell::RefCell;
12 use std::path::PathBuf;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::Session;
18 use rustc_span::edition::Edition;
21 use crate::config::{RenderInfo, RenderOptions};
22 use crate::error::Error;
23 use crate::formats::cache::Cache;
24 use crate::formats::FormatRenderer;
25 use crate::html::render::cache::ExternalLocation;
28 crate struct JsonRenderer<'tcx> {
30 /// A mapping of IDs that contains all local items for this crate which gets output as a top
31 /// level field of the JSON blob.
32 index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
33 /// The directory where the blob will be written to.
37 impl JsonRenderer<'_> {
38 fn sess(&self) -> &Session {
42 fn get_trait_implementors(
44 id: rustc_span::def_id::DefId,
54 let item = &i.impl_item;
55 self.item(item.clone(), cache).unwrap();
63 fn get_impls(&mut self, id: rustc_span::def_id::DefId, cache: &Cache) -> Vec<types::Id> {
71 let item = &i.impl_item;
72 if item.def_id.is_local() {
73 self.item(item.clone(), cache).unwrap();
74 Some(item.def_id.into())
84 fn get_trait_items(&mut self, cache: &Cache) -> Vec<(types::Id, types::Item)> {
88 .filter_map(|(&id, trait_item)| {
89 // only need to synthesize items for external traits
91 trait_item.items.clone().into_iter().for_each(|i| self.item(i, cache).unwrap());
96 crate_id: id.krate.as_u32(),
104 .expect("Trait should either be in local or external paths")
109 visibility: types::Visibility::Public,
110 kind: types::ItemKind::Trait,
111 inner: types::ItemEnum::TraitItem(trait_item.clone().into()),
113 docs: Default::default(),
114 links: Default::default(),
115 attrs: Default::default(),
116 deprecation: Default::default(),
127 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
128 fn descr() -> &'static str {
134 options: RenderOptions,
135 _render_info: RenderInfo,
139 ) -> Result<(Self, clean::Crate), Error> {
140 debug!("Initializing json renderer");
144 index: Rc::new(RefCell::new(FxHashMap::default())),
145 out_path: options.output,
151 /// Inserts an item into the index. This should be used rather than directly calling insert on
152 /// the hashmap because certain items (traits and types) need to have their mappings for trait
153 /// implementations filled out before they're inserted.
154 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
155 // Flatten items that recursively store other items
156 item.kind.inner_items().for_each(|i| self.item(i.clone(), cache).unwrap());
158 let id = item.def_id;
159 if let Some(mut new_item) = self.convert_item(item) {
160 if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
161 t.implementors = self.get_trait_implementors(id, cache)
162 } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
163 s.impls = self.get_impls(id, cache)
164 } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
165 e.impls = self.get_impls(id, cache)
167 let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
168 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
169 // to make sure the items are unique.
170 if let Some(old_item) = removed {
171 assert_eq!(old_item, new_item);
183 ) -> Result<(), Error> {
184 use clean::types::ItemKind::*;
185 if let ModuleItem(m) = &*item.kind {
186 for item in &m.items {
188 // These don't have names so they don't get added to the output by default
189 ImportItem(_) => self.item(item.clone(), cache).unwrap(),
190 ExternCrateItem(_, _) => self.item(item.clone(), cache).unwrap(),
192 i.items.iter().for_each(|i| self.item(i.clone(), cache).unwrap())
198 self.item(item.clone(), cache).unwrap();
202 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
208 krate: &clean::Crate,
210 _diag: &rustc_errors::Handler,
211 ) -> Result<(), Error> {
212 debug!("Done with crate");
213 let mut index = (*self.index).clone().into_inner();
214 index.extend(self.get_trait_items(cache));
215 let output = types::Crate {
216 root: types::Id(String::from("0:0")),
217 crate_version: krate.version.clone(),
218 includes_private: cache.document_private,
224 .chain(cache.external_paths.clone().into_iter())
225 .map(|(k, (path, kind))| {
228 types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
232 external_crates: cache
238 types::ExternalCrate {
239 name: v.0.to_string(),
240 html_root_url: match &v.2 {
241 ExternalLocation::Remote(s) => Some(s.clone()),
250 let mut p = self.out_path.clone();
251 p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
252 p.set_extension("json");
253 let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
254 serde_json::ser::to_writer(&file, &output).unwrap();