]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/json/mod.rs
Merge branch 'debian/experimental2' into debian/experimental
[rustc.git] / src / librustdoc / json / mod.rs
1 //! Rustdoc's JSON backend
2 //!
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.
6
7 mod conversions;
8
9 use std::cell::RefCell;
10 use std::fs::File;
11 use std::path::PathBuf;
12 use std::rc::Rc;
13
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_middle::ty::TyCtxt;
16 use rustc_session::Session;
17 use rustc_span::edition::Edition;
18
19 use rustdoc_json_types as types;
20
21 use crate::clean;
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;
28
29 #[derive(Clone)]
30 crate struct JsonRenderer<'tcx> {
31 tcx: TyCtxt<'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.
36 out_path: PathBuf,
37 cache: Rc<Cache>,
38 }
39
40 impl JsonRenderer<'tcx> {
41 fn sess(&self) -> &'tcx Session {
42 self.tcx.sess
43 }
44
45 fn get_trait_implementors(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
46 Rc::clone(&self.cache)
47 .implementors
48 .get(&id)
49 .map(|implementors| {
50 implementors
51 .iter()
52 .map(|i| {
53 let item = &i.impl_item;
54 self.item(item.clone()).unwrap();
55 from_def_id(item.def_id)
56 })
57 .collect()
58 })
59 .unwrap_or_default()
60 }
61
62 fn get_impls(&mut self, id: rustc_span::def_id::DefId) -> Vec<types::Id> {
63 Rc::clone(&self.cache)
64 .impls
65 .get(&id)
66 .map(|impls| {
67 impls
68 .iter()
69 .filter_map(|i| {
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))
74 } else {
75 None
76 }
77 })
78 .collect()
79 })
80 .unwrap_or_default()
81 }
82
83 fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> {
84 Rc::clone(&self.cache)
85 .traits
86 .iter()
87 .filter_map(|(&id, trait_item)| {
88 // only need to synthesize items for external traits
89 if !id.is_local() {
90 let trait_item = &trait_item.trait_;
91 trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
92 Some((
93 from_def_id(id),
94 types::Item {
95 id: from_def_id(id),
96 crate_id: id.krate.as_u32(),
97 name: self
98 .cache
99 .paths
100 .get(&id)
101 .unwrap_or_else(|| {
102 self.cache
103 .external_paths
104 .get(&id)
105 .expect("Trait should either be in local or external paths")
106 })
107 .0
108 .last()
109 .map(Clone::clone),
110 visibility: types::Visibility::Public,
111 inner: types::ItemEnum::Trait(trait_item.clone().into()),
112 source: None,
113 docs: Default::default(),
114 links: Default::default(),
115 attrs: Default::default(),
116 deprecation: Default::default(),
117 },
118 ))
119 } else {
120 None
121 }
122 })
123 .collect()
124 }
125 }
126
127 impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
128 fn descr() -> &'static str {
129 "json"
130 }
131
132 fn init(
133 krate: clean::Crate,
134 options: RenderOptions,
135 _edition: Edition,
136 cache: Cache,
137 tcx: TyCtxt<'tcx>,
138 ) -> Result<(Self, clean::Crate), Error> {
139 debug!("Initializing json renderer");
140 Ok((
141 JsonRenderer {
142 tcx,
143 index: Rc::new(RefCell::new(FxHashMap::default())),
144 out_path: options.output,
145 cache: Rc::new(cache),
146 },
147 krate,
148 ))
149 }
150
151 fn make_child_renderer(&self) -> Self {
152 self.clone()
153 }
154
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());
161
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)
170 }
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);
176 }
177 }
178
179 Ok(())
180 }
181
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 {
186 match &*item.kind {
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()),
191 _ => {}
192 }
193 }
194 }
195 self.item(item.clone()).unwrap();
196 Ok(())
197 }
198
199 fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> {
200 Ok(())
201 }
202
203 fn after_krate(
204 &mut self,
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
212 // rustdoc-json
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(),
219 paths: self
220 .cache
221 .paths
222 .clone()
223 .into_iter()
224 .chain(self.cache.external_paths.clone().into_iter())
225 .map(|(k, (path, kind))| {
226 (
227 from_def_id(k),
228 types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
229 )
230 })
231 .collect(),
232 external_crates: self
233 .cache
234 .extern_locations
235 .iter()
236 .map(|(k, v)| {
237 (
238 k.as_u32(),
239 types::ExternalCrate {
240 name: v.0.to_string(),
241 html_root_url: match &v.2 {
242 ExternalLocation::Remote(s) => Some(s.clone()),
243 _ => None,
244 },
245 },
246 )
247 })
248 .collect(),
249 format_version: 4,
250 };
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();
256 Ok(())
257 }
258
259 fn cache(&self) -> &Cache {
260 &self.cache
261 }
262 }