Skip to main content

rustdoc/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
7mod conversions;
8mod ids;
9mod import_finder;
10
11use std::cell::RefCell;
12use std::fs::{File, create_dir_all};
13use std::io::{BufWriter, Write, stdout};
14use std::path::PathBuf;
15use std::rc::Rc;
16
17use rustc_hir::def::DefKind;
18use rustc_hir::def_id::{DefId, DefIdSet};
19use rustc_middle::ty::TyCtxt;
20use rustc_session::Session;
21use rustc_span::def_id::LOCAL_CRATE;
22use rustdoc_json_types as types;
23// It's important to use the FxHashMap from rustdoc_json_types here, instead of
24// the one from rustc_data_structures, as they're different types due to sysroots.
25// See #110051 and #127456 for details
26use rustdoc_json_types::FxHashMap;
27use tracing::{debug, trace};
28
29use crate::clean::ItemKind;
30use crate::clean::types::{ExternalCrate, ExternalLocation};
31use crate::config::{EmitType, RenderOptions};
32use crate::docfs::PathError;
33use crate::error::Error;
34use crate::formats::FormatRenderer;
35use crate::formats::cache::Cache;
36use crate::formats::item_type::ItemType;
37use crate::json::conversions::IntoJson;
38use crate::passes::collect_intra_doc_links::UrlFragment;
39use crate::{clean, try_err};
40
41pub(crate) struct JsonRenderer<'tcx> {
42    tcx: TyCtxt<'tcx>,
43    /// A mapping of IDs that contains all local items for this crate which gets output as a top
44    /// level field of the JSON blob.
45    index: FxHashMap<types::Id, types::Item>,
46    /// The directory where the JSON blob should be written to.
47    ///
48    /// If this is `None`, the blob will be printed to `stdout` instead.
49    out_dir: Option<PathBuf>,
50    cache: Rc<Cache>,
51    imported_items: DefIdSet,
52    id_interner: RefCell<ids::IdInterner>,
53}
54
55impl<'tcx> JsonRenderer<'tcx> {
56    fn sess(&self) -> &'tcx Session {
57        self.tcx.sess
58    }
59
60    fn get_trait_implementors(&mut self, id: DefId) -> Vec<types::Id> {
61        Rc::clone(&self.cache)
62            .implementors
63            .get(&id)
64            .map(|implementors| {
65                implementors
66                    .iter()
67                    .map(|i| {
68                        let item = &i.impl_item;
69                        self.item(item).unwrap();
70                        self.id_from_item(item)
71                    })
72                    .collect()
73            })
74            .unwrap_or_default()
75    }
76
77    fn get_impls(&mut self, id: DefId) -> Vec<types::Id> {
78        Rc::clone(&self.cache)
79            .impls
80            .get(&id)
81            .map(|impls| {
82                impls
83                    .iter()
84                    .filter_map(|i| {
85                        let item = &i.impl_item;
86
87                        // HACK(hkmatsumoto): For impls of primitive types, we index them
88                        // regardless of whether they're local. This is because users can
89                        // document primitive items in an arbitrary crate by using
90                        // `rustc_doc_primitive`.
91                        let mut is_primitive_impl = false;
92                        if let clean::types::ItemKind::ImplItem(ref impl_) = item.kind
93                            && impl_.trait_.is_none()
94                            && let clean::types::Type::Primitive(_) = impl_.for_
95                        {
96                            is_primitive_impl = true;
97                        }
98
99                        if item.item_id.is_local() || is_primitive_impl {
100                            self.item(item).unwrap();
101                            Some(self.id_from_item(item))
102                        } else {
103                            None
104                        }
105                    })
106                    .collect()
107            })
108            .unwrap_or_default()
109    }
110
111    fn paths(&self) -> FxHashMap<types::Id, types::ItemSummary> {
112        let mut paths = self
113            .cache
114            .paths
115            .iter()
116            .chain(&self.cache.external_paths)
117            .map(|(&k, &(ref path, kind))| {
118                (
119                    self.id_from_item_default(k.into()),
120                    types::ItemSummary {
121                        crate_id: k.krate.as_u32(),
122                        path: path.iter().map(|s| s.to_string()).collect(),
123                        kind: kind.into_json(self),
124                    },
125                )
126            })
127            .collect();
128
129        self.add_intra_doc_link_paths(&mut paths);
130        paths
131    }
132
133    fn add_intra_doc_link_paths(&self, paths: &mut FxHashMap<types::Id, types::ItemSummary>) {
134        // The link target IDs were already interned when the `links` maps were emitted.
135        // This only fills missing summaries in `paths`, where JSON object order is not meaningful.
136        #[allow(rustc::potential_query_instability)]
137        let links = self.cache.intra_doc_links.values();
138        for link in links.flatten() {
139            let Some(UrlFragment::Item(item_id)) = link.fragment.as_ref() else {
140                continue;
141            };
142            let item_id = *item_id;
143            let id = self.id_from_item_default(item_id.into());
144
145            if paths.contains_key(&id) || (item_id.is_local() && !self.index.contains_key(&id)) {
146                continue;
147            }
148
149            let path = self.path_for_link_target(link.page_id, item_id);
150            let kind = ItemType::from_def_id(item_id, self.tcx);
151            paths.insert(
152                id,
153                types::ItemSummary {
154                    crate_id: item_id.krate.as_u32(),
155                    path,
156                    kind: kind.into_json(self),
157                },
158            );
159        }
160    }
161
162    fn path_for_link_target(&self, page_id: DefId, item_id: DefId) -> Vec<String> {
163        let parent_id = self.tcx.parent(item_id);
164        // Inherent items have an unnamed impl parent, while variant fields have one extra named
165        // parent between themselves and their page.
166        let (mut path, variant_id) = match self.tcx.def_kind(parent_id) {
167            DefKind::Impl { .. } => (
168                self.cached_path(page_id).expect("intra-doc link page should have a cached path"),
169                None,
170            ),
171            DefKind::Variant => {
172                (self.path_for_named_item(self.tcx.parent(parent_id)), Some(parent_id))
173            }
174            _ => (self.path_for_named_item(parent_id), None),
175        };
176
177        if let Some(variant_id) = variant_id {
178            path.push(self.tcx.item_name(variant_id).to_string());
179        }
180        path.push(self.tcx.item_name(item_id).to_string());
181        path
182    }
183
184    fn path_for_named_item(&self, item_id: DefId) -> Vec<String> {
185        self.cached_path(item_id).unwrap_or_else(|| {
186            let kind = ItemType::from_def_id(item_id, self.tcx);
187            clean::inline::get_item_path(self.tcx, item_id, kind)
188                .into_iter()
189                .map(|name| name.to_string())
190                .collect()
191        })
192    }
193
194    fn cached_path(&self, item_id: DefId) -> Option<Vec<String>> {
195        self.cache
196            .paths
197            .get(&item_id)
198            .or_else(|| self.cache.external_paths.get(&item_id))
199            .map(|(path, _)| path.iter().map(|name| name.to_string()).collect())
200    }
201}
202
203impl<'tcx> JsonRenderer<'tcx> {
204    pub(crate) fn init(
205        krate: clean::Crate,
206        options: RenderOptions,
207        cache: Cache,
208        tcx: TyCtxt<'tcx>,
209    ) -> Result<(Self, clean::Crate), Error> {
210        debug!("Initializing json renderer");
211
212        let (krate, imported_items) = import_finder::get_imports(krate);
213
214        Ok((
215            JsonRenderer {
216                tcx,
217                index: FxHashMap::default(),
218                out_dir: if options.output_to_stdout { None } else { Some(options.output) },
219                cache: Rc::new(cache),
220                imported_items,
221                id_interner: Default::default(),
222            },
223            krate,
224        ))
225    }
226}
227
228impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
229    const DESCR: &'static str = "json";
230    const RUN_ON_MODULE: bool = false;
231    const NON_STATIC_FILE_EMIT_TYPE: EmitType = EmitType::IrJsonFiles;
232
233    type ModuleData = ();
234
235    fn save_module_data(&mut self) -> Self::ModuleData {
236        unreachable!("RUN_ON_MODULE = false, should never call save_module_data")
237    }
238    fn restore_module_data(&mut self, _info: Self::ModuleData) {
239        unreachable!("RUN_ON_MODULE = false, should never call set_back_info")
240    }
241
242    /// Inserts an item into the index. This should be used rather than directly calling insert on
243    /// the hashmap because certain items (traits and types) need to have their mappings for trait
244    /// implementations filled out before they're inserted.
245    fn item(&mut self, item: &clean::Item) -> Result<(), Error> {
246        use std::collections::hash_map::Entry;
247
248        let item_type = item.type_();
249        let item_name = item.name;
250        trace!("rendering {item_type} {item_name:?}");
251
252        // Flatten items that recursively store other items. We include orphaned items from
253        // stripped modules and etc that are otherwise reachable.
254        if let ItemKind::StrippedItem(inner) = &item.kind {
255            inner.inner_items().for_each(|i| self.item(i).unwrap());
256        }
257
258        // Flatten items that recursively store other items
259        item.kind.inner_items().for_each(|i| self.item(i).unwrap());
260
261        let item_id = item.item_id;
262        if let Some(mut new_item) = self.convert_item(item) {
263            let can_be_ignored = match new_item.inner {
264                types::ItemEnum::Trait(ref mut t) => {
265                    t.implementations = self.get_trait_implementors(item_id.expect_def_id());
266                    false
267                }
268                types::ItemEnum::Struct(ref mut s) => {
269                    s.impls = self.get_impls(item_id.expect_def_id());
270                    false
271                }
272                types::ItemEnum::Enum(ref mut e) => {
273                    e.impls = self.get_impls(item_id.expect_def_id());
274                    false
275                }
276                types::ItemEnum::Union(ref mut u) => {
277                    u.impls = self.get_impls(item_id.expect_def_id());
278                    false
279                }
280                types::ItemEnum::Primitive(ref mut p) => {
281                    p.impls = self.get_impls(item_id.expect_def_id());
282                    false
283                }
284
285                types::ItemEnum::Function(_)
286                | types::ItemEnum::Module(_)
287                | types::ItemEnum::Use(_)
288                | types::ItemEnum::AssocConst { .. }
289                | types::ItemEnum::AssocType { .. } => true,
290                types::ItemEnum::ExternCrate { .. }
291                | types::ItemEnum::StructField(_)
292                | types::ItemEnum::Variant(_)
293                | types::ItemEnum::TraitAlias(_)
294                | types::ItemEnum::Impl(_)
295                | types::ItemEnum::TypeAlias(_)
296                | types::ItemEnum::Constant { .. }
297                | types::ItemEnum::Static(_)
298                | types::ItemEnum::ExternType
299                | types::ItemEnum::Macro(_)
300                | types::ItemEnum::ProcMacro(_) => false,
301            };
302
303            // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
304            // to make sure the items are unique. The main place this happens is when an item, is
305            // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod`
306            match self.index.entry(new_item.id) {
307                Entry::Vacant(entry) => {
308                    entry.insert(new_item);
309                }
310                Entry::Occupied(mut entry) => {
311                    // In case of generic implementations (like `impl<T> Trait for T {}`), all the
312                    // inner items will be duplicated so we can ignore if they are slightly
313                    // different.
314                    let old_item = entry.get_mut();
315                    if !can_be_ignored {
316                        assert_eq!(*old_item, new_item);
317                    }
318                    trace!("replaced {old_item:?}\nwith {new_item:?}");
319                    *old_item = new_item;
320                }
321            }
322        }
323
324        trace!("done rendering {item_type} {item_name:?}");
325        Ok(())
326    }
327
328    fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> {
329        unreachable!("RUN_ON_MODULE = false, should never call mod_item_in")
330    }
331
332    fn after_krate(self) -> Result<(), Error> {
333        debug!("Done with crate");
334
335        let e = ExternalCrate { crate_num: LOCAL_CRATE };
336        let sess = self.sess();
337
338        // Note that tcx.rust_target_features is inappropriate here because rustdoc tries to run for
339        // multiple targets: https://github.com/rust-lang/rust/pull/137632
340        //
341        // We want to describe a single target, so pass tcx.sess rather than tcx.
342        let target = conversions::target(sess);
343
344        debug!("Constructing Output");
345        let paths = self.paths();
346        let output_crate = types::Crate {
347            root: self.id_from_item_default(e.def_id().into()),
348            crate_version: self.cache.crate_version.clone(),
349            includes_private: self.cache.document_private,
350            paths,
351            external_crates: self
352                .cache
353                .extern_locations
354                .iter()
355                .map(|(crate_num, external_location)| {
356                    let e = ExternalCrate { crate_num: *crate_num };
357                    (
358                        crate_num.as_u32(),
359                        types::ExternalCrate {
360                            name: e.name(self.tcx).to_string(),
361                            html_root_url: match external_location {
362                                // FIXME: relative extern URLs are not resolved here
363                                ExternalLocation::Remote { url, .. } => Some(url.clone()),
364                                _ => None,
365                            },
366                            path: self
367                                .tcx
368                                .used_crate_source(*crate_num)
369                                .paths()
370                                .next()
371                                .expect("crate should have at least 1 path")
372                                .clone(),
373                        },
374                    )
375                })
376                .collect(),
377            // Be careful to not clone the `index`, it is big.
378            index: self.index,
379            target,
380            format_version: types::FORMAT_VERSION,
381        };
382        if let Some(ref out_dir) = self.out_dir {
383            try_err!(create_dir_all(out_dir), out_dir);
384
385            let mut p = out_dir.clone();
386            p.push(output_crate.index.get(&output_crate.root).unwrap().name.clone().unwrap());
387            p.set_extension("json");
388
389            serialize_and_write(
390                sess,
391                output_crate,
392                try_err!(File::create_buffered(&p), p),
393                &p.display().to_string(),
394            )
395        } else {
396            serialize_and_write(sess, output_crate, BufWriter::new(stdout().lock()), "<stdout>")
397        }
398    }
399}
400
401fn serialize_and_write<T: Write>(
402    sess: &Session,
403    output_crate: types::Crate,
404    mut writer: BufWriter<T>,
405    path: &str,
406) -> Result<(), Error> {
407    sess.time("rustdoc_json_serialize_and_write", || {
408        try_err!(
409            serde_json::ser::to_writer(&mut writer, &output_crate).map_err(|e| e.to_string()),
410            path
411        );
412        try_err!(writer.flush(), path);
413        Ok(())
414    })
415}
416
417// Some nodes are used a lot. Make sure they don't unintentionally get bigger.
418//
419// These assertions are here, not in `src/rustdoc-json-types/lib.rs` where the types are defined,
420// because we have access to `static_assert_size` here.
421#[cfg(target_pointer_width = "64")]
422mod size_asserts {
423    use rustc_data_structures::static_assert_size;
424
425    use super::types::*;
426    // tidy-alphabetical-start
427    static_assert_size!(AssocItemConstraint, 112);
428    static_assert_size!(Crate, 184);
429    static_assert_size!(FunctionPointer, 168);
430    static_assert_size!(GenericArg, 80);
431    static_assert_size!(GenericArgs, 104);
432    static_assert_size!(GenericBound, 72);
433    static_assert_size!(GenericParamDef, 136);
434    static_assert_size!(Impl, 304);
435    static_assert_size!(ItemSummary, 32);
436    static_assert_size!(PolyTrait, 64);
437    static_assert_size!(PreciseCapturingArg, 32);
438    static_assert_size!(TargetFeature, 80);
439    static_assert_size!(Type, 80);
440    static_assert_size!(WherePredicate, 160);
441    // tidy-alphabetical-end
442
443    // These contains a `PathBuf`, which is different sizes on different OSes.
444    static_assert_size!(Item, 544 + size_of::<std::path::PathBuf>());
445    static_assert_size!(ExternalCrate, 48 + size_of::<std::path::PathBuf>());
446}