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