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_span::edition::Edition;
19 use crate::config::{RenderInfo, RenderOptions};
20 use crate::error::Error;
21 use crate::formats::cache::Cache;
22 use crate::formats::FormatRenderer;
23 use crate::html::render::cache::ExternalLocation;
26 crate struct JsonRenderer {
27 /// A mapping of IDs that contains all local items for this crate which gets output as a top
28 /// level field of the JSON blob.
29 index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
30 /// The directory where the blob will be written to.
35 fn get_trait_implementors(
37 id: rustc_span::def_id::DefId,
47 let item = &i.impl_item;
48 self.item(item.clone(), cache).unwrap();
56 fn get_impls(&mut self, id: rustc_span::def_id::DefId, cache: &Cache) -> Vec<types::Id> {
64 let item = &i.impl_item;
65 if item.def_id.is_local() {
66 self.item(item.clone(), cache).unwrap();
67 Some(item.def_id.into())
77 fn get_trait_items(&mut self, cache: &Cache) -> Vec<(types::Id, types::Item)> {
81 .filter_map(|(&id, trait_item)| {
82 // only need to synthesize items for external traits
84 trait_item.items.clone().into_iter().for_each(|i| self.item(i, cache).unwrap());
89 crate_id: id.krate.as_u32(),
97 .expect("Trait should either be in local or external paths")
102 visibility: types::Visibility::Public,
103 kind: types::ItemKind::Trait,
104 inner: types::ItemEnum::TraitItem(trait_item.clone().into()),
106 docs: Default::default(),
107 links: Default::default(),
108 attrs: Default::default(),
109 deprecation: Default::default(),
120 impl FormatRenderer for JsonRenderer {
123 options: RenderOptions,
124 _render_info: RenderInfo,
127 ) -> Result<(Self, clean::Crate), Error> {
128 debug!("Initializing json renderer");
131 index: Rc::new(RefCell::new(FxHashMap::default())),
132 out_path: options.output,
138 /// Inserts an item into the index. This should be used rather than directly calling insert on
139 /// the hashmap because certain items (traits and types) need to have their mappings for trait
140 /// implementations filled out before they're inserted.
141 fn item(&mut self, item: clean::Item, cache: &Cache) -> Result<(), Error> {
142 // Flatten items that recursively store other items
143 item.kind.inner_items().for_each(|i| self.item(i.clone(), cache).unwrap());
145 let id = item.def_id;
146 if let Some(mut new_item) = item.into(): Option<types::Item> {
147 if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
148 t.implementors = self.get_trait_implementors(id, cache)
149 } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
150 s.impls = self.get_impls(id, cache)
151 } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
152 e.impls = self.get_impls(id, cache)
154 let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
155 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
156 // to make sure the items are unique.
157 if let Some(old_item) = removed {
158 assert_eq!(old_item, new_item);
170 ) -> Result<(), Error> {
171 use clean::types::ItemKind::*;
172 if let ModuleItem(m) = &item.kind {
173 for item in &m.items {
175 // These don't have names so they don't get added to the output by default
176 ImportItem(_) => self.item(item.clone(), cache).unwrap(),
177 ExternCrateItem(_, _) => self.item(item.clone(), cache).unwrap(),
179 i.items.iter().for_each(|i| self.item(i.clone(), cache).unwrap())
185 self.item(item.clone(), cache).unwrap();
189 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
193 fn after_krate(&mut self, krate: &clean::Crate, cache: &Cache) -> Result<(), Error> {
194 debug!("Done with crate");
195 let mut index = (*self.index).clone().into_inner();
196 index.extend(self.get_trait_items(cache));
197 let output = types::Crate {
198 root: types::Id(String::from("0:0")),
199 crate_version: krate.version.clone(),
200 includes_private: cache.document_private,
206 .chain(cache.external_paths.clone().into_iter())
207 .map(|(k, (path, kind))| {
210 types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
214 external_crates: cache
220 types::ExternalCrate {
222 html_root_url: match &v.2 {
223 ExternalLocation::Remote(s) => Some(s.clone()),
232 let mut p = self.out_path.clone();
233 p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
234 p.set_extension("json");
235 let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
236 serde_json::ser::to_writer(&file, &output).unwrap();
240 fn after_run(&mut self, _diag: &rustc_errors::Handler) -> Result<(), Error> {