Skip to content

Commit

Permalink
Auto merge of rust-lang#122041 - matthiaskrgr:rollup-imsmdke, r=matth…
Browse files Browse the repository at this point in the history
…iaskrgr

Rollup of 8 pull requests

Successful merges:

 - rust-lang#121202 (Limit the number of names and values in check-cfg diagnostics)
 - rust-lang#121301 (errors: share `SilentEmitter` between rustc and rustfmt)
 - rust-lang#121658 (Hint user to update nightly on ICEs produced from outdated nightly)
 - rust-lang#121846 (only compare ambiguity item that have hard error)
 - rust-lang#121961 (add test for rust-lang#78894 rust-lang#71450)
 - rust-lang#121975 (hir_analysis: enums return `None` in `find_field`)
 - rust-lang#121978 (Fix duplicated path in the "not found dylib" error)
 - rust-lang#121991 (Merge impl_trait_in_assoc_types_defined_by query back into `opaque_types_defined_by`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Mar 5, 2024
2 parents 3c02972 + 3d6b3d0 commit 4cb986b
Show file tree
Hide file tree
Showing 37 changed files with 584 additions and 220 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_driver_impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ rustc_trait_selection = { path = "../rustc_trait_selection" }
rustc_ty_utils = { path = "../rustc_ty_utils" }
serde_json = "1.0.59"
shlex = "1.0"
time = { version = "0.3", default-features = false, features = ["alloc", "formatting"] }
time = { version = "0.3", default-features = false, features = ["alloc", "formatting", "parsing", "macros"] }
tracing = { version = "0.1.35" }
# tidy-alphabetical-end

Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_driver_impl/messages.ftl
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
driver_impl_ice = the compiler unexpectedly panicked. this is a bug.
driver_impl_ice_bug_report = we would appreciate a bug report: {$bug_report_url}
driver_impl_ice_bug_report_internal_feature = using internal features is not supported and expected to cause internal compiler errors when used incorrectly
driver_impl_ice_bug_report_outdated =
it seems that this compiler `{$version}` is outdated, a newer nightly should have been released in the mean time
.update = please consider running `rustup update nightly` to update the nightly channel and check if this problem still persists
.url = if the problem still persists, we would appreciate a bug report: {$bug_report_url}
driver_impl_ice_exclude_cargo_defaults = some of the compiler flags provided by cargo are hidden
driver_impl_ice_flags = compiler flags: {$flags}
Expand Down
35 changes: 31 additions & 4 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ use std::str;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Instant, SystemTime};
use time::OffsetDateTime;
use time::{Date, OffsetDateTime, Time};

#[allow(unused_macros)]
macro do_not_use_print($($t:tt)*) {
Expand Down Expand Up @@ -1369,6 +1369,9 @@ pub fn install_ice_hook(
using_internal_features
}

const DATE_FORMAT: &[time::format_description::FormatItem<'static>] =
&time::macros::format_description!("[year]-[month]-[day]");

/// Prints the ICE message, including query stack, but without backtrace.
///
/// The message will point the user at `bug_report_url` to report the ICE.
Expand Down Expand Up @@ -1397,10 +1400,34 @@ fn report_ice(
dcx.emit_err(session_diagnostics::Ice);
}

if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
use time::ext::NumericalDuration;

// Try to hint user to update nightly if applicable when reporting an ICE.
// Attempt to calculate when current version was released, and add 12 hours
// as buffer. If the current version's release timestamp is older than
// the system's current time + 24 hours + 12 hours buffer if we're on
// nightly.
if let Some("nightly") = option_env!("CFG_RELEASE_CHANNEL")
&& let Some(version) = option_env!("CFG_VERSION")
&& let Some(ver_date_str) = option_env!("CFG_VER_DATE")
&& let Ok(ver_date) = Date::parse(&ver_date_str, DATE_FORMAT)
&& let ver_datetime = OffsetDateTime::new_utc(ver_date, Time::MIDNIGHT)
&& let system_datetime = OffsetDateTime::from(SystemTime::now())
&& system_datetime.checked_sub(36.hours()).is_some_and(|d| d > ver_datetime)
&& !using_internal_features.load(std::sync::atomic::Ordering::Relaxed)
{
dcx.emit_note(session_diagnostics::IceBugReportOutdated {
version,
bug_report_url,
note_update: (),
note_url: (),
});
} else {
dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
if using_internal_features.load(std::sync::atomic::Ordering::Relaxed) {
dcx.emit_note(session_diagnostics::IceBugReportInternalFeature);
} else {
dcx.emit_note(session_diagnostics::IceBugReport { bug_report_url });
}
}

let version = util::version_str!().unwrap_or("unknown_version");
Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_driver_impl/src/session_diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ pub(crate) struct IceBugReport<'a> {
#[diag(driver_impl_ice_bug_report_internal_feature)]
pub(crate) struct IceBugReportInternalFeature;

#[derive(Diagnostic)]
#[diag(driver_impl_ice_bug_report_outdated)]
pub(crate) struct IceBugReportOutdated<'a> {
pub version: &'a str,
pub bug_report_url: &'a str,
#[note(driver_impl_update)]
pub note_update: (),
#[note(driver_impl_url)]
pub note_url: (),
}

#[derive(Diagnostic)]
#[diag(driver_impl_ice_version)]
pub(crate) struct IceVersion<'a> {
Expand Down
32 changes: 8 additions & 24 deletions compiler/rustc_errors/src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
use rustc_span::source_map::SourceMap;
use rustc_span::{FileLines, FileName, SourceFile, Span};

use crate::error::TranslateError;
use crate::snippet::{
Annotation, AnnotationColumn, AnnotationType, Line, MultilineAnnotation, Style, StyledString,
};
Expand Down Expand Up @@ -539,18 +538,9 @@ impl Emitter for HumanEmitter {
/// Fatal diagnostics are forwarded to `fatal_dcx` to avoid silent
/// failures of rustc, as witnessed e.g. in issue #89358.
pub struct SilentEmitter {
pub fallback_bundle: LazyFallbackBundle,
pub fatal_dcx: DiagCtxt,
pub fatal_note: String,
}

pub fn silent_translate<'a>(message: &'a DiagMessage) -> Result<Cow<'_, str>, TranslateError<'_>> {
match message {
DiagMessage::Str(msg) | DiagMessage::Translated(msg) => Ok(Cow::Borrowed(msg)),
DiagMessage::FluentIdentifier(identifier, _) => {
// Any value works here.
Ok(identifier.clone())
}
}
pub fatal_note: Option<String>,
}

impl Translate for SilentEmitter {
Expand All @@ -559,17 +549,9 @@ impl Translate for SilentEmitter {
}

fn fallback_fluent_bundle(&self) -> &FluentBundle {
panic!("silent emitter attempted to translate message")
}

// Override `translate_message` for the silent emitter because eager translation of
// subdiagnostics result in a call to this.
fn translate_message<'a>(
&'a self,
message: &'a DiagMessage,
_: &'a FluentArgs<'_>,
) -> Result<Cow<'_, str>, TranslateError<'_>> {
silent_translate(message)
// Ideally this field wouldn't be necessary and the fallback bundle in `fatal_dcx` would be
// used but the lock prevents this.
&self.fallback_bundle
}
}

Expand All @@ -580,7 +562,9 @@ impl Emitter for SilentEmitter {

fn emit_diagnostic(&mut self, mut diag: DiagInner) {
if diag.level == Level::Fatal {
diag.sub(Level::Note, self.fatal_note.clone(), MultiSpan::new());
if let Some(fatal_note) = &self.fatal_note {
diag.sub(Level::Note, fatal_note.clone(), MultiSpan::new());
}
self.fatal_dcx.emit_diagnostic(diag);
}
}
Expand Down
95 changes: 72 additions & 23 deletions compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ use emitter::{is_case_difference, DynEmitter, Emitter};
use registry::Registry;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
use rustc_data_structures::stable_hasher::{Hash128, StableHasher};
use rustc_data_structures::sync::Lock;
use rustc_data_structures::sync::{Lock, Lrc};
use rustc_data_structures::AtomicRef;
use rustc_lint_defs::LintExpectationId;
use rustc_span::source_map::SourceMap;
Expand Down Expand Up @@ -606,29 +606,54 @@ impl DiagCtxt {
}

pub fn new(emitter: Box<DynEmitter>) -> Self {
Self {
inner: Lock::new(DiagCtxtInner {
flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() },
err_guars: Vec::new(),
lint_err_guars: Vec::new(),
delayed_bugs: Vec::new(),
deduplicated_err_count: 0,
deduplicated_warn_count: 0,
emitter,
must_produce_diag: false,
has_printed: false,
suppressed_expected_diag: false,
taught_diagnostics: Default::default(),
emitted_diagnostic_codes: Default::default(),
emitted_diagnostics: Default::default(),
stashed_diagnostics: Default::default(),
future_breakage_diagnostics: Vec::new(),
check_unstable_expect_diagnostics: false,
unstable_expect_diagnostics: Vec::new(),
fulfilled_expectations: Default::default(),
ice_file: None,
}),
Self { inner: Lock::new(DiagCtxtInner::new(emitter)) }
}

pub fn make_silent(&mut self, fallback_bundle: LazyFallbackBundle, fatal_note: Option<String>) {
self.wrap_emitter(|old_dcx| {
Box::new(emitter::SilentEmitter {
fallback_bundle,
fatal_dcx: DiagCtxt { inner: Lock::new(old_dcx) },
fatal_note,
})
});
}

fn wrap_emitter<F>(&mut self, f: F)
where
F: FnOnce(DiagCtxtInner) -> Box<DynEmitter>,
{
// A empty type that implements `Emitter` so that a `DiagCtxtInner` can be constructed
// to temporarily swap in place of the real one, which will be used in constructing
// its replacement.
struct FalseEmitter;

impl Emitter for FalseEmitter {
fn emit_diagnostic(&mut self, _: DiagInner) {
unimplemented!("false emitter must only used during `wrap_emitter`")
}

fn source_map(&self) -> Option<&Lrc<SourceMap>> {
unimplemented!("false emitter must only used during `wrap_emitter`")
}
}

impl translation::Translate for FalseEmitter {
fn fluent_bundle(&self) -> Option<&Lrc<FluentBundle>> {
unimplemented!("false emitter must only used during `wrap_emitter`")
}

fn fallback_fluent_bundle(&self) -> &FluentBundle {
unimplemented!("false emitter must only used during `wrap_emitter`")
}
}

let mut inner = self.inner.borrow_mut();
let mut prev_dcx = DiagCtxtInner::new(Box::new(FalseEmitter));
std::mem::swap(&mut *inner, &mut prev_dcx);
let new_emitter = f(prev_dcx);
let mut new_dcx = DiagCtxtInner::new(new_emitter);
std::mem::swap(&mut *inner, &mut new_dcx);
}

/// Translate `message` eagerly with `args` to `SubdiagMessage::Eager`.
Expand Down Expand Up @@ -1345,6 +1370,30 @@ impl DiagCtxt {
// `DiagCtxt::foo()` just borrows `inner` and forwards a call to
// `DiagCtxtInner::foo`.
impl DiagCtxtInner {
fn new(emitter: Box<DynEmitter>) -> Self {
Self {
flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() },
err_guars: Vec::new(),
lint_err_guars: Vec::new(),
delayed_bugs: Vec::new(),
deduplicated_err_count: 0,
deduplicated_warn_count: 0,
emitter,
must_produce_diag: false,
has_printed: false,
suppressed_expected_diag: false,
taught_diagnostics: Default::default(),
emitted_diagnostic_codes: Default::default(),
emitted_diagnostics: Default::default(),
stashed_diagnostics: Default::default(),
future_breakage_diagnostics: Vec::new(),
check_unstable_expect_diagnostics: false,
unstable_expect_diagnostics: Vec::new(),
fulfilled_expectations: Default::default(),
ice_file: None,
}
}

/// Emit all stashed diagnostics.
fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
let mut guar = None;
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_hir_analysis/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,12 @@ fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
}

fn find_field(tcx: TyCtxt<'_>, (def_id, ident): (DefId, Ident)) -> Option<FieldIdx> {
tcx.adt_def(def_id).non_enum_variant().fields.iter_enumerated().find_map(|(idx, field)| {
let adt = tcx.adt_def(def_id);
if adt.is_enum() {
return None;
}

adt.non_enum_variant().fields.iter_enumerated().find_map(|(idx, field)| {
if field.is_unnamed() {
let field_ty = tcx.type_of(field.did).instantiate_identity();
let adt_def = field_ty.ty_adt_def().expect("expect Adt for unnamed field");
Expand Down
28 changes: 8 additions & 20 deletions compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ pub(super) fn find_opaque_ty_constraints_for_impl_trait_in_assoc_type(
for &assoc_id in tcx.associated_item_def_ids(impl_def_id) {
let assoc = tcx.associated_item(assoc_id);
match assoc.kind {
ty::AssocKind::Const | ty::AssocKind::Fn => {
locator.check(assoc_id.expect_local(), ImplTraitSource::AssocTy)
}
ty::AssocKind::Const | ty::AssocKind::Fn => locator.check(assoc_id.expect_local()),
// Associated types don't have bodies, so they can't constrain hidden types
ty::AssocKind::Type => {}
}
Expand Down Expand Up @@ -182,15 +180,9 @@ struct TaitConstraintLocator<'tcx> {
typeck_types: Vec<ty::OpaqueHiddenType<'tcx>>,
}

#[derive(Debug)]
enum ImplTraitSource {
AssocTy,
TyAlias,
}

impl TaitConstraintLocator<'_> {
#[instrument(skip(self), level = "debug")]
fn check(&mut self, item_def_id: LocalDefId, source: ImplTraitSource) {
fn check(&mut self, item_def_id: LocalDefId) {
// Don't try to check items that cannot possibly constrain the type.
if !self.tcx.has_typeck_results(item_def_id) {
debug!("no constraint: no typeck results");
Expand Down Expand Up @@ -242,12 +234,8 @@ impl TaitConstraintLocator<'_> {
continue;
}
constrained = true;
let opaque_types_defined_by = match source {
ImplTraitSource::AssocTy => {
self.tcx.impl_trait_in_assoc_types_defined_by(item_def_id)
}
ImplTraitSource::TyAlias => self.tcx.opaque_types_defined_by(item_def_id),
};
let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);

if !opaque_types_defined_by.contains(&self.def_id) {
self.tcx.dcx().emit_err(TaitForwardCompat {
span: hidden_type.span,
Expand Down Expand Up @@ -308,29 +296,29 @@ impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
}
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let hir::ExprKind::Closure(closure) = ex.kind {
self.check(closure.def_id, ImplTraitSource::TyAlias);
self.check(closure.def_id);
}
intravisit::walk_expr(self, ex);
}
fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
trace!(?it.owner_id);
// The opaque type itself or its children are not within its reveal scope.
if it.owner_id.def_id != self.def_id {
self.check(it.owner_id.def_id, ImplTraitSource::TyAlias);
self.check(it.owner_id.def_id);
intravisit::walk_item(self, it);
}
}
fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
trace!(?it.owner_id);
// The opaque type itself or its children are not within its reveal scope.
if it.owner_id.def_id != self.def_id {
self.check(it.owner_id.def_id, ImplTraitSource::TyAlias);
self.check(it.owner_id.def_id);
intravisit::walk_impl_item(self, it);
}
}
fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
trace!(?it.owner_id);
self.check(it.owner_id.def_id, ImplTraitSource::TyAlias);
self.check(it.owner_id.def_id);
intravisit::walk_trait_item(self, it);
}
fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
Expand Down
14 changes: 8 additions & 6 deletions compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ pub struct Compiler {
pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec<String>) -> Cfg {
cfgs.into_iter()
.map(|s| {
let psess = ParseSess::with_silent_emitter(format!(
"this error occurred on the command line: `--cfg={s}`"
));
let psess = ParseSess::with_silent_emitter(
vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE],
format!("this error occurred on the command line: `--cfg={s}`"),
);
let filename = FileName::cfg_spec_source_code(&s);

macro_rules! error {
Expand Down Expand Up @@ -107,9 +108,10 @@ pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec<String>) -> CheckCfg {
let mut check_cfg = CheckCfg { exhaustive_names, exhaustive_values, ..CheckCfg::default() };

for s in specs {
let psess = ParseSess::with_silent_emitter(format!(
"this error occurred on the command line: `--check-cfg={s}`"
));
let psess = ParseSess::with_silent_emitter(
vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE],
format!("this error occurred on the command line: `--check-cfg={s}`"),
);
let filename = FileName::cfg_spec_source_code(&s);

macro_rules! error {
Expand Down
Loading

0 comments on commit 4cb986b

Please sign in to comment.