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.
38 impl JsonRenderer<'_> {
39 fn sess(&self) -> &Session {
43 fn get_trait_implementors(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
44 Rc::clone(&self.cache)
51 let item = &i.impl_item;
52 self.item(item.clone()).unwrap();
60 fn get_impls(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
61 Rc::clone(&self.cache)
68 let item = &i.impl_item;
69 if item.def_id.is_local() {
70 self.item(item.clone()).unwrap();
71 Some(item.def_id.into())
81 fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
82 Rc::clone(&self.cache)
85 .filter_map(|(&id, trait_item)| {
86 // only need to synthesize items for external traits
88 trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
93 crate_id: id.krate.as_u32(),
102 .expect("Trait should either be in local or external paths")
107 visibility: types::Visibility::Public,
108 kind: types::ItemKind::Trait,
109 inner: types::ItemEnum::TraitItem(trait_item.clone().into()),
111 docs: Default::default(),
112 links: Default::default(),
113 attrs: Default::default(),
114 deprecation: Default::default(),
125 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
126 fn descr() -> &'static str {
132 options: RenderOptions,
133 _render_info: RenderInfo,
137 ) -> Result<(Self, clean::Crate), Error> {
138 debug!("Initializing json renderer");
142 index: Rc::new(RefCell::new(FxHashMap::default())),
143 out_path: options.output,
144 cache: Rc::new(cache),
150 /// Inserts an item into the index. This should be used rather than directly calling insert on
151 /// the hashmap because certain items (traits and types) need to have their mappings for trait
152 /// implementations filled out before they're inserted.
153 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
154 // Flatten items that recursively store other items
155 item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
157 let id = item.def_id;
158 if let Some(mut new_item) = self.convert_item(item) {
159 if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
160 t.implementors = self.get_trait_implementors(id)
161 } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
162 s.impls = self.get_impls(id)
163 } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
164 e.impls = self.get_impls(id)
166 let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
167 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
168 // to make sure the items are unique.
169 if let Some(old_item) = removed {
170 assert_eq!(old_item, new_item);
177 fn mod_item_in(&mut self, item: &clean::Item, _module_name: &str) -> Result<(), Error> {
178 use clean::types::ItemKind::*;
179 if let ModuleItem(m) = &*item.kind {
180 for item in &m.items {
182 // These don't have names so they don't get added to the output by default
183 ImportItem(_) => self.item(item.clone()).unwrap(),
184 ExternCrateItem(_, _) => self.item(item.clone()).unwrap(),
185 ImplItem(i) => i.items.iter().for_each(|i| self.item(i.clone()).unwrap()),
190 self.item(item.clone()).unwrap();
194 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
200 krate: &clean::Crate,
201 _diag: &rustc_errors::Handler,
202 ) -> Result<(), Error> {
203 debug!("Done with crate");
204 let mut index = (*self.index).clone().into_inner();
205 index.extend(self.get_trait_items());
206 let output = types::Crate {
207 root: types::Id(String::from("0:0")),
208 crate_version: krate.version.clone(),
209 includes_private: self.cache.document_private,
216 .chain(self.cache.external_paths.clone().into_iter())
217 .map(|(k, (path, kind))| {
220 types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
224 external_crates: self
231 types::ExternalCrate {
232 name: v.0.to_string(),
233 html_root_url: match &v.2 {
234 ExternalLocation::Remote(s) => Some(s.clone()),
243 let mut p = self.out_path.clone();
244 p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
245 p.set_extension("json");
246 let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
247 serde_json::ser::to_writer(&file, &output).unwrap();
251 fn cache(&self) -> &Cache {