diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 6c1eaa809c905..05b19fcfb999a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -187,6 +187,12 @@ impl Display for RegionName { } } +impl rustc_errors::IntoDiagnosticArg for RegionName { + fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { + self.to_string().into_diagnostic_arg() + } +} + impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId { self.body.source.def_id().expect_local() diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index 9f19453a1a658..24f672de97bc6 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,4 +1,4 @@ -use rustc_errors::{IntoDiagnosticArg, MultiSpan}; +use rustc_errors::MultiSpan; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::Ty; use rustc_span::Span; @@ -137,18 +137,6 @@ pub(crate) enum LifetimeReturnCategoryErr<'a> { }, } -impl IntoDiagnosticArg for &RegionName { - fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { - format!("{}", self).into_diagnostic_arg() - } -} - -impl IntoDiagnosticArg for RegionName { - fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> { - format!("{}", self).into_diagnostic_arg() - } -} - #[derive(Subdiagnostic)] pub(crate) enum RequireStaticErr { #[note(borrowck::used_impl_require_static)] diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index c768935eb6238..e1872243a4a68 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -1210,6 +1210,9 @@ static DEFAULT_HOOK: LazyLock) + Sync + Send + /// /// When `install_ice_hook` is called, this function will be called as the panic /// hook. +// FIXME(translation): need struct diagnostics implemented on `Handler` +#[allow(rustc::untranslatable_diagnostic)] +#[allow(rustc::diagnostic_outside_of_impl)] pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false); diff --git a/compiler/rustc_error_messages/locales/en-US/incremental.ftl b/compiler/rustc_error_messages/locales/en-US/incremental.ftl new file mode 100644 index 0000000000000..ed9a22c02d181 --- /dev/null +++ b/compiler/rustc_error_messages/locales/en-US/incremental.ftl @@ -0,0 +1,106 @@ +incremental_unrecognized_depnode = unrecognized `DepNode` variant: {$name} + +incremental_missing_depnode = missing `DepNode` variant + +incremental_missing_if_this_changed = no `#[rustc_if_this_changed]` annotation detected + +incremental_no_path = no path from `{$source}` to `{$target}` + +incremental_ok = OK + +incremental_unknown_reuse_kind = unknown cgu-reuse-kind `{$kind}` specified + +incremental_missing_query_depgraph = found CGU-reuse attribute but `-Zquery-dep-graph` was not specified + +incremental_malformed_cgu_name = + found malformed codegen unit name `{$user_path}`. codegen units names must always start with the name of the crate (`{$crate_name}` in this case). + +incremental_no_module_named = no module named `{$user_path}` (mangled: {$cgu_name}). available modules: {$cgu_names} + +incremental_field_associated_value_expected = associated value expected for `{$name}` + +incremental_no_field = no field `{$name}` + +incremental_assertion_auto = `except` specified DepNodes that can not be affected for \"{$name}\": \"{$e}\" + +incremental_undefined_clean_dirty_assertions_item = clean/dirty auto-assertions not yet defined for Node::Item.node={$kind} + +incremental_undefined_clean_dirty_assertions = clean/dirty auto-assertions not yet defined for {$kind} + +incremental_repeated_depnode_label = dep-node label `{$label}` is repeated + +incremental_unrecognized_depnode_label = dep-node label `{$label}` not recognized + +incremental_not_dirty = `{$dep_node_str}` should be dirty but is not + +incremental_not_clean = `{$dep_node_str}` should be clean but is not + +incremental_not_loaded = `{$dep_node_str}` should have been loaded from disk but it was not + +incremental_unknown_item = unknown item `{$name}` + +incremental_no_cfg = no cfg attribute + +incremental_associated_value_expected_for = associated value expected for `{$ident}` + +incremental_associated_value_expected = expected an associated value + +incremental_unchecked_clean = found unchecked `#[rustc_clean]` attribute + +incremental_delete_old = unable to delete old {$name} at `{$path}`: {$err} + +incremental_create_new = failed to create {$name} at `{$path}`: {$err} + +incremental_write_new = failed to write {$name} to `{$path}`: {$err} + +incremental_canonicalize_path = incremental compilation: error canonicalizing path `{$path}`: {$err} + +incremental_create_incr_comp_dir = could not create incremental compilation {$tag} directory `{$path}`: {$err} + +incremental_create_lock = incremental compilation: could not create session directory lock file: {$lock_err} + .lock_unsupported = the filesystem for the incremental path at {$session_dir} does not appear to support locking, consider changing the incremental path to a filesystem that supports locking or disable incremental compilation + .cargo_help_1 = incremental compilation can be disabled by setting the environment variable CARGO_INCREMENTAL=0 (see https://doc.rust-lang.org/cargo/reference/profiles.html#incremental) + .cargo_help_2 = the entire build directory can be changed to a different filesystem by setting the environment variable CARGO_TARGET_DIR to a different path (see https://doc.rust-lang.org/cargo/reference/config.html#buildtarget-dir) + +incremental_delete_lock = error deleting lock file for incremental compilation session directory `{$path}`: {$err} + +incremental_hard_link_failed = + hard linking files in the incremental compilation cache failed. copying files instead. consider moving the cache directory to a file system which supports hard linking in session dir `{$path}` + +incremental_delete_partial = failed to delete partly initialized session dir `{$path}`: {$err} + +incremental_delete_full = error deleting incremental compilation session directory `{$path}`: {$err} + +incremental_finalize = error finalizing incremental compilation session directory `{$path}`: {$err} + +incremental_invalid_gc_failed = + failed to garbage collect invalid incremental compilation session directory `{$path}`: {$err} + +incremental_finalized_gc_failed = + failed to garbage collect finalized incremental compilation session directory `{$path}`: {$err} + +incremental_session_gc_failed = + failed to garbage collect incremental compilation session directory `{$path}`: {$err} + +incremental_assert_not_loaded = + we asserted that the incremental cache should not be loaded, but it was loaded + +incremental_assert_loaded = + we asserted that an existing incremental cache directory should be successfully loaded, but it was not + +incremental_delete_incompatible = + failed to delete invalidated or incompatible incremental compilation session directory contents `{$path}`: {$err} + +incremental_load_dep_graph = could not load dep-graph from `{$path}`: {$err} + +incremental_decode_incr_cache = could not decode incremental cache: {$err} + +incremental_write_dep_graph = failed to write dependency graph to `{$path}`: {$err} + +incremental_move_dep_graph = failed to move dependency graph from `{$from}` to `{$to}`: {$err} + +incremental_create_dep_graph = failed to create dependency graph at `{$path}`: {$err} + +incremental_copy_workproduct_to_cache = error copying object file `{$from}` to incremental directory as `{$to}`: {$err} + +incremental_delete_workproduct = file-system error deleting outdated file `{$path}`: {$err} diff --git a/compiler/rustc_error_messages/locales/en-US/interface.ftl b/compiler/rustc_error_messages/locales/en-US/interface.ftl index bbcb8fc28cffa..c7ebb920ec84f 100644 --- a/compiler/rustc_error_messages/locales/en-US/interface.ftl +++ b/compiler/rustc_error_messages/locales/en-US/interface.ftl @@ -41,3 +41,13 @@ interface_rustc_error_unexpected_annotation = interface_failed_writing_file = failed to write file {$path}: {$error}" + +interface_unsupported_crate_type_for_target = + dropping unsupported crate type `{$crate_type}` for target `{$target_triple}` + +interface_multiple_output_types_adaption = + due to multiple output types requested, the explicitly specified output file name will be adapted for each output type + +interface_ignoring_extra_filename = ignoring -C extra-filename flag due to -o flag + +interface_ignoring_out_dir = ignoring --out-dir flag due to -o flag diff --git a/compiler/rustc_error_messages/locales/en-US/monomorphize.ftl b/compiler/rustc_error_messages/locales/en-US/monomorphize.ftl index 42c84fdd2d14b..5839a47fb6708 100644 --- a/compiler/rustc_error_messages/locales/en-US/monomorphize.ftl +++ b/compiler/rustc_error_messages/locales/en-US/monomorphize.ftl @@ -24,3 +24,9 @@ monomorphize_large_assignments = monomorphize_requires_lang_item = requires `{$lang_item}` lang_item + +monomorphize_encountered_error_while_instantiating = + the above error was encountered while instantiating `{$formatted_item}` + +monomorphize_unknown_cgu_collection_mode = + unknown codegen-item collection mode '{$mode}', falling back to 'lazy' mode diff --git a/compiler/rustc_error_messages/locales/en-US/session.ftl b/compiler/rustc_error_messages/locales/en-US/session.ftl index 76cae3c81e451..bffd720b39d0c 100644 --- a/compiler/rustc_error_messages/locales/en-US/session.ftl +++ b/compiler/rustc_error_messages/locales/en-US/session.ftl @@ -66,3 +66,5 @@ session_crate_name_invalid = crate names cannot start with a `-`, but `{$s}` has session_crate_name_empty = crate name must not be empty session_invalid_character_in_create_name = invalid character `{$character}` in crate name: `{$crate_name}` + +session_optimization_fuel_exhausted = optimization-fuel-exhausted: {$msg} diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index ff33ae7e8f224..05479d78a3d52 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -43,24 +43,25 @@ fluent_messages! { const_eval => "../locales/en-US/const_eval.ftl", driver => "../locales/en-US/driver.ftl", expand => "../locales/en-US/expand.ftl", - session => "../locales/en-US/session.ftl", - interface => "../locales/en-US/interface.ftl", + incremental => "../locales/en-US/incremental.ftl", infer => "../locales/en-US/infer.ftl", + interface => "../locales/en-US/interface.ftl", lint => "../locales/en-US/lint.ftl", + metadata => "../locales/en-US/metadata.ftl", middle => "../locales/en-US/middle.ftl", + mir_dataflow => "../locales/en-US/mir_dataflow.ftl", monomorphize => "../locales/en-US/monomorphize.ftl", - metadata => "../locales/en-US/metadata.ftl", parser => "../locales/en-US/parser.ftl", passes => "../locales/en-US/passes.ftl", plugin_impl => "../locales/en-US/plugin_impl.ftl", privacy => "../locales/en-US/privacy.ftl", query_system => "../locales/en-US/query_system.ftl", - trait_selection => "../locales/en-US/trait_selection.ftl", save_analysis => "../locales/en-US/save_analysis.ftl", + session => "../locales/en-US/session.ftl", + symbol_mangling => "../locales/en-US/symbol_mangling.ftl", + trait_selection => "../locales/en-US/trait_selection.ftl", ty_utils => "../locales/en-US/ty_utils.ftl", typeck => "../locales/en-US/typeck.ftl", - mir_dataflow => "../locales/en-US/mir_dataflow.ftl", - symbol_mangling => "../locales/en-US/symbol_mangling.ftl", } pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES}; diff --git a/compiler/rustc_errors/Cargo.toml b/compiler/rustc_errors/Cargo.toml index c36ca11fad6f2..dd96348153959 100644 --- a/compiler/rustc_errors/Cargo.toml +++ b/compiler/rustc_errors/Cargo.toml @@ -7,22 +7,22 @@ edition = "2021" doctest = false [dependencies] -tracing = "0.1" +annotate-snippets = "0.9" +atty = "0.2" +rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_messages = { path = "../rustc_error_messages" } +rustc_hir = { path = "../rustc_hir" } +rustc_lint_defs = { path = "../rustc_lint_defs" } +rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } -rustc_macros = { path = "../rustc_macros" } -rustc_data_structures = { path = "../rustc_data_structures" } rustc_target = { path = "../rustc_target" } -rustc_hir = { path = "../rustc_hir" } -rustc_lint_defs = { path = "../rustc_lint_defs" } -unicode-width = "0.1.4" -atty = "0.2" -termcolor = "1.0" -annotate-snippets = "0.9" -termize = "0.1.1" serde = { version = "1.0.125", features = [ "derive" ] } serde_json = "1.0.59" +termcolor = "1.0" +termize = "0.1.1" +tracing = "0.1" +unicode-width = "0.1.4" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = [ "handleapi", "synchapi", "winbase" ] } diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index a52e95e92d55c..1de0f0e774267 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -43,6 +43,12 @@ pub trait IntoDiagnosticArg { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static>; } +impl<'a, T: Clone + IntoDiagnosticArg> IntoDiagnosticArg for &'a T { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + self.clone().into_diagnostic_arg() + } +} + pub struct DiagnosticArgFromDisplay<'a>(pub &'a dyn fmt::Display); impl IntoDiagnosticArg for DiagnosticArgFromDisplay<'_> { @@ -94,7 +100,7 @@ into_diagnostic_arg_using_display!( MacroRulesNormalizedIdent, ParseIntError, StackProtector, - &TargetTriple, + TargetTriple, SplitDebuginfo ); diff --git a/compiler/rustc_errors/src/diagnostic_builder.rs b/compiler/rustc_errors/src/diagnostic_builder.rs index b4ba65ca96d3b..ed4095fd354ae 100644 --- a/compiler/rustc_errors/src/diagnostic_builder.rs +++ b/compiler/rustc_errors/src/diagnostic_builder.rs @@ -242,6 +242,56 @@ impl EmissionGuarantee for () { } } +/// Marker type which enables implementation of `create_note` and `emit_note` functions for +/// note-without-error struct diagnostics. +#[derive(Copy, Clone)] +pub struct Noted; + +impl<'a> DiagnosticBuilder<'a, Noted> { + /// Convenience function for internal use, clients should use one of the + /// `struct_*` methods on [`Handler`]. + pub(crate) fn new_note(handler: &'a Handler, message: impl Into) -> Self { + let diagnostic = Diagnostic::new_with_code(Level::Note, None, message); + Self::new_diagnostic_note(handler, diagnostic) + } + + /// Creates a new `DiagnosticBuilder` with an already constructed + /// diagnostic. + pub(crate) fn new_diagnostic_note(handler: &'a Handler, diagnostic: Diagnostic) -> Self { + debug!("Created new diagnostic"); + Self { + inner: DiagnosticBuilderInner { + state: DiagnosticBuilderState::Emittable(handler), + diagnostic: Box::new(diagnostic), + }, + _marker: PhantomData, + } + } +} + +impl EmissionGuarantee for Noted { + fn diagnostic_builder_emit_producing_guarantee(db: &mut DiagnosticBuilder<'_, Self>) -> Self { + match db.inner.state { + // First `.emit()` call, the `&Handler` is still available. + DiagnosticBuilderState::Emittable(handler) => { + db.inner.state = DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation; + handler.emit_diagnostic(&mut db.inner.diagnostic); + } + // `.emit()` was previously called, disallowed from repeating it. + DiagnosticBuilderState::AlreadyEmittedOrDuringCancellation => {} + } + + Noted + } + + fn make_diagnostic_builder( + handler: &Handler, + msg: impl Into, + ) -> DiagnosticBuilder<'_, Self> { + DiagnosticBuilder::new_note(handler, msg) + } +} + impl<'a> DiagnosticBuilder<'a, !> { /// Convenience function for internal use, clients should use one of the /// `struct_*` methods on [`Handler`]. diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 68971cebc3527..d4be147a99d06 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -374,7 +374,7 @@ pub use diagnostic::{ AddToDiagnostic, DecorateLint, Diagnostic, DiagnosticArg, DiagnosticArgFromDisplay, DiagnosticArgValue, DiagnosticId, DiagnosticStyledString, IntoDiagnosticArg, SubDiagnostic, }; -pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, LintDiagnosticBuilder}; +pub use diagnostic_builder::{DiagnosticBuilder, EmissionGuarantee, LintDiagnosticBuilder, Noted}; use std::backtrace::Backtrace; /// A handler deals with errors and other compiler output. @@ -941,6 +941,7 @@ impl Handler { self.emit_diag_at_span(Diagnostic::new(Bug, msg), span); } + #[rustc_lint_diagnostics] pub fn span_note_without_error( &self, span: impl Into, @@ -949,6 +950,7 @@ impl Handler { self.emit_diag_at_span(Diagnostic::new(Note, msg), span); } + #[rustc_lint_diagnostics] pub fn span_note_diag( &self, span: Span, @@ -960,19 +962,23 @@ impl Handler { } // NOTE: intentionally doesn't raise an error so rustc_codegen_ssa only reports fatal errors in the main thread + #[rustc_lint_diagnostics] pub fn fatal(&self, msg: impl Into) -> FatalError { self.inner.borrow_mut().fatal(msg) } + #[rustc_lint_diagnostics] pub fn err(&self, msg: impl Into) -> ErrorGuaranteed { self.inner.borrow_mut().err(msg) } + #[rustc_lint_diagnostics] pub fn warn(&self, msg: impl Into) { let mut db = DiagnosticBuilder::new(self, Warning(None), msg); db.emit(); } + #[rustc_lint_diagnostics] pub fn note_without_error(&self, msg: impl Into) { DiagnosticBuilder::new(self, Note, msg).emit(); } diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 69e482ce854c0..95b48c38218d0 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -33,6 +33,7 @@ //! fn baz() { foo(); } //! ``` +use crate::errors; use rustc_ast as ast; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::implementation::{Direction, NodeIndex, INCOMING, OUTGOING}; @@ -133,12 +134,10 @@ impl<'tcx> IfThisChanged<'tcx> { Some(n) => { match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) { Ok(n) => n, - Err(()) => { - self.tcx.sess.span_fatal( - attr.span, - &format!("unrecognized DepNode variant {:?}", n), - ); - } + Err(()) => self.tcx.sess.emit_fatal(errors::UnrecognizedDepNode { + span: attr.span, + name: n, + }), } } }; @@ -149,16 +148,14 @@ impl<'tcx> IfThisChanged<'tcx> { Some(n) => { match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) { Ok(n) => n, - Err(()) => { - self.tcx.sess.span_fatal( - attr.span, - &format!("unrecognized DepNode variant {:?}", n), - ); - } + Err(()) => self.tcx.sess.emit_fatal(errors::UnrecognizedDepNode { + span: attr.span, + name: n, + }), } } None => { - self.tcx.sess.span_fatal(attr.span, "missing DepNode variant"); + self.tcx.sess.emit_fatal(errors::MissingDepNode { span: attr.span }); } }; self.then_this_would_need.push(( @@ -204,7 +201,7 @@ fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_wou // Return early here so as not to construct the query, which is not cheap. if if_this_changed.is_empty() { for &(target_span, _, _, _) in then_this_would_need { - tcx.sess.span_err(target_span, "no `#[rustc_if_this_changed]` annotation detected"); + tcx.sess.emit_err(errors::MissingIfThisChanged { span: target_span }); } return; } @@ -213,16 +210,13 @@ fn check_paths<'tcx>(tcx: TyCtxt<'tcx>, if_this_changed: &Sources, then_this_wou let dependents = query.transitive_predecessors(source_dep_node); for &(target_span, ref target_pass, _, ref target_dep_node) in then_this_would_need { if !dependents.contains(&target_dep_node) { - tcx.sess.span_err( - target_span, - &format!( - "no path from `{}` to `{}`", - tcx.def_path_str(source_def_id), - target_pass - ), - ); + tcx.sess.emit_err(errors::NoPath { + span: target_span, + source: tcx.def_path_str(source_def_id), + target: *target_pass, + }); } else { - tcx.sess.span_err(target_span, "OK"); + tcx.sess.emit_err(errors::Ok { span: target_span }); } } } diff --git a/compiler/rustc_incremental/src/assert_module_sources.rs b/compiler/rustc_incremental/src/assert_module_sources.rs index 89d419bc8e90f..2968a0e1203a9 100644 --- a/compiler/rustc_incremental/src/assert_module_sources.rs +++ b/compiler/rustc_incremental/src/assert_module_sources.rs @@ -22,6 +22,7 @@ //! allows for doing a more fine-grained check to see if pre- or post-lto data //! was re-used. +use crate::errors; use rustc_ast as ast; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::LOCAL_CRATE; @@ -66,10 +67,9 @@ impl<'tcx> AssertModuleSource<'tcx> { sym::post_dash_lto => (CguReuse::PostLto, ComparisonKind::Exact), sym::any => (CguReuse::PreLto, ComparisonKind::AtLeast), other => { - self.tcx.sess.span_fatal( - attr.span, - &format!("unknown cgu-reuse-kind `{}` specified", other), - ); + self.tcx + .sess + .emit_fatal(errors::UnknownReuseKind { span: attr.span, kind: other }); } } } else { @@ -77,10 +77,7 @@ impl<'tcx> AssertModuleSource<'tcx> { }; if !self.tcx.sess.opts.unstable_opts.query_dep_graph { - self.tcx.sess.span_fatal( - attr.span, - "found CGU-reuse attribute but `-Zquery-dep-graph` was not specified", - ); + self.tcx.sess.emit_fatal(errors::MissingQueryDepGraph { span: attr.span }); } if !self.check_config(attr) { @@ -92,13 +89,11 @@ impl<'tcx> AssertModuleSource<'tcx> { let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_string(); if !user_path.starts_with(&crate_name) { - let msg = format!( - "Found malformed codegen unit name `{}`. \ - Codegen units names must always start with the name of the \ - crate (`{}` in this case).", - user_path, crate_name - ); - self.tcx.sess.span_fatal(attr.span, &msg); + self.tcx.sess.emit_fatal(errors::MalformedCguName { + span: attr.span, + user_path, + crate_name, + }); } // Split of the "special suffix" if there is one. @@ -125,15 +120,12 @@ impl<'tcx> AssertModuleSource<'tcx> { let mut cgu_names: Vec<&str> = self.available_cgus.iter().map(|cgu| cgu.as_str()).collect(); cgu_names.sort(); - self.tcx.sess.span_err( - attr.span, - &format!( - "no module named `{}` (mangled: {}). Available modules: {}", - user_path, - cgu_name, - cgu_names.join(", ") - ), - ); + self.tcx.sess.emit_err(errors::NoModuleNamed { + span: attr.span, + user_path, + cgu_name, + cgu_names: cgu_names.join(", "), + }); } self.tcx.sess.cgu_reuse_tracker.set_expectation( @@ -151,15 +143,15 @@ impl<'tcx> AssertModuleSource<'tcx> { if let Some(value) = item.value_str() { return value; } else { - self.tcx.sess.span_fatal( - item.span(), - &format!("associated value expected for `{}`", name), - ); + self.tcx.sess.emit_fatal(errors::FieldAssociatedValueExpected { + span: item.span(), + name, + }); } } } - self.tcx.sess.span_fatal(attr.span, &format!("no field `{}`", name)); + self.tcx.sess.emit_fatal(errors::NoField { span: attr.span, name }); } /// Scan for a `cfg="foo"` attribute and check whether we have a diff --git a/compiler/rustc_incremental/src/errors.rs b/compiler/rustc_incremental/src/errors.rs new file mode 100644 index 0000000000000..842bb4809251e --- /dev/null +++ b/compiler/rustc_incremental/src/errors.rs @@ -0,0 +1,364 @@ +use rustc_macros::Diagnostic; +use rustc_span::{symbol::Ident, Span, Symbol}; +use std::path::{Path, PathBuf}; + +#[derive(Diagnostic)] +#[diag(incremental::unrecognized_depnode)] +pub struct UnrecognizedDepNode { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(incremental::missing_depnode)] +pub struct MissingDepNode { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::missing_if_this_changed)] +pub struct MissingIfThisChanged { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::ok)] +pub struct Ok { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::no_path)] +pub struct NoPath { + #[primary_span] + pub span: Span, + pub target: Symbol, + pub source: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::unknown_reuse_kind)] +pub struct UnknownReuseKind { + #[primary_span] + pub span: Span, + pub kind: Symbol, +} + +#[derive(Diagnostic)] +#[diag(incremental::missing_query_depgraph)] +pub struct MissingQueryDepGraph { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::malformed_cgu_name)] +pub struct MalformedCguName { + #[primary_span] + pub span: Span, + pub user_path: String, + pub crate_name: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::no_module_named)] +pub struct NoModuleNamed<'a> { + #[primary_span] + pub span: Span, + pub user_path: &'a str, + pub cgu_name: Symbol, + pub cgu_names: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::field_associated_value_expected)] +pub struct FieldAssociatedValueExpected { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(incremental::no_field)] +pub struct NoField { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(incremental::assertion_auto)] +pub struct AssertionAuto<'a> { + #[primary_span] + pub span: Span, + pub name: &'a str, + pub e: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::undefined_clean_dirty_assertions_item)] +pub struct UndefinedCleanDirtyItem { + #[primary_span] + pub span: Span, + pub kind: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::undefined_clean_dirty_assertions)] +pub struct UndefinedCleanDirty { + #[primary_span] + pub span: Span, + pub kind: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::repeated_depnode_label)] +pub struct RepeatedDepNodeLabel<'a> { + #[primary_span] + pub span: Span, + pub label: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::unrecognized_depnode_label)] +pub struct UnrecognizedDepNodeLabel<'a> { + #[primary_span] + pub span: Span, + pub label: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::not_dirty)] +pub struct NotDirty<'a> { + #[primary_span] + pub span: Span, + pub dep_node_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::not_clean)] +pub struct NotClean<'a> { + #[primary_span] + pub span: Span, + pub dep_node_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::not_loaded)] +pub struct NotLoaded<'a> { + #[primary_span] + pub span: Span, + pub dep_node_str: &'a str, +} + +#[derive(Diagnostic)] +#[diag(incremental::unknown_item)] +pub struct UnknownItem { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(incremental::no_cfg)] +pub struct NoCfg { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::associated_value_expected_for)] +pub struct AssociatedValueExpectedFor { + #[primary_span] + pub span: Span, + pub ident: Ident, +} + +#[derive(Diagnostic)] +#[diag(incremental::associated_value_expected)] +pub struct AssociatedValueExpected { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::unchecked_clean)] +pub struct UncheckedClean { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(incremental::delete_old)] +pub struct DeleteOld<'a> { + pub name: &'a str, + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::create_new)] +pub struct CreateNew<'a> { + pub name: &'a str, + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::write_new)] +pub struct WriteNew<'a> { + pub name: &'a str, + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::canonicalize_path)] +pub struct CanonicalizePath { + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::create_incr_comp_dir)] +pub struct CreateIncrCompDir<'a> { + pub tag: &'a str, + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::create_lock)] +pub struct CreateLock<'a> { + pub lock_err: std::io::Error, + pub session_dir: &'a Path, + #[note(incremental::lock_unsupported)] + pub is_unsupported_lock: Option<()>, + #[help(incremental::cargo_help_1)] + #[help(incremental::cargo_help_2)] + pub is_cargo: Option<()>, +} + +#[derive(Diagnostic)] +#[diag(incremental::delete_lock)] +pub struct DeleteLock<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::hard_link_failed)] +pub struct HardLinkFailed<'a> { + pub path: &'a Path, +} + +#[derive(Diagnostic)] +#[diag(incremental::delete_partial)] +pub struct DeletePartial<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::delete_full)] +pub struct DeleteFull<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::finalize)] +pub struct Finalize<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::invalid_gc_failed)] +pub struct InvalidGcFailed<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::finalized_gc_failed)] +pub struct FinalizedGcFailed<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::session_gc_failed)] +pub struct SessionGcFailed<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::assert_not_loaded)] +pub struct AssertNotLoaded; + +#[derive(Diagnostic)] +#[diag(incremental::assert_loaded)] +pub struct AssertLoaded; + +#[derive(Diagnostic)] +#[diag(incremental::delete_incompatible)] +pub struct DeleteIncompatible { + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::load_dep_graph)] +pub struct LoadDepGraph { + pub path: PathBuf, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::decode_incr_cache)] +pub struct DecodeIncrCache { + pub err: String, +} + +#[derive(Diagnostic)] +#[diag(incremental::write_dep_graph)] +pub struct WriteDepGraph<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::move_dep_graph)] +pub struct MoveDepGraph<'a> { + pub from: &'a Path, + pub to: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::create_dep_graph)] +pub struct CreateDepGraph<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::copy_workproduct_to_cache)] +pub struct CopyWorkProductToCache<'a> { + pub from: &'a Path, + pub to: &'a Path, + pub err: std::io::Error, +} + +#[derive(Diagnostic)] +#[diag(incremental::delete_workproduct)] +pub struct DeleteWorkProduct<'a> { + pub path: &'a Path, + pub err: std::io::Error, +} diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 2c9e21f769fb1..51d5030562d12 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -3,8 +3,11 @@ #![deny(missing_docs)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![cfg_attr(bootstrap, feature(let_else))] +#![feature(never_type)] #![recursion_limit = "256"] #![allow(rustc::potential_query_instability)] +#![deny(rustc::untranslatable_diagnostic)] +#![deny(rustc::diagnostic_outside_of_impl)] #[macro_use] extern crate rustc_middle; @@ -13,6 +16,7 @@ extern crate tracing; mod assert_dep_graph; pub mod assert_module_sources; +mod errors; mod persist; use assert_dep_graph::assert_dep_graph; diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 710c4a01b244f..4c815d69ff395 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -19,6 +19,7 @@ //! Errors are reported if we are in the suitable configuration but //! the required condition is not met. +use crate::errors; use rustc_ast::{self as ast, Attribute, NestedMetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::LocalDefId; @@ -198,11 +199,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { let loaded_from_disk = self.loaded_from_disk(attr); for e in except.iter() { if !auto.remove(e) { - let msg = format!( - "`except` specified DepNodes that can not be affected for \"{}\": \"{}\"", - name, e - ); - self.tcx.sess.span_fatal(attr.span, &msg); + self.tcx.sess.emit_fatal(errors::AssertionAuto { span: attr.span, name, e }); } } Assertion { clean: auto, dirty: except, loaded_from_disk } @@ -284,14 +281,10 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { // An implementation, eg `impl Trait for Foo { .. }` HirItem::Impl { .. } => ("ItemKind::Impl", LABELS_IMPL), - _ => self.tcx.sess.span_fatal( - attr.span, - &format!( - "clean/dirty auto-assertions not yet defined \ - for Node::Item.node={:?}", - item.kind - ), - ), + _ => self.tcx.sess.emit_fatal(errors::UndefinedCleanDirtyItem { + span: attr.span, + kind: format!("{:?}", item.kind), + }), } } HirNode::TraitItem(item) => match item.kind { @@ -304,10 +297,10 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL), ImplItemKind::TyAlias(..) => ("NodeImplType", LABELS_CONST_IN_IMPL), }, - _ => self.tcx.sess.span_fatal( - attr.span, - &format!("clean/dirty auto-assertions not yet defined for {:?}", node), - ), + _ => self.tcx.sess.emit_fatal(errors::UndefinedCleanDirty { + span: attr.span, + kind: format!("{:?}", node), + }), }; let labels = Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| (*l).to_string()))); @@ -320,16 +313,15 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { let label = label.trim(); if DepNode::has_label_string(label) { if out.contains(label) { - self.tcx.sess.span_fatal( - item.span(), - &format!("dep-node label `{}` is repeated", label), - ); + self.tcx + .sess + .emit_fatal(errors::RepeatedDepNodeLabel { span: item.span(), label }); } out.insert(label.to_string()); } else { self.tcx .sess - .span_fatal(item.span(), &format!("dep-node label `{}` not recognized", label)); + .emit_fatal(errors::UnrecognizedDepNodeLabel { span: item.span(), label }); } } out @@ -350,7 +342,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { let dep_node_str = self.dep_node_str(&dep_node); self.tcx .sess - .span_err(item_span, &format!("`{}` should be dirty but is not", dep_node_str)); + .emit_err(errors::NotDirty { span: item_span, dep_node_str: &dep_node_str }); } } @@ -361,7 +353,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { let dep_node_str = self.dep_node_str(&dep_node); self.tcx .sess - .span_err(item_span, &format!("`{}` should be clean but is not", dep_node_str)); + .emit_err(errors::NotClean { span: item_span, dep_node_str: &dep_node_str }); } } @@ -370,10 +362,9 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { if !self.tcx.dep_graph.debug_was_loaded_from_disk(dep_node) { let dep_node_str = self.dep_node_str(&dep_node); - self.tcx.sess.span_err( - item_span, - &format!("`{}` should have been loaded from disk but it was not", dep_node_str), - ); + self.tcx + .sess + .emit_err(errors::NotLoaded { span: item_span, dep_node_str: &dep_node_str }); } } @@ -414,12 +405,12 @@ fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool { debug!("check_config: searching for cfg {:?}", value); cfg = Some(config.contains(&(value, None))); } else if !(item.has_name(EXCEPT) || item.has_name(LOADED_FROM_DISK)) { - tcx.sess.span_err(attr.span, &format!("unknown item `{}`", item.name_or_empty())); + tcx.sess.emit_err(errors::UnknownItem { span: attr.span, name: item.name_or_empty() }); } } match cfg { - None => tcx.sess.span_fatal(attr.span, "no cfg attribute"), + None => tcx.sess.emit_fatal(errors::NoCfg { span: attr.span }), Some(c) => c, } } @@ -428,13 +419,11 @@ fn expect_associated_value(tcx: TyCtxt<'_>, item: &NestedMetaItem) -> Symbol { if let Some(value) = item.value_str() { value } else { - let msg = if let Some(ident) = item.ident() { - format!("associated value expected for `{}`", ident) + if let Some(ident) = item.ident() { + tcx.sess.emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident }); } else { - "expected an associated value".to_string() - }; - - tcx.sess.span_fatal(item.span(), &msg); + tcx.sess.emit_fatal(errors::AssociatedValueExpected { span: item.span() }); + } } } @@ -458,7 +447,7 @@ impl<'tcx> FindAllAttrs<'tcx> { fn report_unchecked_attrs(&self, mut checked_attrs: FxHashSet) { for attr in &self.found_attrs { if !checked_attrs.contains(&attr.id) { - self.tcx.sess.span_err(attr.span, "found unchecked `#[rustc_clean]` attribute"); + self.tcx.sess.emit_err(errors::UncheckedClean { span: attr.span }); checked_attrs.insert(attr.id); } } diff --git a/compiler/rustc_incremental/src/persist/file_format.rs b/compiler/rustc_incremental/src/persist/file_format.rs index 2dbd4b6bce85a..dc981c6179eeb 100644 --- a/compiler/rustc_incremental/src/persist/file_format.rs +++ b/compiler/rustc_incremental/src/persist/file_format.rs @@ -9,15 +9,15 @@ //! compiler versions don't change frequently for the typical user, being //! conservative here practically has no downside. -use std::env; -use std::fs; -use std::io::{self, Read}; -use std::path::{Path, PathBuf}; - +use crate::errors; use rustc_data_structures::memmap::Mmap; use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encoder; use rustc_session::Session; +use std::env; +use std::fs; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; /// The first few bytes of files generated by incremental compilation. const FILE_MAGIC: &[u8] = b"RSIC"; @@ -60,12 +60,7 @@ where } Err(err) if err.kind() == io::ErrorKind::NotFound => (), Err(err) => { - sess.err(&format!( - "unable to delete old {} at `{}`: {}", - name, - path_buf.display(), - err - )); + sess.emit_err(errors::DeleteOld { name, path: path_buf, err }); return; } } @@ -73,7 +68,7 @@ where let mut encoder = match FileEncoder::new(&path_buf) { Ok(encoder) => encoder, Err(err) => { - sess.err(&format!("failed to create {} at `{}`: {}", name, path_buf.display(), err)); + sess.emit_err(errors::CreateNew { name, path: path_buf, err }); return; } }; @@ -90,7 +85,7 @@ where debug!("save: data written to disk successfully"); } Err(err) => { - sess.err(&format!("failed to write {} to `{}`: {}", name, path_buf.display(), err)); + sess.emit_err(errors::WriteNew { name, path: path_buf, err }); } } } diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 25c1b2e1c4387..b7fe3263adc9f 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -103,6 +103,7 @@ //! unsupported file system and emit a warning in that case. This is not yet //! implemented. +use crate::errors; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::svh::Svh; use rustc_data_structures::{base_n, flock}; @@ -225,12 +226,7 @@ pub fn prepare_session_directory( let crate_dir = match crate_dir.canonicalize() { Ok(v) => v, Err(err) => { - let reported = sess.err(&format!( - "incremental compilation: error canonicalizing path `{}`: {}", - crate_dir.display(), - err - )); - return Err(reported); + return Err(sess.emit_err(errors::CanonicalizePath { path: crate_dir, err })); } }; @@ -273,14 +269,7 @@ pub fn prepare_session_directory( debug!("successfully copied data from: {}", source_directory.display()); if !allows_links { - sess.warn(&format!( - "Hard linking files in the incremental \ - compilation cache failed. Copying files \ - instead. Consider moving the cache \ - directory to a file system which supports \ - hard linking in session dir `{}`", - session_dir.display() - )); + sess.emit_warning(errors::HardLinkFailed { path: &session_dir }); } sess.init_incr_comp_session(session_dir, directory_lock, true); @@ -295,12 +284,7 @@ pub fn prepare_session_directory( // Try to remove the session directory we just allocated. We don't // know if there's any garbage in it from the failed copy action. if let Err(err) = safe_remove_dir_all(&session_dir) { - sess.warn(&format!( - "Failed to delete partly initialized \ - session dir `{}`: {}", - session_dir.display(), - err - )); + sess.emit_warning(errors::DeletePartial { path: &session_dir, err }); } delete_session_dir_lock_file(sess, &lock_file_path); @@ -332,12 +316,7 @@ pub fn finalize_session_directory(sess: &Session, svh: Svh) { ); if let Err(err) = safe_remove_dir_all(&*incr_comp_session_dir) { - sess.warn(&format!( - "Error deleting incremental compilation \ - session directory `{}`: {}", - incr_comp_session_dir.display(), - err - )); + sess.emit_warning(errors::DeleteFull { path: &incr_comp_session_dir, err }); } let lock_file_path = lock_file_path(&*incr_comp_session_dir); @@ -380,12 +359,7 @@ pub fn finalize_session_directory(sess: &Session, svh: Svh) { } Err(e) => { // Warn about the error. However, no need to abort compilation now. - sess.warn(&format!( - "Error finalizing incremental compilation \ - session directory `{}`: {}", - incr_comp_session_dir.display(), - e - )); + sess.emit_warning(errors::Finalize { path: &incr_comp_session_dir, err: e }); debug!("finalize_session_directory() - error, marking as invalid"); // Drop the file lock, so we can garage collect @@ -488,16 +462,7 @@ fn create_dir(sess: &Session, path: &Path, dir_tag: &str) -> Result<(), ErrorGua debug!("{} directory created successfully", dir_tag); Ok(()) } - Err(err) => { - let reported = sess.err(&format!( - "Could not create incremental compilation {} \ - directory `{}`: {}", - dir_tag, - path.display(), - err - )); - Err(reported) - } + Err(err) => Err(sess.emit_err(errors::CreateIncrCompDir { tag: dir_tag, path, err })), } } @@ -518,46 +483,20 @@ fn lock_directory( // the lock should be exclusive Ok(lock) => Ok((lock, lock_file_path)), Err(lock_err) => { - let mut err = sess.struct_err(&format!( - "incremental compilation: could not create \ - session directory lock file: {}", - lock_err - )); - if flock::Lock::error_unsupported(&lock_err) { - err.note(&format!( - "the filesystem for the incremental path at {} \ - does not appear to support locking, consider changing the \ - incremental path to a filesystem that supports locking \ - or disable incremental compilation", - session_dir.display() - )); - if std::env::var_os("CARGO").is_some() { - err.help( - "incremental compilation can be disabled by setting the \ - environment variable CARGO_INCREMENTAL=0 (see \ - https://doc.rust-lang.org/cargo/reference/profiles.html#incremental)", - ); - err.help( - "the entire build directory can be changed to a different \ - filesystem by setting the environment variable CARGO_TARGET_DIR \ - to a different path (see \ - https://doc.rust-lang.org/cargo/reference/config.html#buildtarget-dir)", - ); - } - } - Err(err.emit()) + let is_unsupported_lock = flock::Lock::error_unsupported(&lock_err).then_some(()); + Err(sess.emit_err(errors::CreateLock { + lock_err, + session_dir, + is_unsupported_lock, + is_cargo: std::env::var_os("CARGO").map(|_| ()), + })) } } } fn delete_session_dir_lock_file(sess: &Session, lock_file_path: &Path) { if let Err(err) = safe_remove_file(&lock_file_path) { - sess.warn(&format!( - "Error deleting lock file for incremental \ - compilation session directory `{}`: {}", - lock_file_path.display(), - err - )); + sess.emit_warning(errors::DeleteLock { path: lock_file_path, err }); } } @@ -774,12 +713,7 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { if !lock_file_to_session_dir.values().any(|dir| *dir == directory_name) { let path = crate_directory.join(directory_name); if let Err(err) = safe_remove_dir_all(&path) { - sess.warn(&format!( - "Failed to garbage collect invalid incremental \ - compilation session directory `{}`: {}", - path.display(), - err - )); + sess.emit_warning(errors::InvalidGcFailed { path: &path, err }); } } } @@ -885,12 +819,7 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { debug!("garbage_collect_session_directories() - deleting `{}`", path.display()); if let Err(err) = safe_remove_dir_all(&path) { - sess.warn(&format!( - "Failed to garbage collect finalized incremental \ - compilation session directory `{}`: {}", - path.display(), - err - )); + sess.emit_warning(errors::FinalizedGcFailed { path: &path, err }); } else { delete_session_dir_lock_file(sess, &lock_file_path(&path)); } @@ -907,11 +836,7 @@ fn delete_old(sess: &Session, path: &Path) { debug!("garbage_collect_session_directories() - deleting `{}`", path.display()); if let Err(err) = safe_remove_dir_all(&path) { - sess.warn(&format!( - "Failed to garbage collect incremental compilation session directory `{}`: {}", - path.display(), - err - )); + sess.emit_warning(errors::SessionGcFailed { path: &path, err }); } else { delete_session_dir_lock_file(sess, &lock_file_path(&path)); } diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index 1c5fd91690230..d5097065dda2e 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -1,5 +1,6 @@ //! Code to save/load the dep-graph from files. +use crate::errors; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::memmap::Mmap; use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId}; @@ -8,7 +9,7 @@ use rustc_serialize::opaque::MemDecoder; use rustc_serialize::Decodable; use rustc_session::config::IncrementalStateAssertion; use rustc_session::Session; -use std::path::Path; +use std::path::{Path, PathBuf}; use super::data::*; use super::file_format; @@ -27,11 +28,10 @@ pub enum LoadResult { }, /// The file either didn't exist or was produced by an incompatible compiler version. DataOutOfDate, - /// An error occurred. - Error { - #[allow(missing_docs)] - message: String, - }, + /// Loading the dep graph failed. + LoadDepGraph(PathBuf, std::io::Error), + /// Decoding loaded incremental cache failed. + DecodeIncrCache(Box), } impl LoadResult { @@ -40,36 +40,31 @@ impl LoadResult { // Check for errors when using `-Zassert-incremental-state` match (sess.opts.assert_incr_state, &self) { (Some(IncrementalStateAssertion::NotLoaded), LoadResult::Ok { .. }) => { - sess.fatal( - "We asserted that the incremental cache should not be loaded, \ - but it was loaded.", - ); + sess.emit_fatal(errors::AssertNotLoaded); } ( Some(IncrementalStateAssertion::Loaded), - LoadResult::Error { .. } | LoadResult::DataOutOfDate, + LoadResult::LoadDepGraph(..) + | LoadResult::DecodeIncrCache(..) + | LoadResult::DataOutOfDate, ) => { - sess.fatal( - "We asserted that an existing incremental cache directory should \ - be successfully loaded, but it was not.", - ); + sess.emit_fatal(errors::AssertLoaded); } _ => {} }; match self { - LoadResult::Error { message } => { - sess.warn(&message); + LoadResult::LoadDepGraph(path, err) => { + sess.emit_warning(errors::LoadDepGraph { path, err }); + Default::default() + } + LoadResult::DecodeIncrCache(err) => { + sess.emit_warning(errors::DecodeIncrCache { err: format!("{err:?}") }); Default::default() } LoadResult::DataOutOfDate => { if let Err(err) = delete_all_session_dir_contents(sess) { - sess.err(&format!( - "Failed to delete invalidated or incompatible \ - incremental compilation session directory contents `{}`: {}.", - dep_graph_path(sess).display(), - err - )); + sess.emit_err(errors::DeleteIncompatible { path: dep_graph_path(sess), err }); } Default::default() } @@ -90,9 +85,7 @@ fn load_data( // compiler version. Neither is an error. LoadResult::DataOutOfDate } - Err(err) => LoadResult::Error { - message: format!("could not load dep-graph from `{}`: {}", path.display(), err), - }, + Err(err) => LoadResult::LoadDepGraph(path.to_path_buf(), err), } } @@ -114,9 +107,9 @@ impl MaybeAsync> { pub fn open(self) -> LoadResult { match self { MaybeAsync::Sync(result) => result, - MaybeAsync::Async(handle) => handle.join().unwrap_or_else(|e| LoadResult::Error { - message: format!("could not decode incremental cache: {:?}", e), - }), + MaybeAsync::Async(handle) => { + handle.join().unwrap_or_else(|e| LoadResult::DecodeIncrCache(e)) + } } } } @@ -185,7 +178,8 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture { match load_data(report_incremental_info, &path, nightly_build) { LoadResult::DataOutOfDate => LoadResult::DataOutOfDate, - LoadResult::Error { message } => LoadResult::Error { message }, + LoadResult::LoadDepGraph(path, err) => LoadResult::LoadDepGraph(path, err), + LoadResult::DecodeIncrCache(err) => LoadResult::DecodeIncrCache(err), LoadResult::Ok { data: (bytes, start_pos) } => { let mut decoder = MemDecoder::new(&bytes, start_pos); let prev_commandline_args_hash = u64::decode(&mut decoder); diff --git a/compiler/rustc_incremental/src/persist/save.rs b/compiler/rustc_incremental/src/persist/save.rs index 710350314975c..7731351a80b7c 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -1,3 +1,4 @@ +use crate::errors; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::join; use rustc_middle::dep_graph::{DepGraph, SerializedDepGraph, WorkProduct, WorkProductId}; @@ -59,19 +60,14 @@ pub fn save_dep_graph(tcx: TyCtxt<'_>) { move || { sess.time("incr_comp_persist_dep_graph", || { if let Err(err) = tcx.dep_graph.encode(&tcx.sess.prof) { - sess.err(&format!( - "failed to write dependency graph to `{}`: {}", - staging_dep_graph_path.display(), - err - )); + sess.emit_err(errors::WriteDepGraph { path: &staging_dep_graph_path, err }); } if let Err(err) = fs::rename(&staging_dep_graph_path, &dep_graph_path) { - sess.err(&format!( - "failed to move dependency graph from `{}` to `{}`: {}", - staging_dep_graph_path.display(), - dep_graph_path.display(), - err - )); + sess.emit_err(errors::MoveDepGraph { + from: &staging_dep_graph_path, + to: &dep_graph_path, + err, + }); } }); }, @@ -163,11 +159,7 @@ pub fn build_dep_graph( let mut encoder = match FileEncoder::new(&path_buf) { Ok(encoder) => encoder, Err(err) => { - sess.err(&format!( - "failed to create dependency graph at `{}`: {}", - path_buf.display(), - err - )); + sess.emit_err(errors::CreateDepGraph { path: &path_buf, err }); return None; } }; diff --git a/compiler/rustc_incremental/src/persist/work_product.rs b/compiler/rustc_incremental/src/persist/work_product.rs index 2f1853c441eee..dc98fbeb0d166 100644 --- a/compiler/rustc_incremental/src/persist/work_product.rs +++ b/compiler/rustc_incremental/src/persist/work_product.rs @@ -2,6 +2,7 @@ //! //! [work products]: WorkProduct +use crate::errors; use crate::persist::fs::*; use rustc_data_structures::fx::FxHashMap; use rustc_fs_util::link_or_copy; @@ -28,12 +29,11 @@ pub fn copy_cgu_workproduct_to_incr_comp_cache_dir( let _ = saved_files.insert(ext.to_string(), file_name); } Err(err) => { - sess.warn(&format!( - "error copying object file `{}` to incremental directory as `{}`: {}", - path.display(), - path_in_incr_dir.display(), - err - )); + sess.emit_warning(errors::CopyWorkProductToCache { + from: &path, + to: &path_in_incr_dir, + err, + }); } } } @@ -49,11 +49,7 @@ pub fn delete_workproduct_files(sess: &Session, work_product: &WorkProduct) { for (_, path) in &work_product.saved_files { let path = in_incr_comp_dir_sess(sess, path); if let Err(err) = std_fs::remove_file(&path) { - sess.warn(&format!( - "file-system error deleting outdated file `{}`: {}", - path.display(), - err - )); + sess.emit_warning(errors::DeleteWorkProduct { path: &path, err }); } } } diff --git a/compiler/rustc_interface/Cargo.toml b/compiler/rustc_interface/Cargo.toml index da4002d09ad02..39fad22635d8e 100644 --- a/compiler/rustc_interface/Cargo.toml +++ b/compiler/rustc_interface/Cargo.toml @@ -45,6 +45,7 @@ rustc_plugin_impl = { path = "../rustc_plugin_impl" } rustc_privacy = { path = "../rustc_privacy" } rustc_query_impl = { path = "../rustc_query_impl" } rustc_resolve = { path = "../rustc_resolve" } +rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_ty_utils = { path = "../rustc_ty_utils" } @@ -54,9 +55,6 @@ libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["libloaderapi"] } -[dev-dependencies] -rustc_target = { path = "../rustc_target" } - [features] llvm = ['rustc_codegen_llvm'] rustc_use_parallel_compiler = ['rayon', 'rustc-rayon-core', 'rustc_query_impl/rustc_use_parallel_compiler'] diff --git a/compiler/rustc_interface/src/errors.rs b/compiler/rustc_interface/src/errors.rs index 097640f26c154..18f03735f34e1 100644 --- a/compiler/rustc_interface/src/errors.rs +++ b/compiler/rustc_interface/src/errors.rs @@ -1,5 +1,7 @@ use rustc_macros::Diagnostic; +use rustc_session::config::CrateType; use rustc_span::{Span, Symbol}; +use rustc_target::spec::TargetTriple; use std::io; use std::path::Path; @@ -87,3 +89,22 @@ pub struct FailedWritingFile<'a> { pub path: &'a Path, pub error: io::Error, } + +#[derive(Diagnostic)] +#[diag(interface::unsupported_crate_type_for_target)] +pub struct UnsupportedCrateTypeForTarget<'a> { + pub crate_type: CrateType, + pub target_triple: &'a TargetTriple, +} + +#[derive(Diagnostic)] +#[diag(interface::multiple_output_types_adaption)] +pub struct MultipleOutputTypesAdaption; + +#[derive(Diagnostic)] +#[diag(interface::ignoring_extra_filename)] +pub struct IgnoringExtraFilename; + +#[derive(Diagnostic)] +#[diag(interface::ignoring_out_dir)] +pub struct IgnoringOutDir; diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index f7e70d355cf86..033a59ae8effd 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -1,3 +1,4 @@ +use crate::errors; use info; use libloading::Library; use rustc_ast as ast; @@ -572,16 +573,15 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec 1 { - sess.warn( - "due to multiple output types requested, the explicitly specified \ - output file name will be adapted for each output type", - ); + sess.emit_warning(errors::MultipleOutputTypesAdaption); None } else { if !sess.opts.cg.extra_filename.is_empty() { - sess.warn("ignoring -C extra-filename flag due to -o flag"); + sess.emit_warning(errors::IgnoringExtraFilename); } Some(out_file.clone()) }; if *odir != None { - sess.warn("ignoring --out-dir flag due to -o flag"); + sess.emit_warning(errors::IgnoringOutDir); } OutputFilenames::new( diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index e773b3032aab8..258fb2e2f9f11 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1133,9 +1133,13 @@ pub struct ProjectionTy<'tcx> { impl<'tcx> ProjectionTy<'tcx> { pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { - let parent = tcx.parent(self.item_def_id); - assert_eq!(tcx.def_kind(parent), DefKind::Trait); - parent + match tcx.def_kind(self.item_def_id) { + DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.item_def_id), + DefKind::ImplTraitPlaceholder => { + tcx.parent(tcx.impl_trait_in_trait_parent(self.item_def_id)) + } + kind => bug!("unexpected DefKind in ProjectionTy: {kind:?}"), + } } /// Extracts the underlying trait reference and own substs from this projection. diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index f1a25a60d5292..d19b19212f767 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -201,7 +201,10 @@ use std::iter; use std::ops::Range; use std::path::PathBuf; -use crate::errors::{LargeAssignmentsLint, RecursionLimit, RequiresLangItem, TypeLengthLimit}; +use crate::errors::{ + EncounteredErrorWhileInstantiating, LargeAssignmentsLint, RecursionLimit, RequiresLangItem, + TypeLengthLimit, +}; #[derive(PartialEq)] pub enum MonoItemCollectionMode { @@ -524,10 +527,10 @@ fn collect_items_rec<'tcx>( && starting_point.node.is_user_defined() { let formatted_item = with_no_trimmed_paths!(starting_point.node.to_string()); - tcx.sess.span_note_without_error( - starting_point.span, - &format!("the above error was encountered while instantiating `{}`", formatted_item), - ); + tcx.sess.emit_note(EncounteredErrorWhileInstantiating { + span: starting_point.span, + formatted_item, + }); } inlining_map.lock_mut().record_accesses(starting_point.node, &neighbors.items); diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index cf6e18c013be8..b26345399b202 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -83,3 +83,17 @@ pub struct SymbolAlreadyDefined { pub span: Option, pub symbol: String, } + +#[derive(Diagnostic)] +#[diag(monomorphize::encountered_error_while_instantiating)] +pub struct EncounteredErrorWhileInstantiating { + #[primary_span] + pub span: Span, + pub formatted_item: String, +} + +#[derive(Diagnostic)] +#[diag(monomorphize::unknown_cgu_collection_mode)] +pub struct UnknownCguCollectionMode<'a> { + pub mode: &'a str, +} diff --git a/compiler/rustc_monomorphize/src/partitioning/mod.rs b/compiler/rustc_monomorphize/src/partitioning/mod.rs index 932edc6675f59..c124d5635900b 100644 --- a/compiler/rustc_monomorphize/src/partitioning/mod.rs +++ b/compiler/rustc_monomorphize/src/partitioning/mod.rs @@ -108,7 +108,7 @@ use rustc_span::symbol::Symbol; use crate::collector::InliningMap; use crate::collector::{self, MonoItemCollectionMode}; -use crate::errors::{SymbolAlreadyDefined, UnknownPartitionStrategy}; +use crate::errors::{SymbolAlreadyDefined, UnknownCguCollectionMode, UnknownPartitionStrategy}; pub struct PartitioningCx<'a, 'tcx> { tcx: TyCtxt<'tcx>, @@ -345,18 +345,13 @@ fn collect_and_partition_mono_items<'tcx>( ) -> (&'tcx DefIdSet, &'tcx [CodegenUnit<'tcx>]) { let collection_mode = match tcx.sess.opts.unstable_opts.print_mono_items { Some(ref s) => { - let mode_string = s.to_lowercase(); - let mode_string = mode_string.trim(); - if mode_string == "eager" { + let mode = s.to_lowercase(); + let mode = mode.trim(); + if mode == "eager" { MonoItemCollectionMode::Eager } else { - if mode_string != "lazy" { - let message = format!( - "Unknown codegen-item collection mode '{}'. \ - Falling back to 'lazy' mode.", - mode_string - ); - tcx.sess.warn(&message); + if mode != "lazy" { + tcx.sess.emit_warning(UnknownCguCollectionMode { mode }); } MonoItemCollectionMode::Lazy diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 70b470f3811d5..8591535845e71 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -25,7 +25,7 @@ use rustc_span::RealFileName; use rustc_span::SourceFileHashAlgorithm; use rustc_errors::emitter::HumanReadableErrorType; -use rustc_errors::{ColorConfig, HandlerFlags}; +use rustc_errors::{ColorConfig, DiagnosticArgValue, HandlerFlags, IntoDiagnosticArg}; use std::collections::btree_map::{ Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter, @@ -2640,6 +2640,12 @@ impl fmt::Display for CrateType { } } +impl IntoDiagnosticArg for CrateType { + fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { + self.to_string().into_diagnostic_arg() + } +} + #[derive(Copy, Clone, PartialEq, Debug)] pub enum PpSourceMode { /// `-Zunpretty=normal` diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index e01dafe2102b8..38289aa58e18b 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -219,3 +219,9 @@ impl IntoDiagnostic<'_> for InvalidCharacterInCrateName<'_> { diag } } + +#[derive(Diagnostic)] +#[diag(session::optimization_fuel_exhausted)] +pub struct OptimisationFuelExhausted { + pub msg: String, +} diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index b9202af2a6765..420189f67604f 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -12,7 +12,8 @@ use rustc_data_structures::sync::{Lock, Lrc}; use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler}; use rustc_errors::{ fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId, - DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, StashKey, + DiagnosticMessage, EmissionGuarantee, ErrorGuaranteed, IntoDiagnostic, MultiSpan, Noted, + StashKey, }; use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; use rustc_span::edition::Edition; @@ -364,6 +365,17 @@ impl ParseSess { self.create_warning(warning).emit() } + pub fn create_note<'a>( + &'a self, + note: impl IntoDiagnostic<'a, Noted>, + ) -> DiagnosticBuilder<'a, Noted> { + note.into_diagnostic(&self.span_diagnostic) + } + + pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted { + self.create_note(note).emit() + } + pub fn create_fatal<'a>( &'a self, fatal: impl IntoDiagnostic<'a, !>, diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 0142e98176633..0dca4516783c0 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -4,8 +4,8 @@ pub use crate::code_stats::{DataTypeKind, FieldInfo, SizeKind, VariantInfo}; use crate::config::{self, CrateType, InstrumentCoverage, OptLevel, OutputType, SwitchWithOptPath}; use crate::errors::{ CannotEnableCrtStaticLinux, CannotMixAndMatchSanitizers, LinkerPluginToWindowsNotSupported, - NotCircumventFeature, ProfileSampleUseFileDoesNotExist, ProfileUseFileDoesNotExist, - SanitizerCfiEnabled, SanitizerNotSupported, SanitizersNotSupported, + NotCircumventFeature, OptimisationFuelExhausted, ProfileSampleUseFileDoesNotExist, + ProfileUseFileDoesNotExist, SanitizerCfiEnabled, SanitizerNotSupported, SanitizersNotSupported, SplitDebugInfoUnstablePlatform, StackProtectorNotSupportedForTarget, TargetRequiresUnwindTables, UnstableVirtualFunctionElimination, UnsupportedDwarfVersion, }; @@ -28,7 +28,7 @@ use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ error_code, fallback_fluent_bundle, DiagnosticBuilder, DiagnosticId, DiagnosticMessage, - ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, + ErrorGuaranteed, FluentBundle, IntoDiagnostic, LazyFallbackBundle, MultiSpan, Noted, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; @@ -500,6 +500,8 @@ impl Session { self.diagnostic().span_err_with_code(sp, msg, code) } #[rustc_lint_diagnostics] + #[allow(rustc::untranslatable_diagnostic)] + #[allow(rustc::diagnostic_outside_of_impl)] pub fn err(&self, msg: impl Into) -> ErrorGuaranteed { self.diagnostic().err(msg) } @@ -533,6 +535,15 @@ impl Session { pub fn emit_warning<'a>(&'a self, warning: impl IntoDiagnostic<'a, ()>) { self.parse_sess.emit_warning(warning) } + pub fn create_note<'a>( + &'a self, + note: impl IntoDiagnostic<'a, Noted>, + ) -> DiagnosticBuilder<'a, Noted> { + self.parse_sess.create_note(note) + } + pub fn emit_note<'a>(&'a self, note: impl IntoDiagnostic<'a, Noted>) -> Noted { + self.parse_sess.emit_note(note) + } pub fn create_fatal<'a>( &'a self, fatal: impl IntoDiagnostic<'a, !>, @@ -576,11 +587,15 @@ impl Session { Err(ErrorGuaranteed::unchecked_claim_error_was_emitted()) } } + + #[rustc_lint_diagnostics] #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] pub fn span_warn>(&self, sp: S, msg: impl Into) { self.diagnostic().span_warn(sp, msg) } + + #[rustc_lint_diagnostics] #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] pub fn span_warn_with_code>( @@ -591,6 +606,10 @@ impl Session { ) { self.diagnostic().span_warn_with_code(sp, msg, code) } + + #[rustc_lint_diagnostics] + #[allow(rustc::untranslatable_diagnostic)] + #[allow(rustc::diagnostic_outside_of_impl)] pub fn warn(&self, msg: impl Into) { self.diagnostic().warn(msg) } @@ -621,9 +640,15 @@ impl Session { self.diagnostic().delay_good_path_bug(msg) } + #[rustc_lint_diagnostics] + #[allow(rustc::untranslatable_diagnostic)] + #[allow(rustc::diagnostic_outside_of_impl)] pub fn note_without_error(&self, msg: impl Into) { self.diagnostic().note_without_error(msg) } + #[rustc_lint_diagnostics] + #[allow(rustc::untranslatable_diagnostic)] + #[allow(rustc::diagnostic_outside_of_impl)] pub fn span_note_without_error>( &self, sp: S, @@ -631,6 +656,8 @@ impl Session { ) { self.diagnostic().span_note_without_error(sp, msg) } + + #[rustc_lint_diagnostics] #[allow(rustc::untranslatable_diagnostic)] #[allow(rustc::diagnostic_outside_of_impl)] pub fn struct_note_without_error( @@ -860,7 +887,7 @@ impl Session { // We only call `msg` in case we can actually emit warnings. // Otherwise, this could cause a `delay_good_path_bug` to // trigger (issue #79546). - self.warn(&format!("optimization-fuel-exhausted: {}", msg())); + self.emit_warning(OptimisationFuelExhausted { msg: msg() }); } fuel.out_of_fuel = true; } else if fuel.remaining > 0 { diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 38dcf6cbf7db7..4b07b393a2f5a 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -300,7 +300,7 @@ pub mod panic_count { thread_local! { static LOCAL_PANIC_COUNT: Cell = const { Cell::new(0) } } // Sum of panic counts from all threads. The purpose of this is to have - // a fast path in `is_zero` (which is used by `panicking`). In any particular + // a fast path in `count_is_zero` (which is used by `panicking`). In any particular // thread, if that thread currently views `GLOBAL_PANIC_COUNT` as being zero, // then `LOCAL_PANIC_COUNT` in that thread is zero. This invariant holds before // and after increase and decrease, but not necessarily during their execution. @@ -369,7 +369,7 @@ pub mod panic_count { } // Slow path is in a separate function to reduce the amount of code - // inlined from `is_zero`. + // inlined from `count_is_zero`. #[inline(never)] #[cold] fn is_zero_slow_path() -> bool { diff --git a/library/std/src/sys/windows/c.rs b/library/std/src/sys/windows/c.rs index 89d0ab59be89f..c61a7e7d1e4ab 100644 --- a/library/std/src/sys/windows/c.rs +++ b/library/std/src/sys/windows/c.rs @@ -279,7 +279,6 @@ pub const STATUS_INVALID_PARAMETER: NTSTATUS = 0xc000000d_u32 as _; pub const STATUS_PENDING: NTSTATUS = 0x103 as _; pub const STATUS_END_OF_FILE: NTSTATUS = 0xC0000011_u32 as _; pub const STATUS_NOT_IMPLEMENTED: NTSTATUS = 0xC0000002_u32 as _; -pub const STATUS_NOT_SUPPORTED: NTSTATUS = 0xC00000BB_u32 as _; // Equivalent to the `NT_SUCCESS` C preprocessor macro. // See: https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/using-ntstatus-values @@ -289,6 +288,7 @@ pub fn nt_success(status: NTSTATUS) -> bool { // "RNG\0" pub const BCRYPT_RNG_ALGORITHM: &[u16] = &[b'R' as u16, b'N' as u16, b'G' as u16, 0]; +pub const BCRYPT_USE_SYSTEM_PREFERRED_RNG: DWORD = 0x00000002; #[repr(C)] pub struct UNICODE_STRING { @@ -817,10 +817,6 @@ if #[cfg(not(target_vendor = "uwp"))] { #[link(name = "advapi32")] extern "system" { - // Forbidden when targeting UWP - #[link_name = "SystemFunction036"] - pub fn RtlGenRandom(RandomBuffer: *mut u8, RandomBufferLength: ULONG) -> BOOLEAN; - // Allowed but unused by UWP pub fn OpenProcessToken( ProcessHandle: HANDLE, diff --git a/library/std/src/sys/windows/rand.rs b/library/std/src/sys/windows/rand.rs index d6cd8f8027162..b5a49489d3fb8 100644 --- a/library/std/src/sys/windows/rand.rs +++ b/library/std/src/sys/windows/rand.rs @@ -13,15 +13,12 @@ //! but significant number of users to experience panics caused by a failure of //! this function. See [#94098]. //! -//! The current version changes this to use the `BCRYPT_RNG_ALG_HANDLE` -//! [Pseudo-handle], which gets the default RNG algorithm without querying the -//! system preference thus hopefully avoiding the previous issue. -//! This is only supported on Windows 10+ so a fallback is used for older versions. +//! The current version falls back to using `BCryptOpenAlgorithmProvider` if +//! `BCRYPT_USE_SYSTEM_PREFERRED_RNG` fails for any reason. //! //! [#94098]: https://github.com/rust-lang/rust/issues/94098 //! [`RtlGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom //! [`BCryptGenRandom`]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom -//! [Pseudo-handle]: https://docs.microsoft.com/en-us/windows/win32/seccng/cng-algorithm-pseudo-handles use crate::mem; use crate::ptr; use crate::sys::c; @@ -33,37 +30,35 @@ use crate::sys::c; /// [`HashMap`]: crate::collections::HashMap /// [`RandomState`]: crate::collections::hash_map::RandomState pub fn hashmap_random_keys() -> (u64, u64) { - Rng::open().and_then(|rng| rng.gen_random_keys()).unwrap_or_else(fallback_rng) + Rng::SYSTEM.gen_random_keys().unwrap_or_else(fallback_rng) } -struct Rng(c::BCRYPT_ALG_HANDLE); +struct Rng { + algorithm: c::BCRYPT_ALG_HANDLE, + flags: u32, +} impl Rng { - #[cfg(miri)] - fn open() -> Result { - const BCRYPT_RNG_ALG_HANDLE: c::BCRYPT_ALG_HANDLE = ptr::invalid_mut(0x81); - let _ = ( - c::BCryptOpenAlgorithmProvider, - c::BCryptCloseAlgorithmProvider, - c::BCRYPT_RNG_ALGORITHM, - c::STATUS_NOT_SUPPORTED, - ); - Ok(Self(BCRYPT_RNG_ALG_HANDLE)) + const SYSTEM: Self = unsafe { Self::new(ptr::null_mut(), c::BCRYPT_USE_SYSTEM_PREFERRED_RNG) }; + + /// Create the RNG from an existing algorithm handle. + /// + /// # Safety + /// + /// The handle must either be null or a valid algorithm handle. + const unsafe fn new(algorithm: c::BCRYPT_ALG_HANDLE, flags: u32) -> Self { + Self { algorithm, flags } } - #[cfg(not(miri))] - // Open a handle to the RNG algorithm. + + /// Open a handle to the RNG algorithm. fn open() -> Result { use crate::sync::atomic::AtomicPtr; use crate::sync::atomic::Ordering::{Acquire, Release}; - const ERROR_VALUE: c::LPVOID = ptr::invalid_mut(usize::MAX); // An atomic is used so we don't need to reopen the handle every time. static HANDLE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); let mut handle = HANDLE.load(Acquire); - // We use a sentinel value to designate an error occurred last time. - if handle == ERROR_VALUE { - Err(c::STATUS_NOT_SUPPORTED) - } else if handle.is_null() { + if handle.is_null() { let status = unsafe { c::BCryptOpenAlgorithmProvider( &mut handle, @@ -80,13 +75,12 @@ impl Rng { unsafe { c::BCryptCloseAlgorithmProvider(handle, 0) }; handle = previous_handle; } - Ok(Self(handle)) + Ok(unsafe { Self::new(handle, 0) }) } else { - HANDLE.store(ERROR_VALUE, Release); Err(status) } } else { - Ok(Self(handle)) + Ok(unsafe { Self::new(handle, 0) }) } } @@ -94,33 +88,19 @@ impl Rng { let mut v = (0, 0); let status = unsafe { let size = mem::size_of_val(&v).try_into().unwrap(); - c::BCryptGenRandom(self.0, ptr::addr_of_mut!(v).cast(), size, 0) + c::BCryptGenRandom(self.algorithm, ptr::addr_of_mut!(v).cast(), size, self.flags) }; if c::nt_success(status) { Ok(v) } else { Err(status) } } } -/// Generate random numbers using the fallback RNG function (RtlGenRandom) -#[cfg(not(target_vendor = "uwp"))] +/// Generate random numbers using the fallback RNG function #[inline(never)] fn fallback_rng(rng_status: c::NTSTATUS) -> (u64, u64) { - let mut v = (0, 0); - let ret = - unsafe { c::RtlGenRandom(&mut v as *mut _ as *mut u8, mem::size_of_val(&v) as c::ULONG) }; - - if ret != 0 { - v - } else { - panic!( - "RNG broken: {rng_status:#x}, fallback RNG broken: {}", - crate::io::Error::last_os_error() - ) + match Rng::open().and_then(|rng| rng.gen_random_keys()) { + Ok(keys) => keys, + Err(status) => { + panic!("RNG broken: {rng_status:#x}, fallback RNG broken: {status:#x}") + } } } - -/// We can't use RtlGenRandom with UWP, so there is no fallback -#[cfg(target_vendor = "uwp")] -#[inline(never)] -fn fallback_rng(rng_status: c::NTSTATUS) -> (u64, u64) { - panic!("RNG broken: {rng_status:#x} fallback RNG broken: RtlGenRandom() not supported on UWP"); -} diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index b7bc96cc86dac..563e67a326f19 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -1424,7 +1424,7 @@ impl Step for Extended { let xform = |p: &Path| { let mut contents = t!(fs::read_to_string(p)); - for tool in &["rust-demangler", "rust-analyzer", "rustfmt"] { + for tool in &["rust-demangler"] { if !built_tools.contains(tool) { contents = filter(&contents, tool); } @@ -1465,7 +1465,8 @@ impl Step for Extended { prepare("rust-analysis"); prepare("clippy"); prepare("miri"); - for tool in &["rust-docs", "rust-demangler", "rust-analyzer"] { + prepare("rust-analyzer"); + for tool in &["rust-docs", "rust-demangler"] { if built_tools.contains(tool) { prepare(tool); } @@ -1525,7 +1526,8 @@ impl Step for Extended { prepare("rust-std"); prepare("clippy"); prepare("miri"); - for tool in &["rust-demangler", "rust-analyzer"] { + prepare("rust-analyzer"); + for tool in &["rust-demangler"] { if built_tools.contains(tool) { prepare(tool); } @@ -1609,25 +1611,23 @@ impl Step for Extended { .arg("-out") .arg(exe.join("StdGroup.wxs")), ); - if built_tools.contains("rust-analyzer") { - builder.run( - Command::new(&heat) - .current_dir(&exe) - .arg("dir") - .arg("rust-analyzer") - .args(&heat_flags) - .arg("-cg") - .arg("RustAnalyzerGroup") - .arg("-dr") - .arg("RustAnalyzer") - .arg("-var") - .arg("var.RustAnalyzerDir") - .arg("-out") - .arg(exe.join("RustAnalyzerGroup.wxs")) - .arg("-t") - .arg(etc.join("msi/remove-duplicates.xsl")), - ); - } + builder.run( + Command::new(&heat) + .current_dir(&exe) + .arg("dir") + .arg("rust-analyzer") + .args(&heat_flags) + .arg("-cg") + .arg("RustAnalyzerGroup") + .arg("-dr") + .arg("RustAnalyzer") + .arg("-var") + .arg("var.RustAnalyzerDir") + .arg("-out") + .arg(exe.join("RustAnalyzerGroup.wxs")) + .arg("-t") + .arg(etc.join("msi/remove-duplicates.xsl")), + ); builder.run( Command::new(&heat) .current_dir(&exe) @@ -2026,6 +2026,7 @@ impl Step for RustDev { "llvm-dwp", "llvm-nm", "llvm-dwarfdump", + "llvm-dis", ] { tarball.add_file(src_bindir.join(exe(bin, target)), "bin", 0o755); } diff --git a/src/bootstrap/download-ci-llvm-stamp b/src/bootstrap/download-ci-llvm-stamp index 19504a51a584b..2e11cf19c3f6a 100644 --- a/src/bootstrap/download-ci-llvm-stamp +++ b/src/bootstrap/download-ci-llvm-stamp @@ -1,4 +1,4 @@ Change this file to make users of the `download-ci-llvm` configuration download a new version of LLVM from CI, even if the LLVM submodule hasn’t changed. -Last change is for: https://github.com/rust-lang/rust/pull/96867 +Last change is for: https://github.com/rust-lang/rust/pull/97550 diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version b/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version index 2774f8587f40e..142464bf22b42 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version +++ b/src/ci/docker/host-x86_64/x86_64-gnu-tools/browser-ui-test.version @@ -1 +1 @@ -0.10.0 \ No newline at end of file +0.11.0 \ No newline at end of file diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index e17165440d109..593c1c436b861 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -411,7 +411,7 @@ img { .sidebar { font-size: 0.875rem; - width: 250px; + width: 200px; min-width: 200px; overflow-y: scroll; position: sticky; diff --git a/src/test/run-make/incremental-session-fail/Makefile b/src/test/run-make/incremental-session-fail/Makefile index 0461bb926e76e..6ce1370927bc1 100644 --- a/src/test/run-make/incremental-session-fail/Makefile +++ b/src/test/run-make/incremental-session-fail/Makefile @@ -9,6 +9,6 @@ all: touch $(SESSION_DIR) # Check exit code is 1 for an error, and not 101 for ICE. $(RUSTC) foo.rs --crate-type=rlib -C incremental=$(SESSION_DIR) > $(OUTPUT_FILE) 2>&1; [ $$? -eq 1 ] - $(CGREP) "Could not create incremental compilation crate directory" < $(OUTPUT_FILE) + $(CGREP) "could not create incremental compilation crate directory" < $(OUTPUT_FILE) # -v tests are fragile, hopefully this text won't change $(CGREP) -v "internal compiler error" < $(OUTPUT_FILE) diff --git a/src/test/rustdoc-gui/check-stab-in-docblock.goml b/src/test/rustdoc-gui/check-stab-in-docblock.goml index 7f965ada594d8..afe25195100c5 100644 --- a/src/test/rustdoc-gui/check-stab-in-docblock.goml +++ b/src/test/rustdoc-gui/check-stab-in-docblock.goml @@ -7,15 +7,21 @@ size: (786, 600) // Confirms that there 3 paragraphs. assert-count: (".top-doc .docblock p", 3) // Checking that there is no scrollable content. +store-property: (clientHeight, ".top-doc .docblock p:nth-of-type(1)", "clientHeight") +store-property: (clientWidth, ".top-doc .docblock p:nth-of-type(1)", "clientWidth") assert-property: ( ".top-doc .docblock p:nth-of-type(1)", - {"scrollHeight": "120", "clientHeight": "120", "scrollWidth": "502", "clientWidth": "502"}, + {"scrollHeight": |clientHeight|, "scrollWidth": |clientWidth|}, ) +store-property: (clientHeight, ".top-doc .docblock p:nth-of-type(2)", "clientHeight") +store-property: (clientWidth, ".top-doc .docblock p:nth-of-type(2)", "clientWidth") assert-property: ( ".top-doc .docblock p:nth-of-type(2)", - {"scrollHeight": "48", "clientHeight": "48", "scrollWidth": "502", "clientWidth": "502"}, + {"scrollHeight": |clientHeight|, "scrollWidth": |clientWidth|}, ) +store-property: (clientHeight, ".top-doc .docblock p:nth-of-type(3)", "clientHeight") +store-property: (clientWidth, ".top-doc .docblock p:nth-of-type(3)", "clientWidth") assert-property: ( ".top-doc .docblock p:nth-of-type(3)", - {"scrollHeight": "48", "clientHeight": "48", "scrollWidth": "502", "clientWidth": "502"}, + {"scrollHeight": |clientHeight|, "scrollWidth": |clientWidth|}, ) diff --git a/src/test/rustdoc-gui/code-blocks-overflow.goml b/src/test/rustdoc-gui/code-blocks-overflow.goml index f93f3f0aefc51..ee4dad444e932 100644 --- a/src/test/rustdoc-gui/code-blocks-overflow.goml +++ b/src/test/rustdoc-gui/code-blocks-overflow.goml @@ -5,4 +5,4 @@ size: (1080, 600) assert-count: (".docblock > .example-wrap", 2) assert: ".docblock > .example-wrap > .language-txt" assert: ".docblock > .example-wrap > .rust-example-rendered" -assert-css: (".docblock > .example-wrap > pre", {"width": "785.25px", "overflow-x": "auto"}, ALL) +assert-css: (".docblock > .example-wrap > pre", {"width": "796px", "overflow-x": "auto"}, ALL) diff --git a/src/test/rustdoc-gui/docblock-table-overflow.goml b/src/test/rustdoc-gui/docblock-table-overflow.goml index 7f97cf220cc55..ef0d37c902e09 100644 --- a/src/test/rustdoc-gui/docblock-table-overflow.goml +++ b/src/test/rustdoc-gui/docblock-table-overflow.goml @@ -4,7 +4,7 @@ goto: file://|DOC_PATH|/lib2/long_table/struct.Foo.html size: (1100, 800) // Logically, the ".docblock" and the "

" should have the same scroll width. compare-elements-property: (".top-doc .docblock", ".top-doc .docblock > p", ["scrollWidth"]) -assert-property: (".top-doc .docblock", {"scrollWidth": "801"}) +assert-property: (".top-doc .docblock", {"scrollWidth": "816"}) // However, since there is overflow in the , its scroll width is bigger. assert-property: (".top-doc .docblock table", {"scrollWidth": "1572"}) @@ -16,6 +16,6 @@ compare-elements-property: ( "#implementations-list > details .docblock > p", ["scrollWidth"], ) -assert-property: ("#implementations-list > details .docblock", {"scrollWidth": "801"}) +assert-property: ("#implementations-list > details .docblock", {"scrollWidth": "816"}) // However, since there is overflow in the
, its scroll width is bigger. assert-property: ("#implementations-list > details .docblock table", {"scrollWidth": "1572"}) diff --git a/src/test/rustdoc-gui/item-info-overflow.goml b/src/test/rustdoc-gui/item-info-overflow.goml index 17478da4fea29..bc3addd33dd38 100644 --- a/src/test/rustdoc-gui/item-info-overflow.goml +++ b/src/test/rustdoc-gui/item-info-overflow.goml @@ -4,7 +4,7 @@ goto: file://|DOC_PATH|/lib2/struct.LongItemInfo.html size: (1200, 870) // Logically, the "item-decl" and the "item-info" should have the same scroll width. compare-elements-property: (".item-decl", ".item-info", ["scrollWidth"]) -assert-property: (".item-info", {"scrollWidth": "890"}) +assert-property: (".item-info", {"scrollWidth": "940"}) // Just to be sure we're comparing the correct "item-info": assert-text: ( ".item-info", @@ -21,7 +21,7 @@ compare-elements-property: ( ) assert-property: ( "#impl-SimpleTrait-for-LongItemInfo2 .item-info", - {"scrollWidth": "866"}, + {"scrollWidth": "916"}, ) // Just to be sure we're comparing the correct "item-info": assert-text: ( diff --git a/src/test/rustdoc-gui/item-info.goml b/src/test/rustdoc-gui/item-info.goml index 50c45b76bd630..8750d5c53606f 100644 --- a/src/test/rustdoc-gui/item-info.goml +++ b/src/test/rustdoc-gui/item-info.goml @@ -4,9 +4,9 @@ goto: file://|DOC_PATH|/lib2/struct.Foo.html // We set a fixed size so there is no chance of "random" resize. size: (1100, 800) // We check that ".item-info" is bigger than its content. -assert-css: (".item-info", {"width": "790px"}) +assert-css: (".item-info", {"width": "840px"}) assert-css: (".item-info .stab", {"width": "289px"}) -assert-position: (".item-info .stab", {"x": 295}) +assert-position: (".item-info .stab", {"x": 245}) // Now we ensure that they're not rendered on the same line. goto: file://|DOC_PATH|/lib2/trait.Trait.html diff --git a/src/test/rustdoc-gui/notable-trait.goml b/src/test/rustdoc-gui/notable-trait.goml index 7eb00d825a5c3..20a129f9d9da6 100644 --- a/src/test/rustdoc-gui/notable-trait.goml +++ b/src/test/rustdoc-gui/notable-trait.goml @@ -18,11 +18,11 @@ compare-elements-position-false: ( // The `i` should be *after* the type. assert-position: ( "//*[@id='method.create_an_iterator_from_read']//a[text()='NotableStructWithLongName']", - {"x": 692}, + {"x": 677}, ) assert-position: ( "//*[@id='method.create_an_iterator_from_read']//*[@class='notable-traits']", - {"x": 966}, + {"x": 951}, ) diff --git a/src/test/rustdoc-gui/search-result-display.goml b/src/test/rustdoc-gui/search-result-display.goml index efbbfb925bd3b..e33693e27eaf6 100644 --- a/src/test/rustdoc-gui/search-result-display.goml +++ b/src/test/rustdoc-gui/search-result-display.goml @@ -7,7 +7,7 @@ press-key: 'Enter' wait-for: "#crate-search" // The width is returned by "getComputedStyle" which returns the exact number instead of the // CSS rule which is "50%"... -assert-css: (".search-results div.desc", {"width": "293px"}) +assert-css: (".search-results div.desc", {"width": "318px"}) size: (600, 100) // As counter-intuitive as it may seem, in this width, the width is "100%", which is why // when computed it's larger. diff --git a/src/test/rustdoc-gui/sidebar.goml b/src/test/rustdoc-gui/sidebar.goml index 32fe3334f3644..ea7bcc669945a 100644 --- a/src/test/rustdoc-gui/sidebar.goml +++ b/src/test/rustdoc-gui/sidebar.goml @@ -1,5 +1,6 @@ // Checks multiple things on the sidebar display (width of its elements, colors, etc). goto: file://|DOC_PATH|/test_docs/index.html +assert-property: (".sidebar", {"clientWidth": "200"}) show-text: true local-storage: {"rustdoc-theme": "light"} // We reload the page so the local storage settings are being used. @@ -39,11 +40,13 @@ assert-property: ("html", {"scrollTop": "0"}) // We now go back to the crate page to click on the "lib2" crate link. goto: file://|DOC_PATH|/test_docs/index.html +assert-property: (".sidebar", {"clientWidth": "200"}) assert-css: (".sidebar-elems .crate > ul > li:first-child > a", {"color": "rgb(53, 109, 164)"}) click: ".sidebar-elems .crate > ul > li:first-child > a" // PAGE: lib2/index.html goto: file://|DOC_PATH|/lib2/index.html +assert-property: (".sidebar", {"clientWidth": "200"}) assert-text: (".sidebar > .location", "Crate lib2") // We check that we have the crates list and that the "current" on is now "lib2". assert-text: (".sidebar-elems .crate > ul > li > a.current", "lib2") @@ -65,11 +68,13 @@ assert-text: (".sidebar .sidebar-elems .location", "In lib2") assert-false: ".sidebar-elems > .crate" goto: ./module/index.html +assert-property: (".sidebar", {"clientWidth": "200"}) assert-text: (".sidebar > .location", "Module module") // We check that we don't have the crate list. assert-false: ".sidebar-elems > .crate" goto: ./sub_module/sub_sub_module/index.html +assert-property: (".sidebar", {"clientWidth": "200"}) assert-text: (".sidebar > .location", "Module sub_sub_module") // We check that we don't have the crate list. assert-false: ".sidebar-elems .crate" @@ -78,11 +83,21 @@ assert-text: ("#functions + .item-table .item-left > a", "foo") // Links to trait implementations in the sidebar should not wrap even if they are long. goto: file://|DOC_PATH|/lib2/struct.HasALongTraitWithParams.html +assert-property: (".sidebar", {"clientWidth": "200"}) assert-property: (".sidebar-elems section .block li > a", {"offsetHeight": 29}) // Test that clicking on of the "In " headings in the sidebar links to the // appropriate anchor in index.html. goto: file://|DOC_PATH|/test_docs/struct.Foo.html +assert-property: (".sidebar", {"clientWidth": "200"}) click: ".block.mod h3 a" // PAGE: index.html assert-css: ("#modules", {"background-color": "rgb(253, 255, 211)"}) + +// Finally, assert that the `[+]/[−]` toggle doesn't affect sidebar width. +click: "#toggle-all-docs" +assert-text: ("#toggle-all-docs", "[+]") +assert-property: (".sidebar", {"clientWidth": "200"}) +click: "#toggle-all-docs" +assert-text: ("#toggle-all-docs", "[−]") +assert-property: (".sidebar", {"clientWidth": "200"}) \ No newline at end of file diff --git a/src/test/rustdoc-gui/type-declation-overflow.goml b/src/test/rustdoc-gui/type-declation-overflow.goml index 9a46908f9333b..505874fa01070 100644 --- a/src/test/rustdoc-gui/type-declation-overflow.goml +++ b/src/test/rustdoc-gui/type-declation-overflow.goml @@ -15,7 +15,7 @@ assert-property: (".item-table .struct", {"offsetWidth": "684"}) goto: file://|DOC_PATH|/lib2/too_long/type.ReallyLongTypeNameLongLongLong.html assert-property: ("body", {"scrollWidth": "1100"}) // We now check that the section width hasn't grown because of it. -assert-property: ("#main-content", {"scrollWidth": "825"}) +assert-property: ("#main-content", {"scrollWidth": "840"}) // And now checking that it has scrollable content. assert-property: (".item-decl pre", {"scrollWidth": "1103"}) @@ -24,7 +24,7 @@ assert-property: (".item-decl pre", {"scrollWidth": "1103"}) goto: file://|DOC_PATH|/lib2/too_long/constant.ReallyLongTypeNameLongLongLongConstBecauseWhyNotAConstRightGigaGigaSupraLong.html assert-property: ("body", {"scrollWidth": "1100"}) // We now check that the section width hasn't grown because of it. -assert-property: ("#main-content", {"scrollWidth": "825"}) +assert-property: ("#main-content", {"scrollWidth": "840"}) // And now checking that it has scrollable content. assert-property: (".item-decl pre", {"scrollWidth": "950"}) @@ -32,6 +32,6 @@ assert-property: (".item-decl pre", {"scrollWidth": "950"}) size: (600, 600) goto: file://|DOC_PATH|/lib2/too_long/struct.SuperIncrediblyLongLongLongLongLongLongLongGigaGigaGigaMegaLongLongLongStructName.html // It shouldn't have an overflow in the topbar either. -assert-property: (".mobile-topbar .location", {"scrollWidth": "500"}) -assert-property: (".mobile-topbar .location", {"clientWidth": "500"}) +store-property: (scrollWidth, ".mobile-topbar .location", "scrollWidth") +assert-property: (".mobile-topbar .location", {"clientWidth": |scrollWidth|}) assert-css: (".mobile-topbar .location", {"overflow-x": "hidden"}) diff --git a/src/test/ui/impl-trait/in-trait/issue-102140.rs b/src/test/ui/impl-trait/in-trait/issue-102140.rs new file mode 100644 index 0000000000000..be1e012acb185 --- /dev/null +++ b/src/test/ui/impl-trait/in-trait/issue-102140.rs @@ -0,0 +1,30 @@ +#![feature(return_position_impl_trait_in_trait)] +#![allow(incomplete_features)] + +trait Marker {} +impl Marker for u32 {} + +trait MyTrait { + fn foo(&self) -> impl Marker + where + Self: Sized; +} + +struct Outer; + +impl MyTrait for Outer { + fn foo(&self) -> impl Marker { + 42 + } +} + +impl dyn MyTrait { + fn other(&self) -> impl Marker { + MyTrait::foo(&self) + //~^ ERROR the trait bound `&dyn MyTrait: MyTrait` is not satisfied + //~| ERROR the trait bound `&dyn MyTrait: MyTrait` is not satisfied + //~| ERROR the trait bound `&dyn MyTrait: MyTrait` is not satisfied + } +} + +fn main() {} diff --git a/src/test/ui/impl-trait/in-trait/issue-102140.stderr b/src/test/ui/impl-trait/in-trait/issue-102140.stderr new file mode 100644 index 0000000000000..08602185f50ca --- /dev/null +++ b/src/test/ui/impl-trait/in-trait/issue-102140.stderr @@ -0,0 +1,29 @@ +error[E0277]: the trait bound `&dyn MyTrait: MyTrait` is not satisfied + --> $DIR/issue-102140.rs:23:22 + | +LL | MyTrait::foo(&self) + | ------------ -^^^^ + | | | + | | the trait `MyTrait` is not implemented for `&dyn MyTrait` + | | help: consider removing the leading `&`-reference + | required by a bound introduced by this call + +error[E0277]: the trait bound `&dyn MyTrait: MyTrait` is not satisfied + --> $DIR/issue-102140.rs:23:9 + | +LL | MyTrait::foo(&self) + | ^^^^^^^^^^^^^^^^^^^ the trait `MyTrait` is not implemented for `&dyn MyTrait` + | + = help: the trait `MyTrait` is implemented for `Outer` + +error[E0277]: the trait bound `&dyn MyTrait: MyTrait` is not satisfied + --> $DIR/issue-102140.rs:23:9 + | +LL | MyTrait::foo(&self) + | ^^^^^^^^^^^^ the trait `MyTrait` is not implemented for `&dyn MyTrait` + | + = help: the trait `MyTrait` is implemented for `Outer` + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0277`.