Skip to content

Commit e1b6294

Browse files
authored
Rollup merge of rust-lang#111076 - notriddle:notriddle/silence-private-dep-trait-impl-suggestions, r=cjgillot
diagnostics: exclude indirect private deps from trait impl suggest Fixes rust-lang#88696
2 parents 23f7f7e + bbc9674 commit e1b6294

File tree

17 files changed

+121
-22
lines changed

17 files changed

+121
-22
lines changed

compiler/rustc_data_structures/src/sync.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,11 @@ cfg_if! {
143143
self.0.set(val);
144144
result
145145
}
146+
pub fn fetch_and(&self, val: bool, _: Ordering) -> bool {
147+
let result = self.0.get() & val;
148+
self.0.set(val);
149+
result
150+
}
146151
}
147152

148153
impl<T: Copy + PartialEq> Atomic<T> {

compiler/rustc_metadata/src/creader.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -361,15 +361,21 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
361361
lib: Library,
362362
dep_kind: CrateDepKind,
363363
name: Symbol,
364+
private_dep: Option<bool>,
364365
) -> Result<CrateNum, CrateError> {
365366
let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
366367

367368
let Library { source, metadata } = lib;
368369
let crate_root = metadata.get_root();
369370
let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
370371

371-
let private_dep =
372-
self.sess.opts.externs.get(name.as_str()).map_or(false, |e| e.is_private_dep);
372+
let private_dep = self
373+
.sess
374+
.opts
375+
.externs
376+
.get(name.as_str())
377+
.map_or(private_dep.unwrap_or(false), |e| e.is_private_dep)
378+
&& private_dep.unwrap_or(true);
373379

374380
// Claim this crate number and cache it
375381
let cnum = self.cstore.intern_stable_crate_id(&crate_root)?;
@@ -514,15 +520,16 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
514520
if !name.as_str().is_ascii() {
515521
return Err(CrateError::NonAsciiName(name));
516522
}
517-
let (root, hash, host_hash, extra_filename, path_kind) = match dep {
523+
let (root, hash, host_hash, extra_filename, path_kind, private_dep) = match dep {
518524
Some((root, dep)) => (
519525
Some(root),
520526
Some(dep.hash),
521527
dep.host_hash,
522528
Some(&dep.extra_filename[..]),
523529
PathKind::Dependency,
530+
Some(dep.is_private),
524531
),
525-
None => (None, None, None, None, PathKind::Crate),
532+
None => (None, None, None, None, PathKind::Crate, None),
526533
};
527534
let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
528535
(LoadResult::Previous(cnum), None)
@@ -558,10 +565,13 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
558565
dep_kind = CrateDepKind::MacrosOnly;
559566
}
560567
data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
568+
if let Some(private_dep) = private_dep {
569+
data.update_and_private_dep(private_dep);
570+
}
561571
Ok(cnum)
562572
}
563573
(LoadResult::Loaded(library), host_library) => {
564-
self.register_crate(host_library, root, library, dep_kind, name)
574+
self.register_crate(host_library, root, library, dep_kind, name, private_dep)
565575
}
566576
_ => panic!(),
567577
}

compiler/rustc_metadata/src/rmeta/decoder.rs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use rustc_ast as ast;
88
use rustc_data_structures::captures::Captures;
99
use rustc_data_structures::fx::FxHashMap;
1010
use rustc_data_structures::svh::Svh;
11-
use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc, OnceCell};
11+
use rustc_data_structures::sync::{AppendOnlyVec, AtomicBool, Lock, Lrc, OnceCell};
1212
use rustc_data_structures::unhash::UnhashMap;
1313
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
1414
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
@@ -38,6 +38,7 @@ use proc_macro::bridge::client::ProcMacro;
3838
use std::iter::TrustedLen;
3939
use std::num::NonZeroUsize;
4040
use std::path::Path;
41+
use std::sync::atomic::Ordering;
4142
use std::{io, iter, mem};
4243

4344
pub(super) use cstore_impl::provide;
@@ -109,9 +110,10 @@ pub(crate) struct CrateMetadata {
109110
dep_kind: Lock<CrateDepKind>,
110111
/// Filesystem location of this crate.
111112
source: Lrc<CrateSource>,
112-
/// Whether or not this crate should be consider a private dependency
113-
/// for purposes of the 'exported_private_dependencies' lint
114-
private_dep: bool,
113+
/// Whether or not this crate should be consider a private dependency.
114+
/// Used by the 'exported_private_dependencies' lint, and for determining
115+
/// whether to emit suggestions that reference this crate.
116+
private_dep: AtomicBool,
115117
/// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
116118
host_hash: Option<Svh>,
117119

@@ -692,12 +694,13 @@ impl MetadataBlob {
692694
writeln!(out, "=External Dependencies=")?;
693695

694696
for (i, dep) in root.crate_deps.decode(self).enumerate() {
695-
let CrateDep { name, extra_filename, hash, host_hash, kind } = dep;
697+
let CrateDep { name, extra_filename, hash, host_hash, kind, is_private } = dep;
696698
let number = i + 1;
697699

698700
writeln!(
699701
out,
700-
"{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?}"
702+
"{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?} {privacy}",
703+
privacy = if is_private { "private" } else { "public" }
701704
)?;
702705
}
703706
write!(out, "\n")?;
@@ -1627,7 +1630,7 @@ impl CrateMetadata {
16271630
dependencies,
16281631
dep_kind: Lock::new(dep_kind),
16291632
source: Lrc::new(source),
1630-
private_dep,
1633+
private_dep: AtomicBool::new(private_dep),
16311634
host_hash,
16321635
extern_crate: Lock::new(None),
16331636
hygiene_context: Default::default(),
@@ -1675,6 +1678,10 @@ impl CrateMetadata {
16751678
self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
16761679
}
16771680

1681+
pub(crate) fn update_and_private_dep(&self, private_dep: bool) {
1682+
self.private_dep.fetch_and(private_dep, Ordering::SeqCst);
1683+
}
1684+
16781685
pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
16791686
self.root.required_panic_strategy
16801687
}

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,13 @@ provide! { tcx, def_id, other, cdata,
286286
is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) }
287287

288288
dylib_dependency_formats => { cdata.get_dylib_dependency_formats(tcx) }
289-
is_private_dep => { cdata.private_dep }
289+
is_private_dep => {
290+
// Parallel compiler needs to synchronize type checking and linting (which use this flag)
291+
// so that they happen strictly crate loading. Otherwise, the full list of available
292+
// impls aren't loaded yet.
293+
use std::sync::atomic::Ordering;
294+
cdata.private_dep.load(Ordering::Acquire)
295+
}
290296
is_panic_runtime => { cdata.root.panic_runtime }
291297
is_compiler_builtins => { cdata.root.compiler_builtins }
292298
has_global_allocator => { cdata.root.has_global_allocator }

compiler/rustc_metadata/src/rmeta/encoder.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1869,6 +1869,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
18691869
host_hash: self.tcx.crate_host_hash(cnum),
18701870
kind: self.tcx.dep_kind(cnum),
18711871
extra_filename: self.tcx.extra_filename(cnum).clone(),
1872+
is_private: self.tcx.is_private_dep(cnum),
18721873
};
18731874
(cnum, dep)
18741875
})

compiler/rustc_metadata/src/rmeta/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ pub(crate) struct CrateDep {
302302
pub host_hash: Option<Svh>,
303303
pub kind: CrateDepKind,
304304
pub extra_filename: String,
305+
pub is_private: bool,
305306
}
306307

307308
#[derive(MetadataEncodable, MetadataDecodable)]

compiler/rustc_middle/src/ty/util.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher};
1414
use rustc_errors::ErrorGuaranteed;
1515
use rustc_hir as hir;
1616
use rustc_hir::def::{CtorOf, DefKind, Res};
17-
use rustc_hir::def_id::{DefId, LocalDefId};
17+
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
1818
use rustc_index::bit_set::GrowableBitSet;
1919
use rustc_index::{Idx, IndexVec};
2020
use rustc_macros::HashStable;
@@ -820,6 +820,26 @@ impl<'tcx> TyCtxt<'tcx> {
820820
_ => def_kind.article(),
821821
}
822822
}
823+
824+
/// Return `true` if the supplied `CrateNum` is "user-visible," meaning either a [public]
825+
/// dependency, or a [direct] private dependency. This is used to decide whether the crate can
826+
/// be shown in `impl` suggestions.
827+
///
828+
/// [public]: TyCtxt::is_private_dep
829+
/// [direct]: rustc_session::cstore::ExternCrate::is_direct
830+
pub fn is_user_visible_dep(self, key: CrateNum) -> bool {
831+
// | Private | Direct | Visible | |
832+
// |---------|--------|---------|--------------------|
833+
// | Yes | Yes | Yes | !true || true |
834+
// | No | Yes | Yes | !false || true |
835+
// | Yes | No | No | !true || false |
836+
// | No | No | Yes | !false || false |
837+
!self.is_private_dep(key)
838+
// If `extern_crate` is `None`, then the crate was injected (e.g., by the allocator).
839+
// Treat that kind of crate as "indirect", since it's an implementation detail of
840+
// the language.
841+
|| self.extern_crate(key.as_def_id()).map_or(false, |e| e.is_direct())
842+
}
823843
}
824844

825845
struct OpaqueTypeExpander<'tcx> {

compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1775,6 +1775,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
17751775
|| !trait_pred
17761776
.skip_binder()
17771777
.is_constness_satisfied_by(self.tcx.constness(def_id))
1778+
|| !self.tcx.is_user_visible_dep(def_id.krate)
17781779
{
17791780
return None;
17801781
}

library/std/Cargo.toml

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
cargo-features = ["public-dependency"]
2+
13
[package]
24
name = "std"
35
version = "0.0.0"
@@ -10,12 +12,12 @@ edition = "2021"
1012
crate-type = ["dylib", "rlib"]
1113

1214
[dependencies]
13-
alloc = { path = "../alloc" }
15+
alloc = { path = "../alloc", public = true }
1416
cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] }
1517
panic_unwind = { path = "../panic_unwind", optional = true }
1618
panic_abort = { path = "../panic_abort" }
17-
core = { path = "../core" }
18-
libc = { version = "0.2.143", default-features = false, features = ['rustc-dep-of-std'] }
19+
core = { path = "../core", public = true }
20+
libc = { version = "0.2.143", default-features = false, features = ['rustc-dep-of-std'], public = true }
1921
compiler_builtins = { version = "0.1.91" }
2022
profiler_builtins = { path = "../profiler_builtins", optional = true }
2123
unwind = { path = "../unwind" }
@@ -25,7 +27,7 @@ std_detect = { path = "../stdarch/crates/std_detect", default-features = false,
2527
# Dependencies of the `backtrace` crate
2628
addr2line = { version = "0.19.0", optional = true, default-features = false }
2729
rustc-demangle = { version = "0.1.21", features = ['rustc-dep-of-std'] }
28-
miniz_oxide = { version = "0.6.0", optional = true, default-features = false }
30+
miniz_oxide = { version = "0.6.0", optional = true, default-features = false, public = false }
2931
[dependencies.object]
3032
version = "0.30.0"
3133
optional = true

library/std/tests/common/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@ pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng {
2020
}
2121

2222
// Copied from std::sys_common::io
23-
pub struct TempDir(PathBuf);
23+
pub(crate) struct TempDir(PathBuf);
2424

2525
impl TempDir {
26-
pub fn join(&self, path: &str) -> PathBuf {
26+
pub(crate) fn join(&self, path: &str) -> PathBuf {
2727
let TempDir(ref p) = *self;
2828
p.join(path)
2929
}
3030

31-
pub fn path(&self) -> &Path {
31+
pub(crate) fn path(&self) -> &Path {
3232
let TempDir(ref p) = *self;
3333
p
3434
}
@@ -49,7 +49,7 @@ impl Drop for TempDir {
4949
}
5050

5151
#[track_caller] // for `test_rng`
52-
pub fn tmpdir() -> TempDir {
52+
pub(crate) fn tmpdir() -> TempDir {
5353
let p = env::temp_dir();
5454
let mut r = test_rng();
5555
let ret = p.join(&format!("rust-{}", r.next_u32()));

src/bootstrap/metadata.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ fn workspace_members(build: &Build) -> impl Iterator<Item = Package> {
7474
let collect_metadata = |manifest_path| {
7575
let mut cargo = Command::new(&build.initial_cargo);
7676
cargo
77+
// Will read the libstd Cargo.toml
78+
// which uses the unstable `public-dependency` feature.
79+
.env("RUSTC_BOOTSTRAP", "1")
7780
.arg("metadata")
7881
.arg("--format-version")
7982
.arg("1")

src/tools/rust-installer/combine-installers.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ abs_path() {
1111
(unset CDPATH && cd "$path" > /dev/null && pwd)
1212
}
1313

14+
# Running cargo will read the libstd Cargo.toml
15+
# which uses the unstable `public-dependency` feature.
16+
export RUSTC_BOOTSTRAP=1
17+
1418
src_dir="$(abs_path $(dirname "$0"))"
1519
$CARGO run --manifest-path="$src_dir/Cargo.toml" -- combine "$@"

src/tools/rust-installer/gen-installer.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ abs_path() {
1111
(unset CDPATH && cd "$path" > /dev/null && pwd)
1212
}
1313

14+
# Running cargo will read the libstd Cargo.toml
15+
# which uses the unstable `public-dependency` feature.
16+
export RUSTC_BOOTSTRAP=1
17+
1418
src_dir="$(abs_path $(dirname "$0"))"
1519
$CARGO run --manifest-path="$src_dir/Cargo.toml" -- generate "$@"

src/tools/rust-installer/make-tarballs.sh

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ abs_path() {
1111
(unset CDPATH && cd "$path" > /dev/null && pwd)
1212
}
1313

14+
# Running cargo will read the libstd Cargo.toml
15+
# which uses the unstable `public-dependency` feature.
16+
export RUSTC_BOOTSTRAP=1
17+
1418
src_dir="$(abs_path $(dirname "$0"))"
1519
$CARGO run --manifest-path="$src_dir/Cargo.toml" -- tarball "$@"

src/tools/tidy/src/main.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ use std::sync::atomic::{AtomicBool, Ordering};
1616
use std::thread::{self, scope, ScopedJoinHandle};
1717

1818
fn main() {
19+
// Running Cargo will read the libstd Cargo.toml
20+
// which uses the unstable `public-dependency` feature.
21+
//
22+
// `setenv` might not be thread safe, so run it before using multiple threads.
23+
env::set_var("RUSTC_BOOTSTRAP", "1");
24+
1925
let root_path: PathBuf = env::args_os().nth(1).expect("need path to root of repo").into();
2026
let cargo: PathBuf = env::args_os().nth(2).expect("need path to cargo").into();
2127
let output_directory: PathBuf =

tests/ui/suggestions/issue-88696.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// This test case should ensure that miniz_oxide isn't
2+
// suggested, since it's not a direct dependency.
3+
4+
fn a() -> Result<u64, i32> {
5+
Err(1)
6+
}
7+
8+
fn b() -> Result<u32, i32> {
9+
a().into() //~ERROR [E0277]
10+
}
11+
12+
fn main() {
13+
let _ = dbg!(b());
14+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0277]: the trait bound `Result<u32, i32>: From<Result<u64, i32>>` is not satisfied
2+
--> $DIR/issue-88696.rs:9:9
3+
|
4+
LL | a().into()
5+
| ^^^^ the trait `From<Result<u64, i32>>` is not implemented for `Result<u32, i32>`
6+
|
7+
= note: required for `Result<u64, i32>` to implement `Into<Result<u32, i32>>`
8+
9+
error: aborting due to previous error
10+
11+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)