Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 39 additions & 19 deletions rustdoc/rustdoc_processor/src/compute/orchestration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::sync::Arc;

use ahash::{HashMap, HashMapExt};
use anyhow::Context;
use guppy::graph::PackageGraph;
use guppy::graph::{BuildTargetId, PackageGraph};
use guppy::{PackageId, Version};
use indexmap::IndexSet;
use itertools::Itertools as _;
Expand Down Expand Up @@ -39,6 +39,23 @@ fn format_optional_version(v: &Option<Version>) -> Option<tracing::field::Displa
})
}

/// Returns the library target name for a package, falling back to the
/// normalized package name if no lib target exists.
///
/// `cargo doc` names its output files after the lib target name, not the package name.
/// When a `Cargo.toml` sets `[lib] name = "foo"`, the output file is `foo.json`,
/// regardless of the package name.
fn lib_target_name(package_id: &PackageId, package_graph: &PackageGraph) -> String {
if let Ok(metadata) = package_graph.metadata(package_id)
&& let Some(target) = metadata.build_target(&BuildTargetId::Library)
{
return target.name().to_owned();
}
// Fallback: normalize the package name (hyphens → underscores), which
// is what cargo uses by default when no explicit [lib] name is set.
normalize_crate_name(package_graph.metadata(package_id).unwrap().name())
}

/// Return the JSON documentation for one or more crates.
/// Crates are singled out, within the current workspace, using a [`PackageIdSpecification`].
///
Expand Down Expand Up @@ -92,17 +109,17 @@ where
let mut chunks: Vec<Vec<(PackageId, PackageIdSpecification)>> = vec![];
let mut chunk_id2names = HashMap::<usize, IndexSet<_>>::new();
'outer: for (package_id, package_spec) in to_be_computed {
let target_name = lib_target_name(&package_id, package_graph);
for (index, chunk) in chunks.iter_mut().enumerate() {
let chunk_names = chunk_id2names.get_mut(&index).unwrap();
if chunk_names.insert(package_spec.name.clone()) {
// We haven't seen this crate name before.
if chunk_names.insert(target_name.clone()) {
chunk.push((package_id, package_spec));
continue 'outer;
}
}
// We need a new chunk!
let mut names = IndexSet::new();
names.insert(package_spec.name.clone());
names.insert(target_name);
chunk_id2names.insert(chunks.len(), names);
chunks.push(vec![(package_id, package_spec)]);
}
Expand All @@ -117,20 +134,19 @@ where
// We need to clean up the target directory to make sure that `cargo` doesn't
// mistakenly believe that the JSON docs it generated for another version of
// the crate can be reused.
for (_, spec) in &chunk {
let _ = fs_err::remove_file(json_doc_location(spec, target_directory));
for (id, _) in &chunk {
let lib_name = lib_target_name(id, package_graph);
let _ = fs_err::remove_file(json_doc_location(&lib_name, target_directory));
}
} else {
// If it's the first chunk, we need to check package by package.
for (id, spec) in &chunk {
let metadata = package_graph.metadata(id).unwrap();
if package_graph
for (id, _) in &chunk {
let our_lib = lib_target_name(id, package_graph);
let has_duplicate = package_graph
.packages()
.filter(|p| p.name() == metadata.name())
.count()
> 1
{
let _ = fs_err::remove_file(json_doc_location(spec, target_directory));
.any(|p| p.id() != id && lib_target_name(p.id(), package_graph) == our_lib);
if has_duplicate {
let _ = fs_err::remove_file(json_doc_location(&our_lib, target_directory));
}
}
}
Expand All @@ -156,7 +172,9 @@ where
for (package_id, krate) in chunk
.into_par_iter()
.map(|(package_id, package_spec)| {
let krate = load_json_docs(target_directory, &package_spec, toolchain_name);
let lib_name = lib_target_name(&package_id, package_graph);
let krate =
load_json_docs(target_directory, &lib_name, &package_spec, toolchain_name);
(package_id, krate)
})
.collect::<Vec<_>>()
Expand Down Expand Up @@ -262,26 +280,28 @@ fn _compute_multiple_crate_docs(
}

/// The path to the JSON file generated by `rustdoc`.
fn json_doc_location(spec: &PackageIdSpecification, target_directory: &Path) -> PathBuf {
fn json_doc_location(lib_name: &str, target_directory: &Path) -> PathBuf {
target_directory
.join("doc")
.join(format!("{}.json", normalize_crate_name(&spec.name)))
.join(format!("{}.json", normalize_crate_name(lib_name)))
}

#[tracing::instrument(
skip_all,
fields(
crate.name = package_id_spec.name,
crate.version = format_optional_version(&package_id_spec.version),
crate.source = package_id_spec.source
crate.source = package_id_spec.source,
crate.lib.name = lib_name,
)
)]
fn load_json_docs(
target_directory: &Path,
lib_name: &str,
package_id_spec: &PackageIdSpecification,
toolchain_name: &str,
) -> Result<rustdoc_types::Crate, anyhow::Error> {
let json_path = json_doc_location(package_id_spec, target_directory);
let json_path = json_doc_location(lib_name, target_directory);

let span = tracing::trace_span!("Read and deserialize JSON output");
let guard = span.enter();
Expand Down
10 changes: 7 additions & 3 deletions rustdoc/rustdoc_processor/src/indexing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl CrateIndexer for NoAnnotations {
pub trait IndexingVisitor {
/// Called for every item discovered during traversal.
fn on_item_discovered(&mut self, item: &rustdoc_types::Item, item_id: rustdoc_types::Id);
/// Called for items added to the import index (struct/enum/trait/fn/type_alias/primitive).
/// Called for items added to the import index (struct/enum/trait/fn/type_alias/primitive/static/union).
fn on_type_indexed(&mut self, item_id: rustdoc_types::Id);
}

Expand Down Expand Up @@ -268,6 +268,8 @@ pub(crate) fn index_local_types<'a, V: IndexingVisitor>(
| ItemEnum::Function(_)
| ItemEnum::Primitive(_)
| ItemEnum::TypeAlias(_)
| ItemEnum::Static(_)
| ItemEnum::Union(_)
) {
// We keep track of the source path in our indexes.
// This is useful, in particular, if we don't have
Expand Down Expand Up @@ -325,9 +327,11 @@ pub(crate) fn index_local_types<'a, V: IndexingVisitor>(
| ItemEnum::Function(_)
| ItemEnum::Enum(_)
| ItemEnum::Struct(_)
| ItemEnum::TypeAlias(_) => {
| ItemEnum::TypeAlias(_)
| ItemEnum::Static(_)
| ItemEnum::Union(_) => {
let name = current_item.name.as_deref().expect(
"All 'struct', 'function', 'enum', 'type_alias', 'primitive' and 'trait' items have a 'name' property",
"All 'struct', 'function', 'enum', 'type_alias', 'primitive', 'trait', 'static' and 'union' items have a 'name' property",
);
if matches!(current_item.inner, ItemEnum::Primitive(_)) {
// E.g. `std::bool` won't work, `std::primitive::bool` does work but the `primitive` module
Expand Down
6 changes: 3 additions & 3 deletions rustdoc/rustdoc_resolver/src/resolve_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,9 +526,9 @@ fn skip_default<I: CrateIndexer>(krate_collection: &CrateCollection<I>, default:
.items
.iter()
.find(|(_, entry)| entry.canonical_path() == ["alloc", "alloc", "Global"])
{
return item_entry.1.canonical_path().to_vec();
}
{
return item_entry.1.canonical_path().to_vec();
}
vec!["alloc".into(), "alloc".into(), "Global".into()]
});

Expand Down
Loading