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_hir
::def_id
::DefId
;
16 use rustc_middle
::ty
::TyCtxt
;
17 use rustc_session
::Session
;
19 use rustdoc_json_types
as types
;
22 use crate::clean
::ExternalCrate
;
23 use crate::config
::RenderOptions
;
24 use crate::error
::Error
;
25 use crate::formats
::cache
::Cache
;
26 use crate::formats
::FormatRenderer
;
27 use crate::html
::render
::cache
::ExternalLocation
;
28 use crate::json
::conversions
::{from_item_id, IntoWithTcx}
;
31 crate struct JsonRenderer
<'tcx
> {
33 /// A mapping of IDs that contains all local items for this crate which gets output as a top
34 /// level field of the JSON blob.
35 index
: Rc
<RefCell
<FxHashMap
<types
::Id
, types
::Item
>>>,
36 /// The directory where the blob will be written to.
41 impl JsonRenderer
<'tcx
> {
42 fn sess(&self) -> &'tcx Session
{
46 fn get_trait_implementors(&mut self, id
: DefId
) -> Vec
<types
::Id
> {
47 Rc
::clone(&self.cache
)
54 let item
= &i
.impl_item
;
55 self.item(item
.clone()).unwrap();
56 from_item_id(item
.def_id
)
63 fn get_impls(&mut self, id
: DefId
) -> Vec
<types
::Id
> {
64 Rc
::clone(&self.cache
)
71 let item
= &i
.impl_item
;
73 // HACK(hkmatsumoto): For impls of primitive types, we index them
74 // regardless of whether they're local. This is because users can
75 // document primitive items in an arbitrary crate by using
77 let mut is_primitive_impl
= false;
78 if let clean
::types
::ItemKind
::ImplItem(ref impl_
) = *item
.kind
{
79 if impl_
.trait_
.is_none() {
80 if let clean
::types
::Type
::Primitive(_
) = impl_
.for_
{
81 is_primitive_impl
= true;
86 if item
.def_id
.is_local() || is_primitive_impl
{
87 self.item(item
.clone()).unwrap();
88 Some(from_item_id(item
.def_id
))
98 fn get_trait_items(&mut self) -> Vec
<(types
::Id
, types
::Item
)> {
99 Rc
::clone(&self.cache
)
102 .filter_map(|(&id
, trait_item
)| {
103 // only need to synthesize items for external traits
105 let trait_item
= &trait_item
.trait_
;
106 trait_item
.items
.clone().into_iter().for_each(|i
| self.item(i
).unwrap());
108 from_item_id(id
.into()),
110 id
: from_item_id(id
.into()),
111 crate_id
: id
.krate
.as_u32(),
120 .expect("Trait should either be in local or external paths")
125 visibility
: types
::Visibility
::Public
,
126 inner
: types
::ItemEnum
::Trait(trait_item
.clone().into_tcx(self.tcx
)),
128 docs
: Default
::default(),
129 links
: Default
::default(),
130 attrs
: Default
::default(),
131 deprecation
: Default
::default(),
142 impl<'tcx
> FormatRenderer
<'tcx
> for JsonRenderer
<'tcx
> {
143 fn descr() -> &'
static str {
147 const RUN_ON_MODULE
: bool
= false;
151 options
: RenderOptions
,
154 ) -> Result
<(Self, clean
::Crate
), Error
> {
155 debug
!("Initializing json renderer");
159 index
: Rc
::new(RefCell
::new(FxHashMap
::default())),
160 out_path
: options
.output
,
161 cache
: Rc
::new(cache
),
167 fn make_child_renderer(&self) -> Self {
171 /// Inserts an item into the index. This should be used rather than directly calling insert on
172 /// the hashmap because certain items (traits and types) need to have their mappings for trait
173 /// implementations filled out before they're inserted.
174 fn item(&mut self, item
: clean
::Item
) -> Result
<(), Error
> {
175 // Flatten items that recursively store other items
176 item
.kind
.inner_items().for_each(|i
| self.item(i
.clone()).unwrap());
178 let id
= item
.def_id
;
179 if let Some(mut new_item
) = self.convert_item(item
) {
180 if let types
::ItemEnum
::Trait(ref mut t
) = new_item
.inner
{
181 t
.implementors
= self.get_trait_implementors(id
.expect_def_id())
182 } else if let types
::ItemEnum
::Struct(ref mut s
) = new_item
.inner
{
183 s
.impls
= self.get_impls(id
.expect_def_id())
184 } else if let types
::ItemEnum
::Enum(ref mut e
) = new_item
.inner
{
185 e
.impls
= self.get_impls(id
.expect_def_id())
186 } else if let types
::ItemEnum
::Union(ref mut u
) = new_item
.inner
{
187 u
.impls
= self.get_impls(id
.expect_def_id())
189 let removed
= self.index
.borrow_mut().insert(from_item_id(id
), new_item
.clone());
191 // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
192 // to make sure the items are unique. The main place this happens is when an item, is
193 // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod`
194 if let Some(old_item
) = removed
{
195 assert_eq
!(old_item
, new_item
);
202 fn mod_item_in(&mut self, _item
: &clean
::Item
) -> Result
<(), Error
> {
203 unreachable
!("RUN_ON_MODULE = false should never call mod_item_in")
206 fn after_krate(&mut self) -> Result
<(), Error
> {
207 debug
!("Done with crate");
209 for primitive
in Rc
::clone(&self.cache
).primitive_locations
.values() {
210 self.get_impls(*primitive
);
213 let mut index
= (*self.index
).clone().into_inner();
214 index
.extend(self.get_trait_items());
215 // This needs to be the default HashMap for compatibility with the public interface for
217 #[allow(rustc::default_hash_types)]
218 let output
= types
::Crate
{
219 root
: types
::Id(String
::from("0:0")),
220 crate_version
: self.cache
.crate_version
.clone(),
221 includes_private
: self.cache
.document_private
,
222 index
: index
.into_iter().collect(),
228 .chain(self.cache
.external_paths
.clone().into_iter())
229 .map(|(k
, (path
, kind
))| {
231 from_item_id(k
.into()),
233 crate_id
: k
.krate
.as_u32(),
235 kind
: kind
.into_tcx(self.tcx
),
240 external_crates
: self
244 .map(|(crate_num
, external_location
)| {
245 let e
= ExternalCrate { crate_num: *crate_num }
;
248 types
::ExternalCrate
{
249 name
: e
.name(self.tcx
).to_string(),
250 html_root_url
: match external_location
{
251 ExternalLocation
::Remote(s
) => Some(s
.clone()),
258 format_version
: types
::FORMAT_VERSION
,
260 let mut p
= self.out_path
.clone();
261 p
.push(output
.index
.get(&output
.root
).unwrap().name
.clone().unwrap());
262 p
.set_extension("json");
263 let file
= File
::create(&p
).map_err(|error
| Error { error: error.to_string(), file: p }
)?
;
264 serde_json
::ser
::to_writer(&file
, &output
).unwrap();
268 fn cache(&self) -> &Cache
{