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;
11 use std::path::PathBuf;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_middle::ty::TyCtxt;
16 use rustc_session::Session;
17 use rustc_span::edition::Edition;
19 use rustdoc_json_types as types;
22 use crate::config::RenderOptions;
23 use crate::error::Error;
24 use crate::formats::cache::Cache;
25 use crate::formats::FormatRenderer;
26 use crate::html::render::cache::ExternalLocation;
27 use crate::json::conversions::from_def_id;
30 crate struct JsonRenderer<'tcx> {
32 /// A mapping of IDs that contains all local items for this crate which gets output as a top
33 /// level field of the JSON blob.
34 index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
35 /// The directory where the blob will be written to.
40 impl JsonRenderer<'tcx> {
41 fn sess(&self) -> &'tcx Session {
45 fn get_trait_implementors(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
46 Rc::clone(&self.cache)
53 let item = &i.impl_item;
54 self.item(item.clone()).unwrap();
55 from_def_id(item.def_id)
62 fn get_impls(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
63 Rc::clone(&self.cache)
70 let item = &i.impl_item;
71 if item.def_id.is_local() {
72 self.item(item.clone()).unwrap();
73 Some(from_def_id(item.def_id))
83 fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
84 Rc::clone(&self.cache)
87 .filter_map(|(&id, trait_item)| {
88 // only need to synthesize items for external traits
90 let trait_item = &trait_item.trait_;
91 trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
96 crate_id: id.krate.as_u32(),
105 .expect("Trait should either be in local or external paths")
110 visibility: types::Visibility::Public,
111 kind: types::ItemKind::Trait,
112 inner: types::ItemEnum::TraitItem(trait_item.clone().into()),
114 docs: Default::default(),
115 links: Default::default(),
116 attrs: Default::default(),
117 deprecation: Default::default(),
128 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
129 fn descr() -> &'static str {
135 options: RenderOptions,
139 ) -> Result<(Self, clean::Crate), Error> {
140 debug!("Initializing json renderer");
144 index: Rc::new(RefCell::new(FxHashMap::default())),
145 out_path: options.output,
146 cache: Rc::new(cache),
152 /// Inserts an item into the index. This should be used rather than directly calling insert on
153 /// the hashmap because certain items (traits and types) need to have their mappings for trait
154 /// implementations filled out before they're inserted.
155 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
156 // Flatten items that recursively store other items
157 item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
159 let id = item.def_id;
160 if let Some(mut new_item) = self.convert_item(item) {
161 if let types::ItemEnum::TraitItem(ref mut t) = new_item.inner {
162 t.implementors = self.get_trait_implementors(id)
163 } else if let types::ItemEnum::StructItem(ref mut s) = new_item.inner {
164 s.impls = self.get_impls(id)
165 } else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
166 e.impls = self.get_impls(id)
168 let removed = self.index.borrow_mut().insert(from_def_id(id), new_item.clone());
169 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
170 // to make sure the items are unique.
171 if let Some(old_item) = removed {
172 assert_eq!(old_item, new_item);
179 fn mod_item_in(&mut self, item: &clean::Item, _module_name: &str) -> Result<(), Error> {
180 use clean::types::ItemKind::*;
181 if let ModuleItem(m) = &*item.kind {
182 for item in &m.items {
184 // These don't have names so they don't get added to the output by default
185 ImportItem(_) => self.item(item.clone()).unwrap(),
186 ExternCrateItem { .. } => self.item(item.clone()).unwrap(),
187 ImplItem(i) => i.items.iter().for_each(|i| self.item(i.clone()).unwrap()),
192 self.item(item.clone()).unwrap();
196 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
202 _krate: &clean::Crate,
203 _diag: &rustc_errors::Handler,
204 ) -> Result<(), Error> {
205 debug!("Done with crate");
206 let mut index = (*self.index).clone().into_inner();
207 index.extend(self.get_trait_items());
208 // This needs to be the default HashMap for compatibility with the public interface for
210 #[allow(rustc::default_hash_types)]
211 let output = types::Crate {
212 root: types::Id(String::from("0:0")),
213 crate_version: self.cache.crate_version.clone(),
214 includes_private: self.cache.document_private,
215 index: index.into_iter().collect(),
221 .chain(self.cache.external_paths.clone().into_iter())
222 .map(|(k, (path, kind))| {
225 types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
229 external_crates: self
236 types::ExternalCrate {
237 name: v.0.to_string(),
238 html_root_url: match &v.2 {
239 ExternalLocation::Remote(s) => Some(s.clone()),
248 let mut p = self.out_path.clone();
249 p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
250 p.set_extension("json");
251 let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
252 serde_json::ser::to_writer(&file, &output).unwrap();
256 fn cache(&self) -> &Cache {