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 inner: types::ItemEnum::Trait(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,
138 ) -> Result<(Self, clean::Crate), Error> {
139 debug!("Initializing json renderer");
143 index: Rc::new(RefCell::new(FxHashMap::default())),
144 out_path: options.output,
145 cache: Rc::new(cache),
151 fn make_child_renderer(&self) -> Self {
155 /// Inserts an item into the index. This should be used rather than directly calling insert on
156 /// the hashmap because certain items (traits and types) need to have their mappings for trait
157 /// implementations filled out before they're inserted.
158 fn item(&mut self, item: clean::Item) -> Result<(), Error> {
159 // Flatten items that recursively store other items
160 item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap());
162 let id = item.def_id;
163 if let Some(mut new_item) = self.convert_item(item) {
164 if let types::ItemEnum::Trait(ref mut t) = new_item.inner {
165 t.implementors = self.get_trait_implementors(id)
166 } else if let types::ItemEnum::Struct(ref mut s) = new_item.inner {
167 s.impls = self.get_impls(id)
168 } else if let types::ItemEnum::Enum(ref mut e) = new_item.inner {
169 e.impls = self.get_impls(id)
171 let removed = self.index.borrow_mut().insert(from_def_id(id), new_item.clone());
172 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
173 // to make sure the items are unique.
174 if let Some(old_item) = removed {
175 assert_eq!(old_item, new_item);
182 fn mod_item_in(&mut self, item: &clean::Item, _module_name: &str) -> Result<(), Error> {
183 use clean::types::ItemKind::*;
184 if let ModuleItem(m) = &*item.kind {
185 for item in &m.items {
187 // These don't have names so they don't get added to the output by default
188 ImportItem(_) => self.item(item.clone()).unwrap(),
189 ExternCrateItem { .. } => self.item(item.clone()).unwrap(),
190 ImplItem(i) => i.items.iter().for_each(|i| self.item(i.clone()).unwrap()),
195 self.item(item.clone()).unwrap();
199 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
205 _krate: &clean::Crate,
206 _diag: &rustc_errors::Handler,
207 ) -> Result<(), Error> {
208 debug!("Done with crate");
209 let mut index = (*self.index).clone().into_inner();
210 index.extend(self.get_trait_items());
211 // This needs to be the default HashMap for compatibility with the public interface for
213 #[allow(rustc::default_hash_types)]
214 let output = types::Crate {
215 root: types::Id(String::from("0:0")),
216 crate_version: self.cache.crate_version.clone(),
217 includes_private: self.cache.document_private,
218 index: index.into_iter().collect(),
224 .chain(self.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: self
239 types::ExternalCrate {
240 name: v.0.to_string(),
241 html_root_url: match &v.2 {
242 ExternalLocation::Remote(s) => Some(s.clone()),
251 let mut p = self.out_path.clone();
252 p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
253 p.set_extension("json");
254 let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
255 serde_json::ser::to_writer(&file, &output).unwrap();
259 fn cache(&self) -> &Cache {