Skip to content

Commit 788036d

Browse files
authored
Rollup merge of #81287 - CraftSpider:json-crate, r=jyn514,GuillaumeGomez
Split rustdoc JSON types into separately versioned crate For now just an in-tree change. In the future, this may be exposed as a standalone crate with standard semver.
2 parents 0c5fcce + 3aa8456 commit 788036d

File tree

8 files changed

+88
-59
lines changed

8 files changed

+88
-59
lines changed

Cargo.lock

+8
Original file line numberDiff line numberDiff line change
@@ -4392,12 +4392,20 @@ dependencies = [
43924392
"pulldown-cmark 0.8.0",
43934393
"regex",
43944394
"rustc-rayon",
4395+
"rustdoc-json-types",
43954396
"serde",
43964397
"serde_json",
43974398
"smallvec 1.4.2",
43984399
"tempfile",
43994400
]
44004401

4402+
[[package]]
4403+
name = "rustdoc-json-types"
4404+
version = "0.1.0"
4405+
dependencies = [
4406+
"serde",
4407+
]
4408+
44014409
[[package]]
44024410
name = "rustdoc-themes"
44034411
version = "0.1.0"

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ members = [
44
"compiler/rustc",
55
"library/std",
66
"library/test",
7+
"src/rustdoc-json-types",
78
"src/tools/cargotest",
89
"src/tools/clippy",
910
"src/tools/compiletest",

src/librustdoc/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ smallvec = "1.0"
1717
tempfile = "3"
1818
itertools = "0.9"
1919
regex = "1"
20+
rustdoc-json-types = { path = "../rustdoc-json-types" }
2021

2122
[dev-dependencies]
2223
expect-test = "1.0"

src/librustdoc/json/conversions.rs

+37-46
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ use rustc_hir::def::CtorKind;
99
use rustc_span::def_id::{DefId, CRATE_DEF_INDEX};
1010
use rustc_span::Pos;
1111

12+
use rustdoc_json_types::*;
13+
1214
use crate::clean;
1315
use crate::formats::item_type::ItemType;
14-
use crate::json::types::*;
1516
use crate::json::JsonRenderer;
1617

1718
impl JsonRenderer<'_> {
@@ -22,7 +23,7 @@ impl JsonRenderer<'_> {
2223
match *kind {
2324
clean::StrippedItem(_) => None,
2425
kind => Some(Item {
25-
id: def_id.into(),
26+
id: from_def_id(def_id),
2627
crate_id: def_id.krate.as_u32(),
2728
name: name.map(|sym| sym.to_string()),
2829
source: self.convert_span(source),
@@ -32,15 +33,15 @@ impl JsonRenderer<'_> {
3233
.links
3334
.into_iter()
3435
.filter_map(|clean::ItemLink { link, did, .. }| {
35-
did.map(|did| (link, did.into()))
36+
did.map(|did| (link, from_def_id(did)))
3637
})
3738
.collect(),
3839
attrs: attrs
3940
.other_attrs
4041
.iter()
4142
.map(rustc_ast_pretty::pprust::attribute_to_string)
4243
.collect(),
43-
deprecation: deprecation.map(Into::into),
44+
deprecation: deprecation.map(from_deprecation),
4445
kind: item_type.into(),
4546
inner: kind.into(),
4647
}),
@@ -74,19 +75,17 @@ impl JsonRenderer<'_> {
7475
Inherited => Visibility::Default,
7576
Restricted(did) if did.index == CRATE_DEF_INDEX => Visibility::Crate,
7677
Restricted(did) => Visibility::Restricted {
77-
parent: did.into(),
78+
parent: from_def_id(did),
7879
path: self.tcx.def_path(did).to_string_no_crate_verbose(),
7980
},
8081
}
8182
}
8283
}
8384

84-
impl From<rustc_attr::Deprecation> for Deprecation {
85-
fn from(deprecation: rustc_attr::Deprecation) -> Self {
86-
#[rustfmt::skip]
87-
let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
88-
Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
89-
}
85+
crate fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation {
86+
#[rustfmt::skip]
87+
let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation;
88+
Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) }
9089
}
9190

9291
impl From<clean::GenericArgs> for GenericArgs {
@@ -141,10 +140,8 @@ impl From<clean::TypeBindingKind> for TypeBindingKind {
141140
}
142141
}
143142

144-
impl From<DefId> for Id {
145-
fn from(did: DefId) -> Self {
146-
Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
147-
}
143+
crate fn from_def_id(did: DefId) -> Id {
144+
Id(format!("{}:{}", did.krate.as_u32(), u32::from(did.index)))
148145
}
149146

150147
impl From<clean::ItemKind> for ItemEnum {
@@ -199,7 +196,7 @@ impl From<clean::Struct> for Struct {
199196
fn from(struct_: clean::Struct) -> Self {
200197
let clean::Struct { struct_type, generics, fields, fields_stripped } = struct_;
201198
Struct {
202-
struct_type: struct_type.into(),
199+
struct_type: from_ctor_kind(struct_type),
203200
generics: generics.into(),
204201
fields_stripped,
205202
fields: ids(fields),
@@ -221,13 +218,11 @@ impl From<clean::Union> for Struct {
221218
}
222219
}
223220

224-
impl From<CtorKind> for StructType {
225-
fn from(struct_type: CtorKind) -> Self {
226-
match struct_type {
227-
CtorKind::Fictive => StructType::Plain,
228-
CtorKind::Fn => StructType::Tuple,
229-
CtorKind::Const => StructType::Unit,
230-
}
221+
crate fn from_ctor_kind(struct_type: CtorKind) -> StructType {
222+
match struct_type {
223+
CtorKind::Fictive => StructType::Plain,
224+
CtorKind::Fn => StructType::Tuple,
225+
CtorKind::Const => StructType::Unit,
231226
}
232227
}
233228

@@ -310,22 +305,20 @@ impl From<clean::GenericBound> for GenericBound {
310305
GenericBound::TraitBound {
311306
trait_: trait_.into(),
312307
generic_params: generic_params.into_iter().map(Into::into).collect(),
313-
modifier: modifier.into(),
308+
modifier: from_trait_bound_modifier(modifier),
314309
}
315310
}
316311
Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()),
317312
}
318313
}
319314
}
320315

321-
impl From<rustc_hir::TraitBoundModifier> for TraitBoundModifier {
322-
fn from(modifier: rustc_hir::TraitBoundModifier) -> Self {
323-
use rustc_hir::TraitBoundModifier::*;
324-
match modifier {
325-
None => TraitBoundModifier::None,
326-
Maybe => TraitBoundModifier::Maybe,
327-
MaybeConst => TraitBoundModifier::MaybeConst,
328-
}
316+
crate fn from_trait_bound_modifier(modifier: rustc_hir::TraitBoundModifier) -> TraitBoundModifier {
317+
use rustc_hir::TraitBoundModifier::*;
318+
match modifier {
319+
None => TraitBoundModifier::None,
320+
Maybe => TraitBoundModifier::Maybe,
321+
MaybeConst => TraitBoundModifier::MaybeConst,
329322
}
330323
}
331324

@@ -335,7 +328,7 @@ impl From<clean::Type> for Type {
335328
match ty {
336329
ResolvedPath { path, param_names, did, is_generic: _ } => Type::ResolvedPath {
337330
name: path.whole_name(),
338-
id: did.into(),
331+
id: from_def_id(did),
339332
args: path.segments.last().map(|args| Box::new(args.clone().args.into())),
340333
param_names: param_names
341334
.map(|v| v.into_iter().map(Into::into).collect())
@@ -470,7 +463,7 @@ impl From<clean::VariantStruct> for Struct {
470463
fn from(struct_: clean::VariantStruct) -> Self {
471464
let clean::VariantStruct { struct_type, fields, fields_stripped } = struct_;
472465
Struct {
473-
struct_type: struct_type.into(),
466+
struct_type: from_ctor_kind(struct_type),
474467
generics: Default::default(),
475468
fields_stripped,
476469
fields: ids(fields),
@@ -497,13 +490,13 @@ impl From<clean::Import> for Import {
497490
Simple(s) => Import {
498491
span: import.source.path.whole_name(),
499492
name: s.to_string(),
500-
id: import.source.did.map(Into::into),
493+
id: import.source.did.map(from_def_id),
501494
glob: false,
502495
},
503496
Glob => Import {
504497
span: import.source.path.whole_name(),
505498
name: import.source.path.last_name().to_string(),
506-
id: import.source.did.map(Into::into),
499+
id: import.source.did.map(from_def_id),
507500
glob: true,
508501
},
509502
}
@@ -513,20 +506,18 @@ impl From<clean::Import> for Import {
513506
impl From<clean::ProcMacro> for ProcMacro {
514507
fn from(mac: clean::ProcMacro) -> Self {
515508
ProcMacro {
516-
kind: mac.kind.into(),
509+
kind: from_macro_kind(mac.kind),
517510
helpers: mac.helpers.iter().map(|x| x.to_string()).collect(),
518511
}
519512
}
520513
}
521514

522-
impl From<rustc_span::hygiene::MacroKind> for MacroKind {
523-
fn from(kind: rustc_span::hygiene::MacroKind) -> Self {
524-
use rustc_span::hygiene::MacroKind::*;
525-
match kind {
526-
Bang => MacroKind::Bang,
527-
Attr => MacroKind::Attr,
528-
Derive => MacroKind::Derive,
529-
}
515+
crate fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind {
516+
use rustc_span::hygiene::MacroKind::*;
517+
match kind {
518+
Bang => MacroKind::Bang,
519+
Attr => MacroKind::Attr,
520+
Derive => MacroKind::Derive,
530521
}
531522
}
532523

@@ -599,5 +590,5 @@ impl From<ItemType> for ItemKind {
599590
}
600591

601592
fn ids(items: impl IntoIterator<Item = clean::Item>) -> Vec<Id> {
602-
items.into_iter().filter(|x| !x.is_stripped()).map(|i| i.def_id.into()).collect()
593+
items.into_iter().filter(|x| !x.is_stripped()).map(|i| from_def_id(i.def_id)).collect()
603594
}

src/librustdoc/json/mod.rs

+13-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
//! docs for usage and details.
66
77
mod conversions;
8-
pub mod types;
98

109
use std::cell::RefCell;
1110
use std::fs::File;
@@ -17,12 +16,15 @@ use rustc_middle::ty::TyCtxt;
1716
use rustc_session::Session;
1817
use rustc_span::edition::Edition;
1918

19+
use rustdoc_json_types as types;
20+
2021
use crate::clean;
2122
use crate::config::{RenderInfo, RenderOptions};
2223
use crate::error::Error;
2324
use crate::formats::cache::Cache;
2425
use crate::formats::FormatRenderer;
2526
use crate::html::render::cache::ExternalLocation;
27+
use crate::json::conversions::from_def_id;
2628

2729
#[derive(Clone)]
2830
crate struct JsonRenderer<'tcx> {
@@ -50,7 +52,7 @@ impl JsonRenderer<'_> {
5052
.map(|i| {
5153
let item = &i.impl_item;
5254
self.item(item.clone()).unwrap();
53-
item.def_id.into()
55+
from_def_id(item.def_id)
5456
})
5557
.collect()
5658
})
@@ -68,7 +70,7 @@ impl JsonRenderer<'_> {
6870
let item = &i.impl_item;
6971
if item.def_id.is_local() {
7072
self.item(item.clone()).unwrap();
71-
Some(item.def_id.into())
73+
Some(from_def_id(item.def_id))
7274
} else {
7375
None
7476
}
@@ -87,9 +89,9 @@ impl JsonRenderer<'_> {
8789
if !id.is_local() {
8890
trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap());
8991
Some((
90-
id.into(),
92+
from_def_id(id),
9193
types::Item {
92-
id: id.into(),
94+
id: from_def_id(id),
9395
crate_id: id.krate.as_u32(),
9496
name: self
9597
.cache
@@ -163,7 +165,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
163165
} else if let types::ItemEnum::EnumItem(ref mut e) = new_item.inner {
164166
e.impls = self.get_impls(id)
165167
}
166-
let removed = self.index.borrow_mut().insert(id.into(), new_item.clone());
168+
let removed = self.index.borrow_mut().insert(from_def_id(id), new_item.clone());
167169
// FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check
168170
// to make sure the items are unique.
169171
if let Some(old_item) = removed {
@@ -203,11 +205,14 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
203205
debug!("Done with crate");
204206
let mut index = (*self.index).clone().into_inner();
205207
index.extend(self.get_trait_items());
208+
// This needs to be the default HashMap for compatibility with the public interface for
209+
// rustdoc-json
210+
#[allow(rustc::default_hash_types)]
206211
let output = types::Crate {
207212
root: types::Id(String::from("0:0")),
208213
crate_version: krate.version.clone(),
209214
includes_private: self.cache.document_private,
210-
index,
215+
index: index.into_iter().collect(),
211216
paths: self
212217
.cache
213218
.paths
@@ -216,7 +221,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
216221
.chain(self.cache.external_paths.clone().into_iter())
217222
.map(|(k, (path, kind))| {
218223
(
219-
k.into(),
224+
from_def_id(k),
220225
types::ItemSummary { crate_id: k.krate.as_u32(), path, kind: kind.into() },
221226
)
222227
})

src/rustdoc-json-types/Cargo.toml

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "rustdoc-json-types"
3+
version = "0.1.0"
4+
authors = ["The Rust Project Developers"]
5+
edition = "2018"
6+
7+
[lib]
8+
path = "lib.rs"
9+
10+
[dependencies]
11+
serde = { version = "1.0", features = ["derive"] }

src/rustdoc-json-types/README.md

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Rustdoc JSON Types
2+
3+
This crate exposes the Rustdoc JSON API as a set of types with serde implementations.
4+
These types are part of the public interface of the rustdoc JSON output, and making them
5+
their own crate allows them to be versioned and distributed without having to depend on
6+
any rustc/rustdoc internals. This way, consumers can rely on this crate for both documentation
7+
of the output, and as a way to read the output easily, and its versioning is intended to
8+
follow semver guarantees about the version of the format. JSON format X will always be
9+
compatible with rustdoc-json-types version N.
10+
11+
Currently, this crate is only used by rustdoc itself. Upon the stabilization of
12+
rustdoc-json, it may be distributed separately for consumers of the API.

src/librustdoc/json/types.rs renamed to src/rustdoc-json-types/lib.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
//! These types are the public API exposed through the `--output-format json` flag. The [`Crate`]
44
//! struct is the root of the JSON blob and all other items are contained within.
55
6+
use std::collections::HashMap;
67
use std::path::PathBuf;
78

8-
use rustc_data_structures::fx::FxHashMap;
99
use serde::{Deserialize, Serialize};
1010

1111
/// A `Crate` is the root of the emitted JSON blob. It contains all type/documentation information
@@ -21,11 +21,11 @@ pub struct Crate {
2121
pub includes_private: bool,
2222
/// A collection of all items in the local crate as well as some external traits and their
2323
/// items that are referenced locally.
24-
pub index: FxHashMap<Id, Item>,
24+
pub index: HashMap<Id, Item>,
2525
/// Maps IDs to fully qualified paths and other info helpful for generating links.
26-
pub paths: FxHashMap<Id, ItemSummary>,
26+
pub paths: HashMap<Id, ItemSummary>,
2727
/// Maps `crate_id` of items to a crate name and html_root_url if it exists.
28-
pub external_crates: FxHashMap<u32, ExternalCrate>,
28+
pub external_crates: HashMap<u32, ExternalCrate>,
2929
/// A single version number to be used in the future when making backwards incompatible changes
3030
/// to the JSON output.
3131
pub format_version: u32,
@@ -72,7 +72,7 @@ pub struct Item {
7272
/// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
7373
pub docs: Option<String>,
7474
/// This mapping resolves [intra-doc links](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md) from the docstring to their IDs
75-
pub links: FxHashMap<String, Id>,
75+
pub links: HashMap<String, Id>,
7676
/// Stringified versions of the attributes on this item (e.g. `"#[inline]"`)
7777
pub attrs: Vec<String>,
7878
pub deprecation: Option<Deprecation>,

0 commit comments

Comments
 (0)