Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 7 pull requests #106771

Closed
wants to merge 16 commits into from
Closed
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
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4273,6 +4273,7 @@ version = "0.0.0"
dependencies = [
"rustc_span",
"tracing",
"tracing-core",
"tracing-subscriber",
"tracing-tree",
]
Expand Down
12 changes: 10 additions & 2 deletions compiler/rustc_driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,8 @@ fn run_compiler(
registry: diagnostics_registry(),
};

init_rustc_env_logger_with_backtrace_option(&config.opts.unstable_opts.log_backtrace);

match make_input(config.opts.error_format, &matches.free) {
Err(reported) => return Err(reported),
Ok(Some((input, input_file_path))) => {
Expand Down Expand Up @@ -1299,7 +1301,14 @@ pub fn install_ice_hook() {
/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version.
pub fn init_rustc_env_logger() {
if let Err(error) = rustc_log::init_rustc_env_logger() {
init_rustc_env_logger_with_backtrace_option(&None);
}

/// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to
/// choose a target module you wish to show backtraces along with its logging.
pub fn init_rustc_env_logger_with_backtrace_option(backtrace_target: &Option<String>) {
if let Err(error) = rustc_log::init_rustc_env_logger_with_backtrace_option(backtrace_target) {
early_error(ErrorOutputType::default(), &error.to_string());
}
}
Expand Down Expand Up @@ -1365,7 +1374,6 @@ mod signal_handler {
pub fn main() -> ! {
let start_time = Instant::now();
let start_rss = get_resident_set_size();
init_rustc_env_logger();
signal_handler::install();
let mut callbacks = TimePassesCallbacks::default();
install_ice_hook();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_error_codes/src/error_codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ E0791: include_str!("./error_codes/E0791.md"),
// E0487, // unsafe use of destructor: destructor might be called while...
// E0488, // lifetime of variable does not enclose its declaration
// E0489, // type/lifetime parameter not in scope here
E0490, // a value of type `..` is borrowed for too long
// E0490, // removed: unreachable
E0523, // two dependencies have same (crate-name, disambiguator) but different SVH
// E0526, // shuffle indices are not constant
// E0540, // multiple rustc_deprecated attributes
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_error_messages/locales/en-US/infer.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ infer_subtype_2 = ...so that {$requirement ->
infer_reborrow = ...so that reference does not outlive borrowed content
infer_reborrow_upvar = ...so that closure can access `{$name}`
infer_relate_object_bound = ...so that it can be closed over into an object
infer_data_borrowed = ...so that the type `{$name}` is not borrowed for too long
infer_reference_outlives_referent = ...so that the reference type `{$name}` does not outlive the data it points at
infer_relate_param_bound = ...so that the type `{$name}` will meet its required lifetime bounds{$continues ->
[true] ...
Expand Down
35 changes: 0 additions & 35 deletions compiler/rustc_infer/src/infer/error_reporting/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,6 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
RegionOriginNote::Plain { span, msg: fluent::infer_relate_object_bound }
.add_to_diagnostic(err);
}
infer::DataBorrowed(ty, span) => {
RegionOriginNote::WithName {
span,
msg: fluent::infer_data_borrowed,
name: &self.ty_to_string(ty),
continues: false,
}
.add_to_diagnostic(err);
}
infer::ReferenceOutlivesReferent(ty, span) => {
RegionOriginNote::WithName {
span,
Expand Down Expand Up @@ -227,32 +218,6 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
);
err
}
infer::DataBorrowed(ty, span) => {
let mut err = struct_span_err!(
self.tcx.sess,
span,
E0490,
"a value of type `{}` is borrowed for too long",
self.ty_to_string(ty)
);
note_and_explain_region(
self.tcx,
&mut err,
"the type is valid for ",
sub,
"",
None,
);
note_and_explain_region(
self.tcx,
&mut err,
"but the borrow lasts for ",
sup,
"",
None,
);
err
}
infer::ReferenceOutlivesReferent(ty, span) => {
let mut err = struct_span_err!(
self.tcx.sess,
Expand Down
25 changes: 3 additions & 22 deletions compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,26 +702,8 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
// Obtain the spans for all the places that can
// influence the constraints on this value for
// richer diagnostics in `static_impl_trait`.
let influences: Vec<Span> = self
.data
.constraints
.iter()
.filter_map(|(constraint, origin)| match (constraint, origin) {
(
Constraint::VarSubVar(_, sup),
SubregionOrigin::DataBorrowed(_, sp),
) if sup == &node_vid => Some(*sp),
_ => None,
})
.collect();

self.collect_error_for_expanding_node(
graph,
&mut dup_vec,
node_vid,
errors,
influences,
);

self.collect_error_for_expanding_node(graph, &mut dup_vec, node_vid, errors);
}
}
}
Expand Down Expand Up @@ -775,7 +757,6 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
dup_vec: &mut IndexVec<RegionVid, Option<RegionVid>>,
node_idx: RegionVid,
errors: &mut Vec<RegionResolutionError<'tcx>>,
influences: Vec<Span>,
) {
// Errors in expanding nodes result from a lower-bound that is
// not contained by an upper-bound.
Expand Down Expand Up @@ -830,7 +811,7 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
lower_bound.region,
upper_bound.origin.clone(),
upper_bound.region,
influences,
vec![],
));
return;
}
Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,9 +410,6 @@ pub enum SubregionOrigin<'tcx> {
/// Creating a pointer `b` to contents of another reference
Reborrow(Span),

/// Data with type `Ty<'tcx>` was borrowed
DataBorrowed(Ty<'tcx>, Span),

/// (&'a &'b T) where a >= b
ReferenceOutlivesReferent(Ty<'tcx>, Span),

Expand Down Expand Up @@ -1978,7 +1975,6 @@ impl<'tcx> SubregionOrigin<'tcx> {
RelateParamBound(a, ..) => a,
RelateRegionParamBound(a) => a,
Reborrow(a) => a,
DataBorrowed(_, a) => a,
ReferenceOutlivesReferent(_, a) => a,
CompareImplItemObligation { span, .. } => span,
AscribeUserTypeProvePredicate(span) => span,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ fn test_unstable_options_tracking_hash() {
tracked!(link_only, true);
tracked!(llvm_plugins, vec![String::from("plugin_name")]);
tracked!(location_detail, LocationDetail { file: true, line: false, column: false });
tracked!(log_backtrace, Some("filter".to_string()));
tracked!(maximal_hir_to_mir_coverage, true);
tracked!(merge_functions, Some(MergeFunctions::Disabled));
tracked!(mir_emit_retag, true);
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_log/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ edition = "2021"
tracing = "0.1.28"
tracing-subscriber = { version = "0.3.3", default-features = false, features = ["fmt", "env-filter", "smallvec", "parking_lot", "ansi"] }
tracing-tree = "0.2.0"
tracing-core = "0.1.28"

[dev-dependencies]
rustc_span = { path = "../rustc_span" }
Expand Down
58 changes: 56 additions & 2 deletions compiler/rustc_log/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,34 @@
use std::env::{self, VarError};
use std::fmt::{self, Display};
use std::io::{self, IsTerminal};
use tracing_core::{Event, Subscriber};
use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter};
use tracing_subscriber::fmt::{
format::{self, FormatEvent, FormatFields},
FmtContext,
};
use tracing_subscriber::layer::SubscriberExt;

pub fn init_rustc_env_logger() -> Result<(), Error> {
init_env_logger("RUSTC_LOG")
init_rustc_env_logger_with_backtrace_option(&None)
}

pub fn init_rustc_env_logger_with_backtrace_option(
backtrace_target: &Option<String>,
) -> Result<(), Error> {
init_env_logger_with_backtrace_option("RUSTC_LOG", backtrace_target)
}

/// In contrast to `init_rustc_env_logger` this allows you to choose an env var
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) -> Result<(), Error> {
init_env_logger_with_backtrace_option(env, &None)
}

pub fn init_env_logger_with_backtrace_option(
env: &str,
backtrace_target: &Option<String>,
) -> Result<(), Error> {
let filter = match env::var(env) {
Ok(env) => EnvFilter::new(env),
_ => EnvFilter::default().add_directive(Directive::from(LevelFilter::WARN)),
Expand Down Expand Up @@ -88,11 +106,47 @@ pub fn init_env_logger(env: &str) -> Result<(), Error> {
let layer = layer.with_thread_ids(true).with_thread_names(true);

let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
match backtrace_target {
Some(str) => {
let fmt_layer = tracing_subscriber::fmt::layer()
.with_writer(io::stderr)
.without_time()
.event_format(BacktraceFormatter { backtrace_target: str.to_string() });
let subscriber = subscriber.with(fmt_layer);
tracing::subscriber::set_global_default(subscriber).unwrap();
}
None => {
tracing::subscriber::set_global_default(subscriber).unwrap();
}
};

Ok(())
}

struct BacktraceFormatter {
backtrace_target: String,
}

impl<S, N> FormatEvent<S, N> for BacktraceFormatter
where
S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
_ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let target = event.metadata().target();
if !target.contains(&self.backtrace_target) {
return Ok(());
}
let backtrace = std::backtrace::Backtrace::capture();
writeln!(writer, "stack backtrace: \n{:?}", backtrace)
}
}

pub fn stdout_isatty() -> bool {
io::stdout().is_terminal()
}
Expand Down
24 changes: 20 additions & 4 deletions compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,26 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
return Ok(quote! { #diag.subdiagnostic(#binding); });
}
}
(Meta::List(_), "subdiagnostic") => {
throw_invalid_attr!(attr, &meta, |diag| {
diag.help("`subdiagnostic` does not support nested attributes")
})
(Meta::List(MetaList { ref nested, .. }), "subdiagnostic") => {
if nested.len() == 1
&& let Some(NestedMeta::Meta(Meta::Path(path))) = nested.first()
&& path.is_ident("eager") {
let handler = match &self.parent.kind {
DiagnosticDeriveKind::Diagnostic { handler } => handler,
DiagnosticDeriveKind::LintDiagnostic => {
throw_invalid_attr!(attr, &meta, |diag| {
diag.help("eager subdiagnostics are not supported on lints")
})
}
};
return Ok(quote! { #diag.eager_subdiagnostic(#handler, #binding); });
} else {
throw_invalid_attr!(attr, &meta, |diag| {
diag.help(
"`eager` is the only supported nested attribute for `subdiagnostic`",
)
})
}
}
_ => (),
}
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![feature(allow_internal_unstable)]
#![feature(if_let_guard)]
#![feature(let_chains)]
#![feature(never_type)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_span)]
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_resolve/src/build_reduced_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,15 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
self.r.field_names.insert(def_id, field_names);
}

fn insert_field_visibilities_local(&mut self, def_id: DefId, vdata: &ast::VariantData) {
let field_vis = vdata
.fields()
.iter()
.map(|field| field.vis.span.until(field.ident.map_or(field.ty.span, |i| i.span)))
.collect();
self.r.field_visibility_spans.insert(def_id, field_vis);
}

fn insert_field_names_extern(&mut self, def_id: DefId) {
let field_names =
self.r.cstore().struct_field_names_untracked(def_id, self.r.session).collect();
Expand Down Expand Up @@ -737,6 +746,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {

// Record field names for error reporting.
self.insert_field_names_local(def_id, vdata);
self.insert_field_visibilities_local(def_id, vdata);

// If this is a tuple or unit struct, define a name
// in the value namespace as well.
Expand Down Expand Up @@ -770,6 +780,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id.to_def_id());
self.r.define(parent, ident, ValueNS, (ctor_res, ctor_vis, sp, expansion));
self.r.visibilities.insert(ctor_def_id, ctor_vis);
// We need the field visibility spans also for the constructor for E0603.
self.insert_field_visibilities_local(ctor_def_id.to_def_id(), vdata);

self.r
.struct_constructors
Expand All @@ -783,6 +795,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {

// Record field names for error reporting.
self.insert_field_names_local(def_id, vdata);
self.insert_field_visibilities_local(def_id, vdata);
}

ItemKind::Trait(..) => {
Expand Down Expand Up @@ -1510,6 +1523,7 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> {

// Record field names for error reporting.
self.insert_field_names_local(def_id.to_def_id(), &variant.data);
self.insert_field_visibilities_local(def_id.to_def_id(), &variant.data);

visit::walk_variant(self, variant);
}
Expand Down
14 changes: 13 additions & 1 deletion compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use rustc_ast::{self as ast, Crate, ItemKind, ModKind, NodeId, Path, CRATE_NODE_
use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::struct_span_err;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan};
use rustc_errors::{
pluralize, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
};
use rustc_feature::BUILTIN_ATTRIBUTES;
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS};
Expand Down Expand Up @@ -1604,6 +1606,16 @@ impl<'a> Resolver<'a> {
err.span_label(ident.span, &format!("private {}", descr));
if let Some(span) = ctor_fields_span {
err.span_label(span, "a constructor is private if any of the fields is private");
if let Res::Def(_, d) = res && let Some(fields) = self.field_visibility_spans.get(&d) {
err.multipart_suggestion_verbose(
&format!(
"consider making the field{} publicly accessible",
pluralize!(fields.len())
),
fields.iter().map(|span| (*span, "pub ".to_string())).collect(),
Applicability::MaybeIncorrect,
);
}
}

// Print the whole import chain to make it easier to see what happens.
Expand Down
Loading