Skip to content

Commit 629a283

Browse files
Rollup merge of #149043 - aDotInTheVoid:is-this-real-is-this-out-of-spite-does-it-matter, r=GuillaumeGomez
rustdoc-json: add rlib path to ExternalCrate to enable robust crate resolution Historically, it's not been possible to robustly resolve a cross-crate item in rustdoc-json. If you had a `Id` that wasn't in `Crate::index` (because it was defined in a different crate), you could only look it up it `Crate::paths`. But there, you don't get the full information, only an `ItemSummary`. This tells you the `path` and the `crate_id`. But knowing the `crate_id` isn't enough to be able to build/find the rustdoc-json output with this item. It's only use is to get a `ExternalCrate` (via `Crate::external_crates`). But that only tells you the `name` (as a string). This isn't enough to uniquely identify a crate, as there could be multiple versions/features [^1] [^2]. This was originally proposed to be solved via `@LukeMathWalker's` `--orchestrator-id` proposal (rust-lang/compiler-team#635). But that requires invasive changes to cargo/rustc. This PR instead implements `@Urgau's` proposal to re-use the path to a crate's rmeta/rlib as a unique identifer. Callers can use that to determine which package it corresponds to in the language of the build-system above rustc. E.g. for cargo, `cargo rustdoc --message-format=json --output-format=json -Zunstable-options`). (Once you've found the right external crate's rustdoc-json output, you still need to resolve the path->id in that crate. But that's """just""" a matter of walking the module tree. We should probably still make that nicer (by, for example, allowing sharing `Id`s between rustdoc-json document), but that's a future concern) For some notes from RustWeek 2025, where this was designed, see https://hackmd.io/0jkdguobTnW7nXoGKAxfEQ CC `@obi1kenobi` (who wants this for cargo-semver-checks [^3]), `@epage` (who's conversations on what and wasn't possible with cargo informed taking this approach to solve this problem) r? `@GuillaumeGomez` ## TODO: - [x] Docs: [Done](https://github.com/rust-lang/rust/compare/e4cdd0c24a994fed354081b5f907680a11f2ddc5..457ed4edb184997d5d6f879c6a220bc4d69ff6fd) - [x] Tests: [Done](https://github.com/rust-lang/rust/compare/2e1b954dc52bf7e5a6e9311394df760db37d383f..4d00c1a7ee5e03d1e78801cc01a85dac08ab603b) [^1]: rust-lang/compiler-team#635 (comment) § Problem [^2]: https://rust-lang.zulipchat.com/#narrow/channel/266220-t-rustdoc/topic/Identifying.20external.20crates.20in.20Rustdoc.20JSON/with/352701211 [^3]: obi1kenobi/cargo-semver-checks#638
2 parents 110471b + 361af82 commit 629a283

File tree

9 files changed

+124
-6
lines changed

9 files changed

+124
-6
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3336,6 +3336,7 @@ dependencies = [
33363336
"libc",
33373337
"object 0.37.3",
33383338
"regex",
3339+
"rustdoc-json-types",
33393340
"serde_json",
33403341
"similar",
33413342
"wasmparser 0.236.1",

src/librustdoc/json/mod.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,13 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
302302
ExternalLocation::Remote(s) => Some(s.clone()),
303303
_ => None,
304304
},
305+
path: self
306+
.tcx
307+
.used_crate_source(*crate_num)
308+
.paths()
309+
.next()
310+
.expect("crate should have at least 1 path")
311+
.clone(),
305312
},
306313
)
307314
})
@@ -339,20 +346,21 @@ mod size_asserts {
339346
// tidy-alphabetical-start
340347
static_assert_size!(AssocItemConstraint, 112);
341348
static_assert_size!(Crate, 184);
342-
static_assert_size!(ExternalCrate, 48);
343349
static_assert_size!(FunctionPointer, 168);
344350
static_assert_size!(GenericArg, 80);
345351
static_assert_size!(GenericArgs, 104);
346352
static_assert_size!(GenericBound, 72);
347353
static_assert_size!(GenericParamDef, 136);
348354
static_assert_size!(Impl, 304);
349-
// `Item` contains a `PathBuf`, which is different sizes on different OSes.
350-
static_assert_size!(Item, 528 + size_of::<std::path::PathBuf>());
351355
static_assert_size!(ItemSummary, 32);
352356
static_assert_size!(PolyTrait, 64);
353357
static_assert_size!(PreciseCapturingArg, 32);
354358
static_assert_size!(TargetFeature, 80);
355359
static_assert_size!(Type, 80);
356360
static_assert_size!(WherePredicate, 160);
357361
// tidy-alphabetical-end
362+
363+
// These contains a `PathBuf`, which is different sizes on different OSes.
364+
static_assert_size!(Item, 528 + size_of::<std::path::PathBuf>());
365+
static_assert_size!(ExternalCrate, 48 + size_of::<std::path::PathBuf>());
358366
}

src/rustdoc-json-types/lib.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ pub type FxHashMap<K, V> = HashMap<K, V>; // re-export for use in src/librustdoc
3737
// will instead cause conflicts. See #94591 for more. (This paragraph and the "Latest feature" line
3838
// are deliberately not in a doc comment, because they need not be in public docs.)
3939
//
40-
// Latest feature: Add `ItemKind::Attribute`.
41-
pub const FORMAT_VERSION: u32 = 56;
40+
// Latest feature: Add `ExternCrate::path`.
41+
pub const FORMAT_VERSION: u32 = 57;
4242

4343
/// The root of the emitted JSON blob.
4444
///
@@ -135,6 +135,12 @@ pub struct ExternalCrate {
135135
pub name: String,
136136
/// The root URL at which the crate's documentation lives.
137137
pub html_root_url: Option<String>,
138+
139+
/// A path from where this crate was loaded.
140+
///
141+
/// This will typically be a `.rlib` or `.rmeta`. It can be used to determine which crate
142+
/// this was in terms of whatever build-system invoked rustc.
143+
pub path: PathBuf,
138144
}
139145

140146
/// Information about an external (not defined in the local crate) [`Item`].

src/tools/run-make-support/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ wasmparser = { version = "0.236", default-features = false, features = ["std", "
2222

2323
# Shared with bootstrap and compiletest
2424
build_helper = { path = "../../build_helper" }
25+
# Shared with rustdoc
26+
rustdoc-json-types = { path = "../../rustdoc-json-types" }
2527

2628
[lib]
2729
crate-type = ["lib", "dylib"]

src/tools/run-make-support/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ pub mod rfs {
3434
}
3535

3636
// Re-exports of third-party library crates.
37-
pub use {bstr, gimli, libc, object, regex, serde_json, similar, wasmparser};
37+
pub use {bstr, gimli, libc, object, regex, rustdoc_json_types, serde_json, similar, wasmparser};
3838

3939
// Helpers for building names of output artifacts that are potentially target-specific.
4040
pub use crate::artifact_names::{
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#![no_std]
2+
3+
pub struct S;
4+
5+
pub use trans_dep::S as TransDep;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#![no_std]
2+
3+
pub type FromDep = dep::S;
4+
pub type FromTransDep = dep::TransDep;
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
use std::path;
2+
3+
use run_make_support::rustdoc_json_types::{Crate, ItemEnum, Path, Type, TypeAlias};
4+
use run_make_support::{cwd, rfs, rust_lib_name, rustc, rustdoc, serde_json};
5+
6+
#[track_caller]
7+
fn canonicalize(p: &path::Path) -> path::PathBuf {
8+
std::fs::canonicalize(p).expect("path should be canonicalizeable")
9+
}
10+
11+
fn main() {
12+
rustc().input("trans_dep.rs").edition("2024").crate_type("lib").run();
13+
14+
rustc()
15+
.input("dep.rs")
16+
.edition("2024")
17+
.crate_type("lib")
18+
.extern_("trans_dep", rust_lib_name("trans_dep"))
19+
.run();
20+
21+
rustdoc()
22+
.input("entry.rs")
23+
.edition("2024")
24+
.output_format("json")
25+
.library_search_path(cwd())
26+
.extern_("dep", rust_lib_name("dep"))
27+
.arg("-Zunstable-options")
28+
.run();
29+
30+
let bytes = rfs::read("doc/entry.json");
31+
32+
let krate: Crate = serde_json::from_slice(&bytes).expect("output should be valid json");
33+
34+
let root_item = &krate.index[&krate.root];
35+
let ItemEnum::Module(root_mod) = &root_item.inner else { panic!("expected ItemEnum::Module") };
36+
37+
assert_eq!(root_mod.items.len(), 2);
38+
39+
let items = root_mod.items.iter().map(|id| &krate.index[id]).collect::<Vec<_>>();
40+
41+
let from_dep = items
42+
.iter()
43+
.filter(|item| item.name.as_deref() == Some("FromDep"))
44+
.next()
45+
.expect("there should be en item called FromDep");
46+
47+
let from_trans_dep = items
48+
.iter()
49+
.filter(|item| item.name.as_deref() == Some("FromTransDep"))
50+
.next()
51+
.expect("there should be en item called FromDep");
52+
53+
let ItemEnum::TypeAlias(TypeAlias {
54+
type_: Type::ResolvedPath(Path { id: from_dep_id, .. }),
55+
..
56+
}) = &from_dep.inner
57+
else {
58+
panic!("Expected FromDep to be a TypeAlias");
59+
};
60+
61+
let ItemEnum::TypeAlias(TypeAlias {
62+
type_: Type::ResolvedPath(Path { id: from_trans_dep_id, .. }),
63+
..
64+
}) = &from_trans_dep.inner
65+
else {
66+
panic!("Expected FromDep to be a TypeAlias");
67+
};
68+
69+
assert_eq!(krate.index.get(from_dep_id), None);
70+
assert_eq!(krate.index.get(from_trans_dep_id), None);
71+
72+
let from_dep_externalinfo = &krate.paths[from_dep_id];
73+
let from_trans_dep_externalinfo = &krate.paths[from_trans_dep_id];
74+
75+
let dep_crate_id = from_dep_externalinfo.crate_id;
76+
let trans_dep_crate_id = from_trans_dep_externalinfo.crate_id;
77+
78+
let dep = &krate.external_crates[&dep_crate_id];
79+
let trans_dep = &krate.external_crates[&trans_dep_crate_id];
80+
81+
assert_eq!(dep.name, "dep");
82+
assert_eq!(trans_dep.name, "trans_dep");
83+
84+
assert_eq!(canonicalize(&dep.path), canonicalize(&cwd().join(rust_lib_name("dep"))));
85+
assert_eq!(
86+
canonicalize(&trans_dep.path),
87+
canonicalize(&cwd().join(rust_lib_name("trans_dep")))
88+
);
89+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#![no_std]
2+
3+
pub struct S;

0 commit comments

Comments
 (0)