From 679f6f347355726f9335fdcbf0d3b81b2e490c38 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 10 Jan 2021 11:36:45 +0100 Subject: [PATCH 01/18] Add `unwrap_unchecked()` methods for `Option` and `Result` In particular: - `unwrap_unchecked()` for `Option`. - `unwrap_unchecked()` and `unwrap_err_unchecked()` for `Result`. These complement other `*_unchecked()` methods in `core` etc. Currently there are a couple of places it may be used inside rustc (`LinkedList`, `BTree`). It is also easy to find other repositories with similar functionality. Fixes #48278. Signed-off-by: Miguel Ojeda --- library/core/src/option.rs | 31 +++++++++++++++++ library/core/src/result.rs | 64 +++++++++++++++++++++++++++++++++++- library/core/tests/lib.rs | 1 + library/core/tests/option.rs | 7 ++++ library/core/tests/result.rs | 12 +++++++ 5 files changed, 114 insertions(+), 1 deletion(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 0051c9eede070..18b494b3175b6 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -428,6 +428,37 @@ impl Option { } } + /// Returns the contained [`Some`] value, consuming the `self` value, + /// without checking that the value is not [`None`]. + /// + /// # Safety + /// + /// Undefined behavior if the value is [`None`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_result_unwrap_unchecked)] + /// let x = Some("air"); + /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); + /// ``` + /// + /// ```no_run + /// #![feature(option_result_unwrap_unchecked)] + /// let x: Option<&str> = None; + /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior! + /// ``` + #[inline] + #[track_caller] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + pub unsafe fn unwrap_unchecked(self) -> T { + debug_assert!(self.is_some()); + match self { + Some(val) => val, + None => unsafe { hint::unreachable_unchecked() }, + } + } + ///////////////////////////////////////////////////////////////////////// // Transforming contained values ///////////////////////////////////////////////////////////////////////// diff --git a/library/core/src/result.rs b/library/core/src/result.rs index d6d1762572928..a0f5c7746cc75 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -229,7 +229,7 @@ use crate::iter::{self, FromIterator, FusedIterator, TrustedLen}; use crate::ops::{self, Deref, DerefMut}; -use crate::{convert, fmt}; +use crate::{convert, fmt, hint}; /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]). /// @@ -821,6 +821,68 @@ impl Result { Err(e) => op(e), } } + + /// Returns the contained [`Ok`] value, consuming the `self` value, + /// without checking that the value is not an [`Err`]. + /// + /// # Safety + /// + /// Undefined behavior if the value is an [`Err`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_result_unwrap_unchecked)] + /// let x: Result = Ok(2); + /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2); + /// ``` + /// + /// ```no_run + /// #![feature(option_result_unwrap_unchecked)] + /// let x: Result = Err("emergency failure"); + /// unsafe { x.unwrap_unchecked(); } // Undefined behavior! + /// ``` + #[inline] + #[track_caller] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + pub unsafe fn unwrap_unchecked(self) -> T { + debug_assert!(self.is_ok()); + match self { + Ok(t) => t, + Err(_) => unsafe { hint::unreachable_unchecked() }, + } + } + + /// Returns the contained [`Err`] value, consuming the `self` value, + /// without checking that the value is not an [`Ok`]. + /// + /// # Safety + /// + /// Undefined behavior if the value is an [`Ok`]. + /// + /// # Examples + /// + /// ```no_run + /// #![feature(option_result_unwrap_unchecked)] + /// let x: Result = Ok(2); + /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! + /// ``` + /// + /// ``` + /// #![feature(option_result_unwrap_unchecked)] + /// let x: Result = Err("emergency failure"); + /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); + /// ``` + #[inline] + #[track_caller] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + pub unsafe fn unwrap_err_unchecked(self) -> E { + debug_assert!(self.is_err()); + match self { + Ok(_) => unsafe { hint::unreachable_unchecked() }, + Err(e) => e, + } + } } impl Result<&T, E> { diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index e01aaa4cbf179..285e6cdfd39f9 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -62,6 +62,7 @@ #![feature(const_raw_ptr_deref)] #![feature(never_type)] #![feature(unwrap_infallible)] +#![feature(option_result_unwrap_unchecked)] #![feature(option_unwrap_none)] #![feature(peekable_next_if)] #![feature(peekable_peek_mut)] diff --git a/library/core/tests/option.rs b/library/core/tests/option.rs index 5388b4756245a..9470451278cc4 100644 --- a/library/core/tests/option.rs +++ b/library/core/tests/option.rs @@ -160,6 +160,13 @@ fn test_unwrap_or_else() { assert_eq!(x.unwrap_or_else(|| 2), 2); } +#[test] +fn test_unwrap_unchecked() { + assert_eq!(unsafe { Some(1).unwrap_unchecked() }, 1); + let s = unsafe { Some("hello".to_string()).unwrap_unchecked() }; + assert_eq!(s, "hello"); +} + #[test] fn test_iter() { let val = 5; diff --git a/library/core/tests/result.rs b/library/core/tests/result.rs index 81660870e95e4..7aa44c6e593b3 100644 --- a/library/core/tests/result.rs +++ b/library/core/tests/result.rs @@ -119,6 +119,18 @@ pub fn test_unwrap_or_else_panic() { let _: isize = bad_err.unwrap_or_else(handler); } +#[test] +fn test_unwrap_unchecked() { + let ok: Result = Ok(100); + assert_eq!(unsafe { ok.unwrap_unchecked() }, 100); +} + +#[test] +fn test_unwrap_err_unchecked() { + let ok_err: Result = Err("Err"); + assert_eq!(unsafe { ok_err.unwrap_err_unchecked() }, "Err"); +} + #[test] pub fn test_expect_ok() { let ok: Result = Ok(100); From 76299b3f42a402aa896b76fccd725f52080f374d Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 10 Jan 2021 15:59:17 +0100 Subject: [PATCH 02/18] Add `SAFETY` annotations Signed-off-by: Miguel Ojeda --- library/core/src/option.rs | 1 + library/core/src/result.rs | 2 ++ 2 files changed, 3 insertions(+) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 18b494b3175b6..5d34f5ca155bf 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -455,6 +455,7 @@ impl Option { debug_assert!(self.is_some()); match self { Some(val) => val, + // SAFETY: the safety contract must be upheld by the caller. None => unsafe { hint::unreachable_unchecked() }, } } diff --git a/library/core/src/result.rs b/library/core/src/result.rs index a0f5c7746cc75..a357750b92f9d 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -849,6 +849,7 @@ impl Result { debug_assert!(self.is_ok()); match self { Ok(t) => t, + // SAFETY: the safety contract must be upheld by the caller. Err(_) => unsafe { hint::unreachable_unchecked() }, } } @@ -879,6 +880,7 @@ impl Result { pub unsafe fn unwrap_err_unchecked(self) -> E { debug_assert!(self.is_err()); match self { + // SAFETY: the safety contract must be upheld by the caller. Ok(_) => unsafe { hint::unreachable_unchecked() }, Err(e) => e, } From 63a1eeea234105fd9c1ed30ac2b6e0d9bf41a1e9 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Mon, 18 Jan 2021 11:55:23 -0600 Subject: [PATCH 03/18] Reset LateContext enclosing body in nested items Prevents LateContext::maybe_typeck_results() from returning data in a nested item without a body. Consequently, LateContext::qpath_res is less likely to ICE when called in a nested item. Would have prevented rust-lang/rust-clippy#4545, presumably. --- compiler/rustc_lint/src/late.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 015e109871182..3821a393efb8b 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -140,6 +140,8 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { let generics = self.context.generics.take(); self.context.generics = it.kind.generics(); + let old_cached_typeck_results = self.context.cached_typeck_results.take(); + let old_enclosing_body = self.context.enclosing_body.take(); self.with_lint_attrs(it.hir_id, &it.attrs, |cx| { cx.with_param_env(it.hir_id, |cx| { lint_callback!(cx, check_item, it); @@ -147,6 +149,8 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas lint_callback!(cx, check_item_post, it); }); }); + self.context.enclosing_body = old_enclosing_body; + self.context.cached_typeck_results.set(old_cached_typeck_results); self.context.generics = generics; } From 21fb586c0c72a546bae445df1588cef464502ada Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Mon, 18 Jan 2021 13:29:37 -0600 Subject: [PATCH 04/18] Query for TypeckResults in LateContext::qpath_res Actually fulfills the documented guarantees. --- compiler/rustc_lint/src/context.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 3971a3099823f..3f92d66d88bce 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -746,6 +746,14 @@ impl<'tcx> LateContext<'tcx> { hir::QPath::Resolved(_, ref path) => path.res, hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self .maybe_typeck_results() + .filter(|typeck_results| typeck_results.hir_owner == id.owner) + .or_else(|| { + if self.tcx.has_typeck_results(id.owner.to_def_id()) { + Some(self.tcx.typeck(id.owner)) + } else { + None + } + }) .and_then(|typeck_results| typeck_results.type_dependent_def(id)) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), } From def0e9b8a495fa2a44e1d2cd948f7d4b6d81344f Mon Sep 17 00:00:00 2001 From: Camelid Date: Sun, 10 Jan 2021 19:55:54 -0800 Subject: [PATCH 05/18] Fix ICE with `ReadPointerAsBytes` validation error --- compiler/rustc_mir/src/interpret/validity.rs | 6 +++- src/test/ui/issues/issue-79690.rs | 29 ++++++++++++++++++++ src/test/ui/issues/issue-79690.stderr | 11 ++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/issues/issue-79690.rs create mode 100644 src/test/ui/issues/issue-79690.stderr diff --git a/compiler/rustc_mir/src/interpret/validity.rs b/compiler/rustc_mir/src/interpret/validity.rs index 423d1270ac865..0b7492631c41d 100644 --- a/compiler/rustc_mir/src/interpret/validity.rs +++ b/compiler/rustc_mir/src/interpret/validity.rs @@ -515,7 +515,11 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' Ok(true) } ty::Float(_) | ty::Int(_) | ty::Uint(_) => { - let value = self.ecx.read_scalar(value)?; + let value = try_validation!( + self.ecx.read_scalar(value), + self.path, + err_unsup!(ReadPointerAsBytes) => { "read of part of a pointer" }, + ); // NOTE: Keep this in sync with the array optimization for int/float // types below! if self.ctfe_mode.is_some() { diff --git a/src/test/ui/issues/issue-79690.rs b/src/test/ui/issues/issue-79690.rs new file mode 100644 index 0000000000000..6a38b3c8c2c71 --- /dev/null +++ b/src/test/ui/issues/issue-79690.rs @@ -0,0 +1,29 @@ +union Transmute { + t: T, + u: U, +} +trait Bar { + fn bar(&self) -> u32; +} +struct Foo { + foo: u32, + bar: bool, +} +impl Bar for Foo { + fn bar(&self) -> u32 { + self.foo + } +} +#[derive(Copy, Clone)] +struct Fat<'a>(&'a Foo, &'static VTable); +struct VTable { + size: Foo, +} +const FOO: &dyn Bar = &Foo { + foo: 128, + bar: false, +}; +const G: Fat = unsafe { Transmute { t: FOO }.u }; +//~^ ERROR it is undefined behavior to use this value + +fn main() {} diff --git a/src/test/ui/issues/issue-79690.stderr b/src/test/ui/issues/issue-79690.stderr new file mode 100644 index 0000000000000..c7f9c6a55e712 --- /dev/null +++ b/src/test/ui/issues/issue-79690.stderr @@ -0,0 +1,11 @@ +error[E0080]: it is undefined behavior to use this value + --> $DIR/issue-79690.rs:26:1 + | +LL | const G: Fat = unsafe { Transmute { t: FOO }.u }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered read of part of a pointer at .1..size.foo + | + = note: The rules on what exactly is undefined behavior aren't clear, so this check might be overzealous. Please open an issue on the rustc repository if you believe it should not be considered undefined behavior. + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0080`. From a7b7a435ea14cd0d2b83ea8a229e7d9cc4c651f1 Mon Sep 17 00:00:00 2001 From: Camelid Date: Sun, 10 Jan 2021 20:40:47 -0800 Subject: [PATCH 06/18] Move test to `src/test/ui/consts/` Apparently `tidy` has a hard limit of 2830 tests in the `src/test/ui/issues/` directory, and this test hit that limit. `src/test/ui/consts/` is probably a better location anyway. --- src/test/ui/{issues => consts}/issue-79690.rs | 0 src/test/ui/{issues => consts}/issue-79690.stderr | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename src/test/ui/{issues => consts}/issue-79690.rs (100%) rename src/test/ui/{issues => consts}/issue-79690.stderr (100%) diff --git a/src/test/ui/issues/issue-79690.rs b/src/test/ui/consts/issue-79690.rs similarity index 100% rename from src/test/ui/issues/issue-79690.rs rename to src/test/ui/consts/issue-79690.rs diff --git a/src/test/ui/issues/issue-79690.stderr b/src/test/ui/consts/issue-79690.stderr similarity index 100% rename from src/test/ui/issues/issue-79690.stderr rename to src/test/ui/consts/issue-79690.stderr From eaba3daa60d789997c0be3da11619df2469e9a7e Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Mon, 18 Jan 2021 13:36:32 -0600 Subject: [PATCH 07/18] Remove qpath_res util function --- src/tools/clippy/clippy_lints/src/default.rs | 4 ++-- .../clippy_lints/src/drop_forget_ref.rs | 4 ++-- src/tools/clippy/clippy_lints/src/exit.rs | 4 ++-- .../clippy/clippy_lints/src/functions.rs | 8 +++---- .../clippy/clippy_lints/src/let_if_seq.rs | 4 ++-- src/tools/clippy/clippy_lints/src/loops.rs | 22 +++++++++---------- .../clippy/clippy_lints/src/manual_strip.rs | 8 +++---- .../clippy/clippy_lints/src/mem_forget.rs | 4 ++-- .../clippy/clippy_lints/src/no_effect.rs | 6 ++--- .../clippy/clippy_lints/src/non_copy_const.rs | 4 ++-- .../clippy_lints/src/to_string_in_display.rs | 4 ++-- src/tools/clippy/clippy_lints/src/types.rs | 12 +++++----- .../clippy_lints/src/utils/internal_lints.rs | 6 ++--- .../clippy/clippy_lints/src/utils/mod.rs | 13 ----------- 14 files changed, 45 insertions(+), 58 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index f7224811e6e79..6fa1378b8c73d 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -1,5 +1,5 @@ use crate::utils::{ - any_parent_is_automatically_derived, contains_name, match_def_path, paths, qpath_res, snippet_with_macro_callsite, + any_parent_is_automatically_derived, contains_name, match_def_path, paths, snippet_with_macro_callsite, }; use crate::utils::{span_lint_and_note, span_lint_and_sugg}; use if_chain::if_chain; @@ -231,7 +231,7 @@ fn is_expr_default<'tcx>(expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> bool if_chain! { if let ExprKind::Call(ref fn_expr, _) = &expr.kind; if let ExprKind::Path(qpath) = &fn_expr.kind; - if let Res::Def(_, def_id) = qpath_res(cx, qpath, fn_expr.hir_id); + if let Res::Def(_, def_id) = cx.qpath_res(qpath, fn_expr.hir_id); then { // right hand side of assignment is `Default::default` match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD) diff --git a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs index cf528d189b4b1..a84f9c4628716 100644 --- a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs +++ b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs @@ -1,4 +1,4 @@ -use crate::utils::{is_copy, match_def_path, paths, qpath_res, span_lint_and_note}; +use crate::utils::{is_copy, match_def_path, paths, span_lint_and_note}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; @@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetRef { if let ExprKind::Call(ref path, ref args) = expr.kind; if let ExprKind::Path(ref qpath) = path.kind; if args.len() == 1; - if let Some(def_id) = qpath_res(cx, qpath, path.hir_id).opt_def_id(); + if let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id(); then { let lint; let msg; diff --git a/src/tools/clippy/clippy_lints/src/exit.rs b/src/tools/clippy/clippy_lints/src/exit.rs index 7337d98c8be37..915859270009b 100644 --- a/src/tools/clippy/clippy_lints/src/exit.rs +++ b/src/tools/clippy/clippy_lints/src/exit.rs @@ -1,4 +1,4 @@ -use crate::utils::{is_entrypoint_fn, match_def_path, paths, qpath_res, span_lint}; +use crate::utils::{is_entrypoint_fn, match_def_path, paths, span_lint}; use if_chain::if_chain; use rustc_hir::{Expr, ExprKind, Item, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; @@ -29,7 +29,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { if_chain! { if let ExprKind::Call(ref path_expr, ref _args) = e.kind; if let ExprKind::Path(ref path) = path_expr.kind; - if let Some(def_id) = qpath_res(cx, path, path_expr.hir_id).opt_def_id(); + if let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::EXIT); then { let parent = cx.tcx.hir().get_parent_item(e.hir_id); diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index fd93548b55c6d..8795425461033 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -1,7 +1,7 @@ use crate::utils::{ attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, is_type_diagnostic_item, iter_input_pats, - last_path_segment, match_def_path, must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, - span_lint_and_help, span_lint_and_then, trait_ref_of_method, type_is_unsafe_function, + last_path_segment, match_def_path, must_use_attr, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help, + span_lint_and_then, trait_ref_of_method, type_is_unsafe_function, }; use if_chain::if_chain; use rustc_ast::ast::Attribute; @@ -659,7 +659,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> { impl<'a, 'tcx> DerefVisitor<'a, 'tcx> { fn check_arg(&self, ptr: &hir::Expr<'_>) { if let hir::ExprKind::Path(ref qpath) = ptr.kind { - if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) { + if let Res::Local(id) = self.cx.qpath_res(qpath, ptr.hir_id) { if self.ptrs.contains(&id) { span_lint( self.cx, @@ -722,7 +722,7 @@ fn is_mutated_static(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool { use hir::ExprKind::{Field, Index, Path}; match e.kind { - Path(ref qpath) => !matches!(qpath_res(cx, qpath, e.hir_id), Res::Local(_)), + Path(ref qpath) => !matches!(cx.qpath_res(qpath, e.hir_id), Res::Local(_)), Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner), _ => false, } diff --git a/src/tools/clippy/clippy_lints/src/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index db717cd1240a4..5886c2360e362 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -1,4 +1,4 @@ -use crate::utils::{qpath_res, snippet, span_lint_and_then, visitors::LocalUsedVisitor}; +use crate::utils::{snippet, span_lint_and_then, visitors::LocalUsedVisitor}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; @@ -145,7 +145,7 @@ fn check_assign<'tcx>( if let hir::StmtKind::Semi(ref expr) = expr.kind; if let hir::ExprKind::Assign(ref var, ref value, _) = expr.kind; if let hir::ExprKind::Path(ref qpath) = var.kind; - if let Res::Local(local_id) = qpath_res(cx, qpath, var.hir_id); + if let Res::Local(local_id) = cx.qpath_res(qpath, var.hir_id); if decl == local_id; then { let mut v = LocalUsedVisitor::new(decl); diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index 1c5ab2874b048..1ae2c6ca95788 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -6,9 +6,9 @@ use crate::utils::visitors::LocalUsedVisitor; use crate::utils::{ contains_name, get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait, indent_of, is_in_panic_handler, is_integer_const, is_no_std_crate, is_refutable, is_type_diagnostic_item, - last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, qpath_res, single_segment_path, - snippet, snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, - span_lint_and_sugg, span_lint_and_then, sugg, SpanlessEq, + last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, single_segment_path, snippet, + snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, + span_lint_and_then, sugg, SpanlessEq, }; use if_chain::if_chain; use rustc_ast::ast; @@ -848,7 +848,7 @@ fn same_var<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, var: HirId) -> bool { if let ExprKind::Path(qpath) = &expr.kind; if let QPath::Resolved(None, path) = qpath; if path.segments.len() == 1; - if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id); + if let Res::Local(local_id) = cx.qpath_res(qpath, expr.hir_id); then { // our variable! local_id == var @@ -1420,7 +1420,7 @@ fn detect_same_item_push<'tcx>( // Make sure that the push does not involve possibly mutating values match pushed_item.kind { ExprKind::Path(ref qpath) => { - match qpath_res(cx, qpath, pushed_item.hir_id) { + match cx.qpath_res(qpath, pushed_item.hir_id) { // immutable bindings that are initialized with literal or constant Res::Local(hir_id) => { if_chain! { @@ -1437,7 +1437,7 @@ fn detect_same_item_push<'tcx>( ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item), // immutable bindings that are initialized with constant ExprKind::Path(ref path) => { - if let Res::Def(DefKind::Const, ..) = qpath_res(cx, path, init.hir_id) { + if let Res::Def(DefKind::Const, ..) = cx.qpath_res(path, init.hir_id) { emit_lint(cx, vec, pushed_item); } } @@ -2028,7 +2028,7 @@ fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option if let ExprKind::Path(ref qpath) = bound.kind; if let QPath::Resolved(None, _) = *qpath; then { - let res = qpath_res(cx, qpath, bound.hir_id); + let res = cx.qpath_res(qpath, bound.hir_id); if let Res::Local(hir_id) = res { let node_str = cx.tcx.hir().get(hir_id); if_chain! { @@ -2120,7 +2120,7 @@ impl<'a, 'tcx> VarVisitor<'a, 'tcx> { if self.prefer_mutable { self.indexed_mut.insert(seqvar.segments[0].ident.name); } - let res = qpath_res(self.cx, seqpath, seqexpr.hir_id); + let res = self.cx.qpath_res(seqpath, seqexpr.hir_id); match res { Res::Local(hir_id) => { let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id); @@ -2184,7 +2184,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { if let QPath::Resolved(None, ref path) = *qpath; if path.segments.len() == 1; then { - if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) { + if let Res::Local(local_id) = self.cx.qpath_res(qpath, expr.hir_id) { if local_id == self.var { self.nonindex = true; } else { @@ -2589,7 +2589,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> { fn var_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { if let ExprKind::Path(ref qpath) = expr.kind { - let path_res = qpath_res(cx, qpath, expr.hir_id); + let path_res = cx.qpath_res(qpath, expr.hir_id); if let Res::Local(hir_id) = path_res { return Some(hir_id); } @@ -2819,7 +2819,7 @@ impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> { if_chain! { if let ExprKind::Path(ref qpath) = ex.kind; if let QPath::Resolved(None, _) = *qpath; - let res = qpath_res(self.cx, qpath, ex.hir_id); + let res = self.cx.qpath_res(qpath, ex.hir_id); then { match res { Res::Local(hir_id) => { diff --git a/src/tools/clippy/clippy_lints/src/manual_strip.rs b/src/tools/clippy/clippy_lints/src/manual_strip.rs index a0cfe145a301c..42a92104a4919 100644 --- a/src/tools/clippy/clippy_lints/src/manual_strip.rs +++ b/src/tools/clippy/clippy_lints/src/manual_strip.rs @@ -1,7 +1,7 @@ use crate::consts::{constant, Constant}; use crate::utils::usage::mutated_variables; use crate::utils::{ - eq_expr_value, higher, match_def_path, meets_msrv, multispan_sugg, paths, qpath_res, snippet, span_lint_and_then, + eq_expr_value, higher, match_def_path, meets_msrv, multispan_sugg, paths, snippet, span_lint_and_then, }; use if_chain::if_chain; @@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualStrip { } else { return; }; - let target_res = qpath_res(cx, &target_path, target_arg.hir_id); + let target_res = cx.qpath_res(&target_path, target_arg.hir_id); if target_res == Res::Err { return; }; @@ -221,7 +221,7 @@ fn find_stripping<'tcx>( if let ExprKind::Index(indexed, index) = &unref.kind; if let Some(higher::Range { start, end, .. }) = higher::range(index); if let ExprKind::Path(path) = &indexed.kind; - if qpath_res(self.cx, path, ex.hir_id) == self.target; + if self.cx.qpath_res(path, ex.hir_id) == self.target; then { match (self.strip_kind, start, end) { (StripKind::Prefix, Some(start), None) => { @@ -235,7 +235,7 @@ fn find_stripping<'tcx>( if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, left, right) = end.kind; if let Some(left_arg) = len_arg(self.cx, left); if let ExprKind::Path(left_path) = &left_arg.kind; - if qpath_res(self.cx, left_path, left_arg.hir_id) == self.target; + if self.cx.qpath_res(left_path, left_arg.hir_id) == self.target; if eq_pattern_length(self.cx, self.pattern, right); then { self.results.push(ex.span); diff --git a/src/tools/clippy/clippy_lints/src/mem_forget.rs b/src/tools/clippy/clippy_lints/src/mem_forget.rs index 8c6fd10f98a1e..d34f9761e26f9 100644 --- a/src/tools/clippy/clippy_lints/src/mem_forget.rs +++ b/src/tools/clippy/clippy_lints/src/mem_forget.rs @@ -1,4 +1,4 @@ -use crate::utils::{match_def_path, paths, qpath_res, span_lint}; +use crate::utils::{match_def_path, paths, span_lint}; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -29,7 +29,7 @@ impl<'tcx> LateLintPass<'tcx> for MemForget { fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) { if let ExprKind::Call(ref path_expr, ref args) = e.kind { if let ExprKind::Path(ref qpath) = path_expr.kind { - if let Some(def_id) = qpath_res(cx, qpath, path_expr.hir_id).opt_def_id() { + if let Some(def_id) = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id() { if match_def_path(cx, def_id, &paths::MEM_FORGET) { let forgot_ty = cx.typeck_results().expr_ty(&args[0]); diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index b1b5b3439a0e3..69302d695ce0a 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -1,4 +1,4 @@ -use crate::utils::{has_drop, qpath_res, snippet_opt, span_lint, span_lint_and_sugg}; +use crate::utils::{has_drop, snippet_opt, span_lint, span_lint_and_sugg}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::{BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource}; @@ -67,7 +67,7 @@ fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { }, ExprKind::Call(ref callee, ref args) => { if let ExprKind::Path(ref qpath) = callee.kind { - let res = qpath_res(cx, qpath, callee.hir_id); + let res = cx.qpath_res(qpath, callee.hir_id); match res { Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) => { !has_drop(cx, cx.typeck_results().expr_ty(expr)) @@ -146,7 +146,7 @@ fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option { if let ExprKind::Path(ref qpath) = callee.kind { - let res = qpath_res(cx, qpath, callee.hir_id); + let res = cx.qpath_res(qpath, callee.hir_id); match res { Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) if !has_drop(cx, cx.typeck_results().expr_ty(expr)) => diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 3a9aa6ced03ba..f57d753631755 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -18,7 +18,7 @@ use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{InnerSpan, Span, DUMMY_SP}; use rustc_typeck::hir_ty_to_ty; -use crate::utils::{in_constant, qpath_res, span_lint_and_then}; +use crate::utils::{in_constant, span_lint_and_then}; use if_chain::if_chain; // FIXME: this is a correctness problem but there's no suitable @@ -339,7 +339,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { } // Make sure it is a const item. - let item_def_id = match qpath_res(cx, qpath, expr.hir_id) { + let item_def_id = match cx.qpath_res(qpath, expr.hir_id) { Res::Def(DefKind::Const | DefKind::AssocConst, did) => did, _ => return, }; diff --git a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs index c53727ba16004..fa508df865e48 100644 --- a/src/tools/clippy/clippy_lints/src/to_string_in_display.rs +++ b/src/tools/clippy/clippy_lints/src/to_string_in_display.rs @@ -1,4 +1,4 @@ -use crate::utils::{match_def_path, match_trait_method, paths, qpath_res, span_lint}; +use crate::utils::{match_def_path, match_trait_method, paths, span_lint}; use if_chain::if_chain; use rustc_hir::def::Res; use rustc_hir::{Expr, ExprKind, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind}; @@ -94,7 +94,7 @@ impl LateLintPass<'_> for ToStringInDisplay { if match_trait_method(cx, expr, &paths::TO_STRING); if self.in_display_impl; if let ExprKind::Path(ref qpath) = args[0].kind; - if let Res::Local(hir_id) = qpath_res(cx, qpath, args[0].hir_id); + if let Res::Local(hir_id) = cx.qpath_res(qpath, args[0].hir_id); if let Some(self_hir_id) = self.self_hir_id; if hir_id == self_hir_id; then { diff --git a/src/tools/clippy/clippy_lints/src/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index 3b5a83d2a0bec..624ea16f585d2 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -34,7 +34,7 @@ use crate::utils::sugg::Sugg; use crate::utils::{ clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_hir_ty_cfg_dependant, is_type_diagnostic_item, last_path_segment, match_def_path, match_path, meets_msrv, method_chain_args, - multispan_sugg, numeric_literal::NumericLiteral, qpath_res, reindent_multiline, sext, snippet, snippet_opt, + multispan_sugg, numeric_literal::NumericLiteral, reindent_multiline, sext, snippet, snippet_opt, snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext, }; @@ -298,7 +298,7 @@ fn match_type_parameter(cx: &LateContext<'_>, qpath: &QPath<'_>, path: &[&str]) _ => None, }); if let TyKind::Path(ref qpath) = ty.kind; - if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id(); + if let Some(did) = cx.qpath_res(qpath, ty.hir_id).opt_def_id(); if match_def_path(cx, did, path); then { return Some(ty.span); @@ -365,7 +365,7 @@ impl Types { match hir_ty.kind { TyKind::Path(ref qpath) if !is_local => { let hir_id = hir_ty.hir_id; - let res = qpath_res(cx, qpath, hir_id); + let res = cx.qpath_res(qpath, hir_id); if let Some(def_id) = res.opt_def_id() { if Some(def_id) == cx.tcx.lang_items().owned_box() { if let Some(span) = match_borrows_parameter(cx, qpath) { @@ -535,7 +535,7 @@ impl Types { }); // ty is now _ at this point if let TyKind::Path(ref ty_qpath) = ty.kind; - let res = qpath_res(cx, ty_qpath, ty.hir_id); + let res = cx.qpath_res(ty_qpath, ty.hir_id); if let Some(def_id) = res.opt_def_id(); if Some(def_id) == cx.tcx.lang_items().owned_box(); // At this point, we know ty is Box, now get T @@ -652,7 +652,7 @@ impl Types { match mut_ty.ty.kind { TyKind::Path(ref qpath) => { let hir_id = mut_ty.ty.hir_id; - let def = qpath_res(cx, qpath, hir_id); + let def = cx.qpath_res(qpath, hir_id); if_chain! { if let Some(def_id) = def.opt_def_id(); if Some(def_id) == cx.tcx.lang_items().owned_box(); @@ -739,7 +739,7 @@ fn is_any_trait(t: &hir::Ty<'_>) -> bool { fn get_bounds_if_impl_trait<'tcx>(cx: &LateContext<'tcx>, qpath: &QPath<'_>, id: HirId) -> Option> { if_chain! { - if let Some(did) = qpath_res(cx, qpath, id).opt_def_id(); + if let Some(did) = cx.qpath_res(qpath, id).opt_def_id(); if let Some(Node::GenericParam(generic_param)) = cx.tcx.hir().get_if_local(did); if let GenericParamKind::Type { synthetic, .. } = generic_param.kind; if synthetic == Some(SyntheticTyParamKind::ImplTrait); diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index 7aa17520ba79f..822863ca3e279 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -1,7 +1,7 @@ use crate::consts::{constant_simple, Constant}; use crate::utils::{ - is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, qpath_res, run_lints, - snippet, span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq, + is_expn_of, match_def_path, match_qpath, match_type, method_calls, path_to_res, paths, run_lints, snippet, + span_lint, span_lint_and_help, span_lint_and_sugg, SpanlessEq, }; use if_chain::if_chain; use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, NodeId}; @@ -787,7 +787,7 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option return path_to_matched_type(cx, expr), - ExprKind::Path(qpath) => match qpath_res(cx, qpath, expr.hir_id) { + ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) { Res::Local(hir_id) => { let parent_id = cx.tcx.hir().get_parent_node(hir_id); if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) { diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 9b262517a9834..023fb0a7112c1 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -370,19 +370,6 @@ pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option { } } -pub fn qpath_res(cx: &LateContext<'_>, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { - match qpath { - hir::QPath::Resolved(_, path) => path.res, - hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => { - if cx.tcx.has_typeck_results(id.owner.to_def_id()) { - cx.tcx.typeck(id.owner).qpath_res(qpath, id) - } else { - Res::Err - } - }, - } -} - /// Convenience function to get the `DefId` of a trait by path. /// It could be a trait or trait alias. pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option { From 3b8f1b7883d300bb1a435b994c90433774105cc9 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Fri, 22 Jan 2021 14:33:21 -0500 Subject: [PATCH 08/18] Make `-Z time-passes` less noisy - Add the module name to `pre_AST_expansion_passes` and don't make it a verbose event (since it normally doesn't take very long, and it's emitted many times) - Don't make the following rustdoc events verbose; they're emitted many times. + build_extern_trait_impl + build_local_trait_impl + build_primitive_trait_impl + get_auto_trait_impls + get_blanket_trait_impls - Remove `get_auto_trait_and_blanket_synthetic_impls`; it's wholly covered by get_{auto,blanket}_trait_impls and not very useful. --- compiler/rustc_expand/src/base.rs | 6 ++++-- compiler/rustc_expand/src/expand.rs | 2 +- compiler/rustc_interface/src/passes.rs | 17 ++++++++++++----- src/librustdoc/clean/utils.rs | 16 ++++++++++------ src/librustdoc/passes/collect_trait_impls.rs | 18 ++++++++---------- 5 files changed, 35 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 2f43940a9dcbb..08543d1622a7d 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -929,7 +929,9 @@ pub struct ExtCtxt<'a> { pub force_mode: bool, pub expansions: FxHashMap>, /// Called directly after having parsed an external `mod foo;` in expansion. - pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>, + /// + /// `Ident` is the module name. + pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate, Ident)>, } impl<'a> ExtCtxt<'a> { @@ -937,7 +939,7 @@ impl<'a> ExtCtxt<'a> { sess: &'a Session, ecfg: expand::ExpansionConfig<'a>, resolver: &'a mut dyn ResolverExpand, - extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>, + extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate, Ident)>, ) -> ExtCtxt<'a> { ExtCtxt { sess, diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 16913dbb1abf8..edfe2edd3e3b7 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1407,7 +1407,7 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { proc_macros: vec![], }; if let Some(extern_mod_loaded) = self.cx.extern_mod_loaded { - extern_mod_loaded(&krate); + extern_mod_loaded(&krate, ident); } *old_mod = krate.module; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index ead2512d3b2a5..6eba378b689a9 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -33,7 +33,7 @@ use rustc_session::lint; use rustc_session::output::{filename_for_input, filename_for_metadata}; use rustc_session::search_paths::PathKind; use rustc_session::Session; -use rustc_span::symbol::Symbol; +use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{FileName, RealFileName}; use rustc_trait_selection::traits; use rustc_typeck as typeck; @@ -211,8 +211,13 @@ pub fn register_plugins<'a>( Ok((krate, lint_store)) } -fn pre_expansion_lint(sess: &Session, lint_store: &LintStore, krate: &ast::Crate) { - sess.time("pre_AST_expansion_lint_checks", || { +fn pre_expansion_lint( + sess: &Session, + lint_store: &LintStore, + krate: &ast::Crate, + crate_name: &str, +) { + sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", crate_name).run(|| { rustc_lint::check_ast_crate( sess, lint_store, @@ -233,7 +238,7 @@ fn configure_and_expand_inner<'a>( metadata_loader: &'a MetadataLoaderDyn, ) -> Result<(ast::Crate, Resolver<'a>)> { tracing::trace!("configure_and_expand_inner"); - pre_expansion_lint(sess, lint_store, &krate); + pre_expansion_lint(sess, lint_store, &krate, crate_name); let mut resolver = Resolver::new(sess, &krate, crate_name, metadata_loader, &resolver_arenas); rustc_builtin_macros::register_builtin_macros(&mut resolver); @@ -295,7 +300,9 @@ fn configure_and_expand_inner<'a>( ..rustc_expand::expand::ExpansionConfig::default(crate_name.to_string()) }; - let extern_mod_loaded = |k: &ast::Crate| pre_expansion_lint(sess, lint_store, k); + let extern_mod_loaded = |k: &ast::Crate, ident: Ident| { + pre_expansion_lint(sess, lint_store, k, &*ident.name.as_str()) + }; let mut ecx = ExtCtxt::new(&sess, cfg, &mut resolver, Some(&extern_mod_loaded)); // Expand macros now! diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 0f5495c831058..60bd3c984b728 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -487,12 +487,16 @@ crate fn get_auto_trait_and_blanket_impls( ty: Ty<'tcx>, param_env_def_id: DefId, ) -> impl Iterator { - let auto_impls = cx.sess().time("get_auto_trait_impls", || { - AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id) - }); - let blanket_impls = cx.sess().time("get_blanket_impls", || { - BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id) - }); + let auto_impls = cx + .sess() + .prof + .generic_activity("get_auto_trait_impls") + .run(|| AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id)); + let blanket_impls = cx + .sess() + .prof + .generic_activity("get_blanket_impls") + .run(|| BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id)); auto_impls.into_iter().chain(blanket_impls) } diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index 7b5e9e5905f33..6ec6620681bf5 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -30,7 +30,7 @@ crate fn collect_trait_impls(krate: Crate, cx: &DocContext<'_>) -> Crate { for &cnum in cx.tcx.crates().iter() { for &(did, _) in cx.tcx.all_trait_implementations(cnum).iter() { - cx.tcx.sess.time("build_extern_trait_impl", || { + cx.tcx.sess.prof.generic_activity("build_extern_trait_impl").run(|| { inline::build_impl(cx, None, did, None, &mut new_items); }); } @@ -39,7 +39,7 @@ crate fn collect_trait_impls(krate: Crate, cx: &DocContext<'_>) -> Crate { // Also try to inline primitive impls from other crates. for &def_id in PrimitiveType::all_impls(cx.tcx).values().flatten() { if !def_id.is_local() { - cx.sess().time("build_primitive_trait_impl", || { + cx.tcx.sess.prof.generic_activity("build_primitive_trait_impls").run(|| { inline::build_impl(cx, None, def_id, None, &mut new_items); // FIXME(eddyb) is this `doc(hidden)` check needed? @@ -59,7 +59,7 @@ crate fn collect_trait_impls(krate: Crate, cx: &DocContext<'_>) -> Crate { for &trait_did in cx.tcx.all_traits(LOCAL_CRATE).iter() { for &impl_node in cx.tcx.hir().trait_impls(trait_did) { let impl_did = cx.tcx.hir().local_def_id(impl_node); - cx.tcx.sess.time("build_local_trait_impl", || { + cx.tcx.sess.prof.generic_activity("build_local_trait_impl").run(|| { let mut extra_attrs = Vec::new(); let mut parent = cx.tcx.parent(impl_did.to_def_id()); while let Some(did) = parent { @@ -177,13 +177,11 @@ impl<'a, 'tcx> DocFolder for SyntheticImplCollector<'a, 'tcx> { if i.is_struct() || i.is_enum() || i.is_union() { // FIXME(eddyb) is this `doc(hidden)` check needed? if !self.cx.tcx.get_attrs(i.def_id).lists(sym::doc).has_word(sym::hidden) { - self.cx.sess().time("get_auto_trait_and_blanket_synthetic_impls", || { - self.impls.extend(get_auto_trait_and_blanket_impls( - self.cx, - self.cx.tcx.type_of(i.def_id), - i.def_id, - )); - }); + self.impls.extend(get_auto_trait_and_blanket_impls( + self.cx, + self.cx.tcx.type_of(i.def_id), + i.def_id, + )); } } From 1d03648e67b2dc3ea86a8d7f6f0c376142d500e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20=C3=85kerblom?= Date: Sun, 24 Jan 2021 20:31:42 +0100 Subject: [PATCH 09/18] Fix spelling in documentation for error E0207 I have trouble parsing the the wording "type parameter parameter". --- compiler/rustc_error_codes/src/error_codes/E0207.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_error_codes/src/error_codes/E0207.md b/compiler/rustc_error_codes/src/error_codes/E0207.md index cb4f5d5157d9b..8a7923ac93f98 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0207.md +++ b/compiler/rustc_error_codes/src/error_codes/E0207.md @@ -14,7 +14,7 @@ impl Foo { } ``` -Any type parameter parameter of an `impl` must meet at least one of +Any type parameter of an `impl` must meet at least one of the following criteria: - it appears in the _implementing type_ of the impl, e.g. `impl Foo` From 2be19932335f76cb4a97c275038a019751fbba6a Mon Sep 17 00:00:00 2001 From: Camelid Date: Sun, 24 Jan 2021 19:38:10 -0800 Subject: [PATCH 10/18] Ignore test on 32-bit architectures --- src/test/ui/consts/issue-79690.rs | 3 +++ src/test/ui/consts/issue-79690.stderr | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/test/ui/consts/issue-79690.rs b/src/test/ui/consts/issue-79690.rs index 6a38b3c8c2c71..a2e7b97b3187d 100644 --- a/src/test/ui/consts/issue-79690.rs +++ b/src/test/ui/consts/issue-79690.rs @@ -1,3 +1,6 @@ +// ignore-32bit +// This test gives a different error on 32-bit architectures. + union Transmute { t: T, u: U, diff --git a/src/test/ui/consts/issue-79690.stderr b/src/test/ui/consts/issue-79690.stderr index c7f9c6a55e712..918dd4c20f96c 100644 --- a/src/test/ui/consts/issue-79690.stderr +++ b/src/test/ui/consts/issue-79690.stderr @@ -1,5 +1,5 @@ error[E0080]: it is undefined behavior to use this value - --> $DIR/issue-79690.rs:26:1 + --> $DIR/issue-79690.rs:29:1 | LL | const G: Fat = unsafe { Transmute { t: FOO }.u }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type validation failed: encountered read of part of a pointer at .1..size.foo From 59195a277246ec194ca3a02ecc563c4dd9c06857 Mon Sep 17 00:00:00 2001 From: Tyson Nottingham Date: Sun, 24 Jan 2021 21:23:38 -0800 Subject: [PATCH 11/18] rustc_codegen_ssa: use wall time for codegen_to_LLVM_IR time-passes entry Use elapsed wall time spent on codegen_to_LLVM_IR for all CGUs as a whole, rather than the sum for each CGU (the distinction matters for parallel builds, where some CGUs are processed in parallel). --- compiler/rustc_codegen_ssa/src/base.rs | 31 ++++++++++++-------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 2ce5fe5ad504b..ad72dc0086b61 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -13,7 +13,7 @@ use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind} use rustc_attr as attr; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::profiling::print_time_passes_entry; -use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator}; +use rustc_data_structures::sync::{par_iter, ParallelIterator}; use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE}; use rustc_hir::lang_items::LangItem; @@ -554,8 +554,6 @@ pub fn codegen_crate( codegen_units }; - let total_codegen_time = Lock::new(Duration::new(0, 0)); - // The non-parallel compiler can only translate codegen units to LLVM IR // on a single thread, leading to a staircase effect where the N LLVM // threads have to wait on the single codegen threads to generate work @@ -578,23 +576,25 @@ pub fn codegen_crate( .collect(); // Compile the found CGUs in parallel. - par_iter(cgus) + let start_time = Instant::now(); + + let pre_compiled_cgus = par_iter(cgus) .map(|(i, _)| { - let start_time = Instant::now(); let module = backend.compile_codegen_unit(tcx, codegen_units[i].name()); - let mut time = total_codegen_time.lock(); - *time += start_time.elapsed(); (i, module) }) - .collect() + .collect(); + + (pre_compiled_cgus, start_time.elapsed()) }) } else { - FxHashMap::default() + (FxHashMap::default(), Duration::new(0, 0)) } }; let mut cgu_reuse = Vec::new(); let mut pre_compiled_cgus: Option> = None; + let mut total_codegen_time = Duration::new(0, 0); for (i, cgu) in codegen_units.iter().enumerate() { ongoing_codegen.wait_for_signal_to_codegen_item(); @@ -607,7 +607,9 @@ pub fn codegen_crate( codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect() }); // Pre compile some CGUs - pre_compiled_cgus = Some(pre_compile_cgus(&cgu_reuse)); + let (compiled_cgus, codegen_time) = pre_compile_cgus(&cgu_reuse); + pre_compiled_cgus = Some(compiled_cgus); + total_codegen_time += codegen_time; } let cgu_reuse = cgu_reuse[i]; @@ -621,8 +623,7 @@ pub fn codegen_crate( } else { let start_time = Instant::now(); let module = backend.compile_codegen_unit(tcx, cgu.name()); - let mut time = total_codegen_time.lock(); - *time += start_time.elapsed(); + total_codegen_time += start_time.elapsed(); module }; submit_codegened_module_to_llvm( @@ -663,11 +664,7 @@ pub fn codegen_crate( // Since the main thread is sometimes blocked during codegen, we keep track // -Ztime-passes output manually. - print_time_passes_entry( - tcx.sess.time_passes(), - "codegen_to_LLVM_IR", - total_codegen_time.into_inner(), - ); + print_time_passes_entry(tcx.sess.time_passes(), "codegen_to_LLVM_IR", total_codegen_time); ongoing_codegen.check_for_errors(tcx.sess); From 088c89d9ffe47fb6d1b51c8edfd8ad652ee2a7f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Tue, 19 Jan 2021 12:44:49 -0800 Subject: [PATCH 12/18] Account for generics when suggesting bound Fix #81175. --- .../src/traits/error_reporting/suggestions.rs | 35 +++++--- src/test/ui/bound-suggestions.fixed | 27 +++++- src/test/ui/bound-suggestions.rs | 27 +++++- src/test/ui/bound-suggestions.stderr | 82 ++++++++++++++++++- 4 files changed, 156 insertions(+), 15 deletions(-) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 1830aaa4471a6..0ab00fddfafc8 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -286,21 +286,32 @@ fn suggest_restriction( ); } else { // Trivial case: `T` needs an extra bound: `T: Bound`. - let (sp, suggestion) = match super_traits { - None => predicate_constraint( + let (sp, suggestion) = match ( + generics + .params + .iter() + .filter( + |p| !matches!(p.kind, hir::GenericParamKind::Type { synthetic: Some(_), ..}), + ) + .next(), + super_traits, + ) { + (_, None) => predicate_constraint( generics, trait_ref.without_const().to_predicate(tcx).to_string(), ), - Some((ident, bounds)) => match bounds { - [.., bound] => ( - bound.span().shrink_to_hi(), - format!(" + {}", trait_ref.print_only_trait_path().to_string()), - ), - [] => ( - ident.span.shrink_to_hi(), - format!(": {}", trait_ref.print_only_trait_path().to_string()), - ), - }, + (None, Some((ident, []))) => ( + ident.span.shrink_to_hi(), + format!(": {}", trait_ref.print_only_trait_path().to_string()), + ), + (_, Some((_, [.., bounds]))) => ( + bounds.span().shrink_to_hi(), + format!(" + {}", trait_ref.print_only_trait_path().to_string()), + ), + (Some(_), Some((_, []))) => ( + generics.span.shrink_to_hi(), + format!(": {}", trait_ref.print_only_trait_path().to_string()), + ), }; err.span_suggestion_verbose( diff --git a/src/test/ui/bound-suggestions.fixed b/src/test/ui/bound-suggestions.fixed index a3fe67a95954f..be61b7dda256a 100644 --- a/src/test/ui/bound-suggestions.fixed +++ b/src/test/ui/bound-suggestions.fixed @@ -40,4 +40,29 @@ fn test_many_bounds_where(x: X) where X: Sized, X: Sized, X: Debug { //~^ ERROR doesn't implement } -pub fn main() { } +trait Foo: Sized { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Bar: std::fmt::Display + Sized { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Baz: Sized where Self: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Qux: Sized where Self: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Bat: std::fmt::Display + Sized { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +fn main() { } diff --git a/src/test/ui/bound-suggestions.rs b/src/test/ui/bound-suggestions.rs index de6133d7f59ac..86f708d42f5e7 100644 --- a/src/test/ui/bound-suggestions.rs +++ b/src/test/ui/bound-suggestions.rs @@ -40,4 +40,29 @@ fn test_many_bounds_where(x: X) where X: Sized, X: Sized { //~^ ERROR doesn't implement } -pub fn main() { } +trait Foo { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Bar: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Baz where Self: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Qux where Self: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +trait Bat: std::fmt::Display { + const SIZE: usize = core::mem::size_of::(); + //~^ ERROR the size for values of type `Self` cannot be known at compilation time +} + +fn main() { } diff --git a/src/test/ui/bound-suggestions.stderr b/src/test/ui/bound-suggestions.stderr index 010f95d8ad6f0..12e67e90265ab 100644 --- a/src/test/ui/bound-suggestions.stderr +++ b/src/test/ui/bound-suggestions.stderr @@ -76,6 +76,86 @@ help: consider further restricting type parameter `X` LL | fn test_many_bounds_where(x: X) where X: Sized, X: Sized, X: Debug { | ^^^^^^^^^^ -error: aborting due to 6 previous errors +error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/bound-suggestions.rs:44:46 + | +LL | const SIZE: usize = core::mem::size_of::(); + | ^^^^ doesn't have a size known at compile-time + | + ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL + | +LL | pub const fn size_of() -> usize { + | - required by this bound in `std::mem::size_of` + | +help: consider further restricting `Self` + | +LL | trait Foo: Sized { + | ^^^^^^^ + +error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/bound-suggestions.rs:49:46 + | +LL | const SIZE: usize = core::mem::size_of::(); + | ^^^^ doesn't have a size known at compile-time + | + ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL + | +LL | pub const fn size_of() -> usize { + | - required by this bound in `std::mem::size_of` + | +help: consider further restricting `Self` + | +LL | trait Bar: std::fmt::Display + Sized { + | ^^^^^^^ + +error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/bound-suggestions.rs:54:46 + | +LL | const SIZE: usize = core::mem::size_of::(); + | ^^^^ doesn't have a size known at compile-time + | + ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL + | +LL | pub const fn size_of() -> usize { + | - required by this bound in `std::mem::size_of` + | +help: consider further restricting `Self` + | +LL | trait Baz: Sized where Self: std::fmt::Display { + | ^^^^^^^ + +error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/bound-suggestions.rs:59:46 + | +LL | const SIZE: usize = core::mem::size_of::(); + | ^^^^ doesn't have a size known at compile-time + | + ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL + | +LL | pub const fn size_of() -> usize { + | - required by this bound in `std::mem::size_of` + | +help: consider further restricting `Self` + | +LL | trait Qux: Sized where Self: std::fmt::Display { + | ^^^^^^^ + +error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/bound-suggestions.rs:64:46 + | +LL | const SIZE: usize = core::mem::size_of::(); + | ^^^^ doesn't have a size known at compile-time + | + ::: $SRC_DIR/core/src/mem/mod.rs:LL:COL + | +LL | pub const fn size_of() -> usize { + | - required by this bound in `std::mem::size_of` + | +help: consider further restricting `Self` + | +LL | trait Bat: std::fmt::Display + Sized { + | ^^^^^^^ + +error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0277`. From 042facb9357f9b6248b0b2b6c5624742c3948e47 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Sat, 23 Jan 2021 14:55:24 +0100 Subject: [PATCH 13/18] Fix some bugs reported by eslint --- src/librustdoc/html/static/main.js | 50 +++++++++------------ src/librustdoc/html/static/settings.js | 2 +- src/librustdoc/html/static/source-script.js | 2 + src/librustdoc/html/static/storage.js | 10 ++++- 4 files changed, 33 insertions(+), 31 deletions(-) diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js index 74bd348e9ac1c..53f0831852456 100644 --- a/src/librustdoc/html/static/main.js +++ b/src/librustdoc/html/static/main.js @@ -1,9 +1,6 @@ -// From rust: -/* global ALIASES */ - // Local js definitions: -/* global addClass, getCurrentValue, hasClass */ -/* global onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */ +/* global addClass, getSettingValue, hasClass */ +/* global onEach, onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */ /* global hideThemeButtonState, showThemeButtonState */ if (!String.prototype.startsWith) { @@ -2214,7 +2211,7 @@ function defocusSearchBar() { } } - function toggleAllDocs(pageId, fromAutoCollapse) { + function toggleAllDocs(fromAutoCollapse) { var innerToggle = document.getElementById(toggleAllDocsId); if (!innerToggle) { return; @@ -2257,14 +2254,14 @@ function defocusSearchBar() { } if (!parent || !superParent || superParent.id !== "main" || hasClass(parent, "impl") === false) { - collapseDocs(e, "hide", pageId); + collapseDocs(e, "hide"); } }); } } } - function collapseDocs(toggle, mode, pageId) { + function collapseDocs(toggle, mode) { if (!toggle || !toggle.parentNode) { return; } @@ -2384,27 +2381,27 @@ function defocusSearchBar() { } } - function collapser(pageId, e, collapse) { + function collapser(e, collapse) { // inherent impl ids are like "impl" or impl-'. // they will never be hidden by default. var n = e.parentElement; if (n.id.match(/^impl(?:-\d+)?$/) === null) { // Automatically minimize all non-inherent impls if (collapse || hasClass(n, "impl")) { - collapseDocs(e, "hide", pageId); + collapseDocs(e, "hide"); } } } - function autoCollapse(pageId, collapse) { + function autoCollapse(collapse) { if (collapse) { - toggleAllDocs(pageId, true); + toggleAllDocs(true); } else if (getSettingValue("auto-hide-trait-implementations") !== "false") { var impl_list = document.getElementById("trait-implementations-list"); if (impl_list !== null) { onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) { - collapser(pageId, e, collapse); + collapser(e, collapse); }); } @@ -2412,7 +2409,7 @@ function defocusSearchBar() { if (blanket_list !== null) { onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) { - collapser(pageId, e, collapse); + collapser(e, collapse); }); } } @@ -2475,7 +2472,6 @@ function defocusSearchBar() { var toggle = createSimpleToggle(false); var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true"; var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false"; - var pageId = getPageId(); var func = function(e) { var next = e.nextElementSibling; @@ -2489,7 +2485,7 @@ function defocusSearchBar() { var newToggle = toggle.cloneNode(true); insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]); if (hideMethodDocs === true && hasClass(e, "method") === true) { - collapseDocs(newToggle, "hide", pageId); + collapseDocs(newToggle, "hide"); } } }; @@ -2513,7 +2509,7 @@ function defocusSearchBar() { // In case the option "auto-collapse implementors" is not set to false, we collapse // all implementors. if (hideImplementors === true && e.parentNode.id === "implementors-list") { - collapseDocs(newToggle, "hide", pageId); + collapseDocs(newToggle, "hide"); } } }; @@ -2527,7 +2523,7 @@ function defocusSearchBar() { if (e.id.match(/^impl(?:-\d+)?$/) === null) { // Automatically minimize all non-inherent impls if (hasClass(e, "impl") === true) { - collapseDocs(newToggle, "hide", pageId); + collapseDocs(newToggle, "hide"); } } }; @@ -2562,14 +2558,12 @@ function defocusSearchBar() { } onEachLazy(document.getElementsByClassName("impl-items"), function(e) { onEachLazy(e.getElementsByClassName("associatedconstant"), func); - var hiddenElems = e.getElementsByClassName("hidden"); - var needToggle = false; - - var needToggle = onEachLazy(e.getElementsByClassName("hidden"), function(hiddenElem) { - if (hasClass(hiddenElem, "content") === false && - hasClass(hiddenElem, "docblock") === false) { - return true; - } + // We transform the DOM iterator into a vec of DOM elements to prevent performance + // issues on webkit browsers. + var hiddenElems = Array.prototype.slice.call(e.getElementsByClassName("hidden")); + var needToggle = hiddenElems.some(function(hiddenElem) { + return hasClass(hiddenElem, "content") === false && + hasClass(hiddenElem, "docblock") === false; }); if (needToggle === true) { var inner_toggle = newToggle.cloneNode(true); @@ -2672,10 +2666,10 @@ function defocusSearchBar() { onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper); onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper); - var pageId = getPageId(); - autoCollapse(pageId, getSettingValue("collapse") === "true"); + autoCollapse(getSettingValue("collapse") === "true"); + var pageId = getPageId(); if (pageId !== null) { expandSection(pageId); } diff --git a/src/librustdoc/html/static/settings.js b/src/librustdoc/html/static/settings.js index bc14420232c4d..4f10e14e8558c 100644 --- a/src/librustdoc/html/static/settings.js +++ b/src/librustdoc/html/static/settings.js @@ -1,5 +1,5 @@ // Local js definitions: -/* global getCurrentValue, getVirtualKey, updateLocalStorage, updateSystemTheme */ +/* global getSettingValue, getVirtualKey, onEachLazy, updateLocalStorage, updateSystemTheme */ (function () { function changeSetting(settingName, value) { diff --git a/src/librustdoc/html/static/source-script.js b/src/librustdoc/html/static/source-script.js index a9cc0ffdf79b0..42b54e4cc1e46 100644 --- a/src/librustdoc/html/static/source-script.js +++ b/src/librustdoc/html/static/source-script.js @@ -113,6 +113,8 @@ function createSidebarToggle() { return sidebarToggle; } +// This function is called from "source-files.js", generated in `html/render/mod.rs`. +// eslint-disable-next-line no-unused-vars function createSourceSidebar() { if (window.rootPath.endsWith("/") === false) { window.rootPath += "/"; diff --git a/src/librustdoc/html/static/storage.js b/src/librustdoc/html/static/storage.js index d081781f14be1..9c5ac1625afea 100644 --- a/src/librustdoc/html/static/storage.js +++ b/src/librustdoc/html/static/storage.js @@ -1,5 +1,5 @@ // From rust: -/* global resourcesSuffix, getSettingValue */ +/* global resourcesSuffix */ var darkThemes = ["dark", "ayu"]; var currentTheme = document.getElementById("themeStyle"); @@ -35,10 +35,12 @@ var localStoredTheme = getSettingValue("theme"); var savedHref = []; +// eslint-disable-next-line no-unused-vars function hasClass(elem, className) { return elem && elem.classList && elem.classList.contains(className); } +// eslint-disable-next-line no-unused-vars function addClass(elem, className) { if (!elem || !elem.classList) { return; @@ -46,6 +48,7 @@ function addClass(elem, className) { elem.classList.add(className); } +// eslint-disable-next-line no-unused-vars function removeClass(elem, className) { if (!elem || !elem.classList) { return; @@ -81,6 +84,7 @@ function onEachLazy(lazyArray, func, reversed) { reversed); } +// eslint-disable-next-line no-unused-vars function hasOwnProperty(obj, property) { return Object.prototype.hasOwnProperty.call(obj, property); } @@ -148,6 +152,8 @@ function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) { } } +// This function is called from "theme.js", generated in `html/render/mod.rs`. +// eslint-disable-next-line no-unused-vars function useSystemTheme(value) { if (value === undefined) { value = true; @@ -172,7 +178,7 @@ var updateSystemTheme = (function() { switchTheme( currentTheme, mainTheme, - JSON.parse(cssTheme) || light, + JSON.parse(cssTheme) || "light", true ); }; From 0140dacabbc6b5a33f19f88c22b531f318ef8f37 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 25 Jan 2021 14:53:19 +0100 Subject: [PATCH 14/18] Link the reference about undefined behavior Suggested-by: Mara Bos Signed-off-by: Miguel Ojeda --- library/core/src/option.rs | 4 +++- library/core/src/result.rs | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 5d34f5ca155bf..9f89bfd674a74 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -433,7 +433,9 @@ impl Option { /// /// # Safety /// - /// Undefined behavior if the value is [`None`]. + /// Calling this method on [`None`] is *[undefined behavior]*. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html /// /// # Examples /// diff --git a/library/core/src/result.rs b/library/core/src/result.rs index a357750b92f9d..436f4bf20c7e7 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -827,7 +827,9 @@ impl Result { /// /// # Safety /// - /// Undefined behavior if the value is an [`Err`]. + /// Calling this method on an [`Err`] is *[undefined behavior]*. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html /// /// # Examples /// @@ -859,7 +861,9 @@ impl Result { /// /// # Safety /// - /// Undefined behavior if the value is an [`Ok`]. + /// Calling this method on an [`Ok`] is *[undefined behavior]*. + /// + /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html /// /// # Examples /// From 01250fcec6c77552b0f7aac11ed833412294ccba Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 25 Jan 2021 14:58:09 +0100 Subject: [PATCH 15/18] Add tracking issue Signed-off-by: Miguel Ojeda --- library/core/src/option.rs | 2 +- library/core/src/result.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 9f89bfd674a74..14e4e4da3b96d 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -452,7 +452,7 @@ impl Option { /// ``` #[inline] #[track_caller] - #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")] pub unsafe fn unwrap_unchecked(self) -> T { debug_assert!(self.is_some()); match self { diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 436f4bf20c7e7..a43ba5882edcd 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -846,7 +846,7 @@ impl Result { /// ``` #[inline] #[track_caller] - #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")] pub unsafe fn unwrap_unchecked(self) -> T { debug_assert!(self.is_ok()); match self { @@ -880,7 +880,7 @@ impl Result { /// ``` #[inline] #[track_caller] - #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "none")] + #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")] pub unsafe fn unwrap_err_unchecked(self) -> E { debug_assert!(self.is_err()); match self { From 1c0a52d304cdebfcdf57c528b413457030659eb0 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Mon, 25 Jan 2021 11:00:02 -0800 Subject: [PATCH 16/18] rustdoc: Document CommonMark extensions. --- .../rustdoc/src/how-to-write-documentation.md | 66 ++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/doc/rustdoc/src/how-to-write-documentation.md b/src/doc/rustdoc/src/how-to-write-documentation.md index ca6db26da3130..41736e5ee3a7e 100644 --- a/src/doc/rustdoc/src/how-to-write-documentation.md +++ b/src/doc/rustdoc/src/how-to-write-documentation.md @@ -153,11 +153,73 @@ and finally provides a code example. ## Markdown -`rustdoc` uses the [commonmark markdown specification]. You might be +`rustdoc` uses the [CommonMark markdown specification]. You might be interested into taking a look at their website to see what's possible to do. - [commonmark quick reference] - [current spec] +In addition to the standard CommonMark syntax, `rustdoc` supports several +extensions: + +### Strikethrough + +Text may be rendered with a horizontal line through the center by wrapping the +text with two tilde characters on each side: + +```text +An example of ~~strikethrough text~~. +``` + +This example will render as: + +> An example of ~~strikethrough text~~. + +This follows the [GitHub Strikethrough extension][strikethrough]. + +### Footnotes + +A footnote generates a small numbered link in the text which when clicked +takes the reader to the footnote text at the bottom of the item. The footnote +label is written similarly to a link reference with a caret at the front. The +footnote text is written like a link reference definition, with the text +following the label. Example: + +```text +This is an example of a footnote[^note]. + +[^note]: This text is the contents of the footnote, which will be rendered + towards the bottom. +``` + +This example will render as: + +> This is an example of a footnote[^note]. +> +> [^note]: This text is the contents of the footnote, which will be rendered +> towards the bottom. + +The footnotes are automatically numbered based on the order the footnotes are +written. + +### Tables + +Tables can be written using pipes and dashes to draw the rows and columns of +the table. These will be translated to HTML table matching the shape. Example: + +```text +| Header1 | Header2 | +|---------|---------| +| abc | def | +``` + +This example will render similarly to this: + +> | Header1 | Header2 | +> |---------|---------| +> | abc | def | + +See the specification for the [GitHub Tables extension][tables] for more +details on the exact syntax supported. [`backtrace`]: https://docs.rs/backtrace/0.3.50/backtrace/ [commonmark markdown specification]: https://commonmark.org/ @@ -170,3 +232,5 @@ interested into taking a look at their website to see what's possible to do. [standard library]: https://doc.rust-lang.org/stable/std/index.html [current spec]: https://spec.commonmark.org/current/ [`std::env`]: https://doc.rust-lang.org/stable/std/env/index.html#functions +[strikethrough]: https://github.github.com/gfm/#strikethrough-extension- +[tables]: https://github.github.com/gfm/#tables-extension- From b8852d4dab8e6ea9d58cc142d96eb11c513cad4c Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 30 Nov 2020 08:39:08 -0800 Subject: [PATCH 17/18] rustc: Stabilize `-Zrun-dsymutil` as `-Csplit-debuginfo` This commit adds a new stable codegen option to rustc, `-Csplit-debuginfo`. The old `-Zrun-dsymutil` flag is deleted and now subsumed by this stable flag. Additionally `-Zsplit-dwarf` is also subsumed by this flag but still requires `-Zunstable-options` to actually activate. The `-Csplit-debuginfo` flag takes one of three values: * `off` - This indicates that split-debuginfo from the final artifact is not desired. This is not supported on Windows and is the default on Unix platforms except macOS. On macOS this means that `dsymutil` is not executed. * `packed` - This means that debuginfo is desired in one location separate from the main executable. This is the default on Windows (`*.pdb`) and macOS (`*.dSYM`). On other Unix platforms this subsumes `-Zsplit-dwarf=single` and produces a `*.dwp` file. * `unpacked` - This means that debuginfo will be roughly equivalent to object files, meaning that it's throughout the build directory rather than in one location (often the fastest for local development). This is not the default on any platform and is not supported on Windows. Each target can indicate its own default preference for how debuginfo is handled. Almost all platforms default to `off` except for Windows and macOS which default to `packed` for historical reasons. Some equivalencies for previous unstable flags with the new flags are: * `-Zrun-dsymutil=yes` -> `-Csplit-debuginfo=packed` * `-Zrun-dsymutil=no` -> `-Csplit-debuginfo=unpacked` * `-Zsplit-dwarf=single` -> `-Csplit-debuginfo=packed` * `-Zsplit-dwarf=split` -> `-Csplit-debuginfo=unpacked` Note that `-Csplit-debuginfo` still requires `-Zunstable-options` for non-macOS platforms since split-dwarf support was *just* implemented in rustc. There's some more rationale listed on #79361, but the main gist of the motivation for this commit is that `dsymutil` can take quite a long time to execute in debug builds and provides little benefit. This means that incremental compile times appear that much worse on macOS because the compiler is constantly running `dsymutil` over every single binary it produces during `cargo build` (even build scripts!). Ideally rustc would switch to not running `dsymutil` by default, but that's a problem left to get tackled another day. Closes #79361 --- compiler/rustc_codegen_llvm/src/back/lto.rs | 5 +- compiler/rustc_codegen_llvm/src/back/write.rs | 29 ++++--- .../src/debuginfo/metadata.rs | 11 ++- compiler/rustc_codegen_llvm/src/lib.rs | 7 +- compiler/rustc_codegen_ssa/src/back/link.rs | 84 +++++++++---------- compiler/rustc_codegen_ssa/src/back/write.rs | 20 ++++- compiler/rustc_interface/src/tests.rs | 4 +- compiler/rustc_session/src/config.rs | 45 +++++----- compiler/rustc_session/src/options.rs | 35 +++----- compiler/rustc_session/src/session.rs | 10 ++- compiler/rustc_target/src/spec/apple_base.rs | 6 +- compiler/rustc_target/src/spec/mod.rs | 82 ++++++++++++++++++ compiler/rustc_target/src/spec/msvc_base.rs | 6 +- src/bootstrap/builder.rs | 14 +++- src/doc/rustc/src/codegen-options/index.md | 30 ++++++- .../split-debuginfo/Makefile | 59 +++++++++++++ .../run-make-fulldeps/split-debuginfo/foo.rs | 1 + .../run-make-fulldeps/split-dwarf/Makefile | 2 +- src/test/ui/backtrace-apple-no-dsymutil.rs | 30 +++++++ src/tools/compiletest/src/runtest.rs | 4 +- src/tools/tidy/src/ui_tests.rs | 2 +- 21 files changed, 352 insertions(+), 134 deletions(-) create mode 100644 src/test/run-make-fulldeps/split-debuginfo/Makefile create mode 100644 src/test/run-make-fulldeps/split-debuginfo/foo.rs create mode 100644 src/test/ui/backtrace-apple-no-dsymutil.rs diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 29415973ed073..5effe68752808 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -732,10 +732,7 @@ pub unsafe fn optimize_thin_module( let diag_handler = cgcx.create_diag_handler(); let module_name = &thin_module.shared.module_names[thin_module.idx]; - let split_dwarf_file = cgcx - .output_filenames - .split_dwarf_filename(cgcx.split_dwarf_kind, Some(module_name.to_str().unwrap())); - let tm_factory_config = TargetMachineFactoryConfig { split_dwarf_file }; + let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap()); let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, &e))?; diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index e225730dce061..326ae354ccf48 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -23,13 +23,11 @@ use rustc_fs_util::{link_or_copy, path_to_c_string}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{ - self, Lto, OutputType, Passes, SanitizerSet, SplitDwarfKind, SwitchWithOptPath, -}; +use rustc_session::config::{self, Lto, OutputType, Passes, SanitizerSet, SwitchWithOptPath}; use rustc_session::Session; use rustc_span::symbol::sym; use rustc_span::InnerSpan; -use rustc_target::spec::{CodeModel, RelocModel}; +use rustc_target::spec::{CodeModel, RelocModel, SplitDebuginfo}; use tracing::debug; use libc::{c_char, c_int, c_uint, c_void, size_t}; @@ -93,9 +91,12 @@ pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm: } pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine { - let split_dwarf_file = tcx - .output_filenames(LOCAL_CRATE) - .split_dwarf_filename(tcx.sess.opts.debugging_opts.split_dwarf, Some(mod_name)); + let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() { + tcx.output_filenames(LOCAL_CRATE) + .split_dwarf_filename(tcx.sess.split_debuginfo(), Some(mod_name)) + } else { + None + }; let config = TargetMachineFactoryConfig { split_dwarf_file }; target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE))(config) .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise()) @@ -838,11 +839,17 @@ pub(crate) unsafe fn codegen( .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]); let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name); - let dwo_out = match cgcx.split_dwarf_kind { + let dwo_out = match cgcx.split_debuginfo { // Don't change how DWARF is emitted in single mode (or when disabled). - SplitDwarfKind::None | SplitDwarfKind::Single => None, + SplitDebuginfo::Off | SplitDebuginfo::Packed => None, // Emit (a subset of the) DWARF into a separate file in split mode. - SplitDwarfKind::Split => Some(dwo_out.as_path()), + SplitDebuginfo::Unpacked => { + if cgcx.target_can_use_split_dwarf { + Some(dwo_out.as_path()) + } else { + None + } + } }; with_codegen(tm, llmod, config.no_builtins, |cpm| { @@ -880,7 +887,7 @@ pub(crate) unsafe fn codegen( Ok(module.into_compiled_module( config.emit_obj != EmitObj::None, - cgcx.split_dwarf_kind == SplitDwarfKind::Split, + cgcx.target_can_use_split_dwarf && cgcx.split_debuginfo == SplitDebuginfo::Unpacked, config.emit_bc, &cgcx.output_filenames, )) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index b9ae796325023..ae629a3778e0f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -996,10 +996,13 @@ pub fn compile_unit_metadata( let flags = "\0"; let out_dir = &tcx.output_filenames(LOCAL_CRATE).out_directory; - let split_name = tcx - .output_filenames(LOCAL_CRATE) - .split_dwarf_filename(tcx.sess.opts.debugging_opts.split_dwarf, Some(codegen_unit_name)) - .unwrap_or_default(); + let split_name = if tcx.sess.target_can_use_split_dwarf() { + tcx.output_filenames(LOCAL_CRATE) + .split_dwarf_filename(tcx.sess.split_debuginfo(), Some(codegen_unit_name)) + } else { + None + } + .unwrap_or_default(); let out_dir = out_dir.to_str().unwrap(); let split_name = split_name.to_str().unwrap(); diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 92ac770aca554..d11c1592f99d1 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -351,12 +351,7 @@ impl ModuleLlvm { unsafe { let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names); let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?; - - let split_dwarf_file = cgcx - .output_filenames - .split_dwarf_filename(cgcx.split_dwarf_kind, Some(name.to_str().unwrap())); - let tm_factory_config = TargetMachineFactoryConfig { split_dwarf_file }; - + let tm_factory_config = TargetMachineFactoryConfig::new(&cgcx, name.to_str().unwrap()); let tm = match (cgcx.tm_factory)(tm_factory_config) { Ok(m) => m, Err(e) => { diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 72e049b6d7469..0738b2df71e0c 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -14,7 +14,7 @@ use rustc_session::utils::NativeLibKind; use rustc_session::{filesearch, Session}; use rustc_span::symbol::Symbol; use rustc_target::spec::crt_objects::{CrtObjects, CrtObjectsFallback}; -use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor}; +use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor, SplitDebuginfo}; use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target}; use super::archive::ArchiveBuilder; @@ -99,9 +99,6 @@ pub fn link_binary<'a, B: ArchiveBuilder<'a>>( path.as_ref(), target_cpu, ); - if sess.opts.debugging_opts.split_dwarf == config::SplitDwarfKind::Split { - link_dwarf_object(sess, &out_filename); - } } } if sess.opts.json_artifact_notifications { @@ -828,29 +825,43 @@ fn link_natively<'a, B: ArchiveBuilder<'a>>( } } - // On macOS, debuggers need this utility to get run to do some munging of - // the symbols. Note, though, that if the object files are being preserved - // for their debug information there's no need for us to run dsymutil. - if sess.target.is_like_osx - && sess.opts.debuginfo != DebugInfo::None - && !preserve_objects_for_their_debuginfo(sess) - { - let prog = Command::new("dsymutil").arg(out_filename).output(); - match prog { - Ok(prog) => { - if !prog.status.success() { - let mut output = prog.stderr.clone(); - output.extend_from_slice(&prog.stdout); - sess.struct_warn(&format!( - "processing debug info with `dsymutil` failed: {}", - prog.status - )) - .note(&escape_string(&output)) - .emit(); + match sess.split_debuginfo() { + // If split debug information is disabled or located in individual files + // there's nothing to do here. + SplitDebuginfo::Off | SplitDebuginfo::Unpacked => {} + + // If packed split-debuginfo is requested, but the final compilation + // doesn't actually have any debug information, then we skip this step. + SplitDebuginfo::Packed if sess.opts.debuginfo == DebugInfo::None => {} + + // On macOS the external `dsymutil` tool is used to create the packed + // debug information. Note that this will read debug information from + // the objects on the filesystem which we'll clean up later. + SplitDebuginfo::Packed if sess.target.is_like_osx => { + let prog = Command::new("dsymutil").arg(out_filename).output(); + match prog { + Ok(prog) => { + if !prog.status.success() { + let mut output = prog.stderr.clone(); + output.extend_from_slice(&prog.stdout); + sess.struct_warn(&format!( + "processing debug info with `dsymutil` failed: {}", + prog.status + )) + .note(&escape_string(&output)) + .emit(); + } } + Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)), } - Err(e) => sess.fatal(&format!("unable to run `dsymutil`: {}", e)), } + + // On MSVC packed debug information is produced by the linker itself so + // there's no need to do anything else here. + SplitDebuginfo::Packed if sess.target.is_like_msvc => {} + + // ... and otherwise we're processing a `*.dwp` packed dwarf file. + SplitDebuginfo::Packed => link_dwarf_object(sess, &out_filename), } } @@ -1050,28 +1061,9 @@ fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool { return false; } - // Single mode keeps debuginfo in the same object file, but in such a way that it it skipped - // by the linker - so it's expected that when codegen units are linked together that this - // debuginfo would be lost without keeping around the temps. - if sess.opts.debugging_opts.split_dwarf == config::SplitDwarfKind::Single { - return true; - } - - // If we're on OSX then the equivalent of split dwarf is turned on by - // default. The final executable won't actually have any debug information - // except it'll have pointers to elsewhere. Historically we've always run - // `dsymutil` to "link all the dwarf together" but this is actually sort of - // a bummer for incremental compilation! (the whole point of split dwarf is - // that you don't do this sort of dwarf link). - // - // Basically as a result this just means that if we're on OSX and we're - // *not* running dsymutil then the object files are the only source of truth - // for debug information, so we must preserve them. - if sess.target.is_like_osx { - return !sess.opts.debugging_opts.run_dsymutil; - } - - false + // "unpacked" split debuginfo means that we leave object files as the + // debuginfo is found in the original object files themselves + sess.split_debuginfo() == SplitDebuginfo::Unpacked } pub fn archive_search_paths(sess: &Session) -> Vec { diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index c84b87964b845..6aef5cb535a1f 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -282,6 +282,20 @@ pub struct TargetMachineFactoryConfig { pub split_dwarf_file: Option, } +impl TargetMachineFactoryConfig { + pub fn new( + cgcx: &CodegenContext, + module_name: &str, + ) -> TargetMachineFactoryConfig { + let split_dwarf_file = if cgcx.target_can_use_split_dwarf { + cgcx.output_filenames.split_dwarf_filename(cgcx.split_debuginfo, Some(module_name)) + } else { + None + }; + TargetMachineFactoryConfig { split_dwarf_file } + } +} + pub type TargetMachineFactoryFn = Arc< dyn Fn(TargetMachineFactoryConfig) -> Result<::TargetMachine, String> + Send @@ -311,10 +325,11 @@ pub struct CodegenContext { pub tm_factory: TargetMachineFactoryFn, pub msvc_imps_needed: bool, pub is_pe_coff: bool, + pub target_can_use_split_dwarf: bool, pub target_pointer_width: u32, pub target_arch: String, pub debuginfo: config::DebugInfo, - pub split_dwarf_kind: config::SplitDwarfKind, + pub split_debuginfo: rustc_target::spec::SplitDebuginfo, // Number of cgus excluding the allocator/metadata modules pub total_cgus: usize, @@ -1035,10 +1050,11 @@ fn start_executing_work( total_cgus, msvc_imps_needed: msvc_imps_needed(tcx), is_pe_coff: tcx.sess.target.is_like_windows, + target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(), target_pointer_width: tcx.sess.target.pointer_width, target_arch: tcx.sess.target.arch.clone(), debuginfo: tcx.sess.opts.debuginfo, - split_dwarf_kind: tcx.sess.opts.debugging_opts.split_dwarf, + split_debuginfo: tcx.sess.split_debuginfo(), }; // This is the "main loop" of parallel work happening for parallel codegen. diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 55d521a9b5ff5..305ae23669bbf 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -17,7 +17,7 @@ use rustc_span::edition::{Edition, DEFAULT_EDITION}; use rustc_span::symbol::sym; use rustc_span::SourceFileHashAlgorithm; use rustc_target::spec::{CodeModel, LinkerFlavor, MergeFunctions, PanicStrategy}; -use rustc_target::spec::{RelocModel, RelroLevel, TlsModel}; +use rustc_target::spec::{RelocModel, RelroLevel, SplitDebuginfo, TlsModel}; use std::collections::{BTreeMap, BTreeSet}; use std::iter::FromIterator; use std::path::PathBuf; @@ -446,6 +446,7 @@ fn test_codegen_options_tracking_hash() { tracked!(profile_use, Some(PathBuf::from("abc"))); tracked!(relocation_model, Some(RelocModel::Pic)); tracked!(soft_float, true); + tracked!(split_debuginfo, Some(SplitDebuginfo::Packed)); tracked!(target_cpu, Some(String::from("abc"))); tracked!(target_feature, String::from("all the features, all of them")); } @@ -579,7 +580,6 @@ fn test_debugging_options_tracking_hash() { tracked!(relax_elf_relocations, Some(true)); tracked!(relro_level, Some(RelroLevel::Full)); tracked!(report_delayed_bugs, true); - tracked!(run_dsymutil, false); tracked!(sanitizer, SanitizerSet::ADDRESS); tracked!(sanitizer_memory_track_origins, 2); tracked!(sanitizer_recover, SanitizerSet::ADDRESS); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 49833601c9e91..e381bfafda60a 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -13,7 +13,7 @@ use rustc_data_structures::impl_stable_hash_via_hash; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_target::abi::{Align, TargetDataLayout}; -use rustc_target::spec::{Target, TargetTriple}; +use rustc_target::spec::{SplitDebuginfo, Target, TargetTriple}; use crate::parse::CrateConfig; use rustc_feature::UnstableFeatures; @@ -221,23 +221,6 @@ pub enum DebugInfo { Full, } -/// Some debuginfo requires link-time relocation and some does not. LLVM can partition the debuginfo -/// into sections depending on whether or not it requires link-time relocation. Split DWARF -/// provides a mechanism which allows the linker to skip the sections which don't require link-time -/// relocation - either by putting those sections into DWARF object files, or keeping them in the -/// object file in such a way that the linker will skip them. -#[derive(Clone, Copy, Debug, PartialEq, Hash)] -pub enum SplitDwarfKind { - /// Disabled. - None, - /// Sections which do not require relocation are written into the object file but ignored - /// by the linker. - Single, - /// Sections which do not require relocation are written into a DWARF object (`.dwo`) file, - /// which is skipped by the linker by virtue of being a different file. - Split, -} - #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] #[derive(Encodable, Decodable)] pub enum OutputType { @@ -635,10 +618,10 @@ impl OutputFilenames { /// mode is being used, which is the logic that this function is intended to encapsulate. pub fn split_dwarf_filename( &self, - split_dwarf_kind: SplitDwarfKind, + split_debuginfo_kind: SplitDebuginfo, cgu_name: Option<&str>, ) -> Option { - self.split_dwarf_path(split_dwarf_kind, cgu_name) + self.split_dwarf_path(split_debuginfo_kind, cgu_name) .map(|path| path.strip_prefix(&self.out_directory).unwrap_or(&path).to_path_buf()) } @@ -646,19 +629,19 @@ impl OutputFilenames { /// mode is being used, which is the logic that this function is intended to encapsulate. pub fn split_dwarf_path( &self, - split_dwarf_kind: SplitDwarfKind, + split_debuginfo_kind: SplitDebuginfo, cgu_name: Option<&str>, ) -> Option { let obj_out = self.temp_path(OutputType::Object, cgu_name); let dwo_out = self.temp_path_dwo(cgu_name); - match split_dwarf_kind { - SplitDwarfKind::None => None, + match split_debuginfo_kind { + SplitDebuginfo::Off => None, // Single mode doesn't change how DWARF is emitted, but does add Split DWARF attributes // (pointing at the path which is being determined here). Use the path to the current // object file. - SplitDwarfKind::Single => Some(obj_out), + SplitDebuginfo::Packed => Some(obj_out), // Split mode emits the DWARF into a different file, use that path. - SplitDwarfKind::Split => Some(dwo_out), + SplitDebuginfo::Unpacked => Some(dwo_out), } } } @@ -1910,6 +1893,15 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { let pretty = parse_pretty(matches, &debugging_opts, error_format); + if !debugging_opts.unstable_options + && !target_triple.triple().contains("darwin") + && cg.split_debuginfo.is_some() + { + { + early_error(error_format, "`-Csplit-debuginfo` is unstable on this platform"); + } + } + Options { crate_types, optimize: opt_level, @@ -2191,7 +2183,7 @@ crate mod dep_tracking { use rustc_feature::UnstableFeatures; use rustc_span::edition::Edition; use rustc_target::spec::{CodeModel, MergeFunctions, PanicStrategy, RelocModel}; - use rustc_target::spec::{RelroLevel, TargetTriple, TlsModel}; + use rustc_target::spec::{RelroLevel, SplitDebuginfo, TargetTriple, TlsModel}; use std::collections::hash_map::DefaultHasher; use std::collections::BTreeMap; use std::hash::Hash; @@ -2263,6 +2255,7 @@ crate mod dep_tracking { impl_dep_tracking_hash_via_hash!(TargetTriple); impl_dep_tracking_hash_via_hash!(Edition); impl_dep_tracking_hash_via_hash!(LinkerPluginLto); + impl_dep_tracking_hash_via_hash!(Option); impl_dep_tracking_hash_via_hash!(SwitchWithOptPath); impl_dep_tracking_hash_via_hash!(Option); impl_dep_tracking_hash_via_hash!(Option); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 30af65e49a075..2aaab84585d07 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -6,7 +6,7 @@ use crate::search_paths::SearchPath; use crate::utils::NativeLibKind; use rustc_target::spec::{CodeModel, LinkerFlavor, MergeFunctions, PanicStrategy}; -use rustc_target::spec::{RelocModel, RelroLevel, TargetTriple, TlsModel}; +use rustc_target::spec::{RelocModel, RelroLevel, SplitDebuginfo, TargetTriple, TlsModel}; use rustc_feature::UnstableFeatures; use rustc_span::edition::Edition; @@ -269,7 +269,6 @@ macro_rules! options { pub const parse_switch_with_opt_path: &str = "an optional path to the profiling data output directory"; pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`"; - pub const parse_split_dwarf_kind: &str = "one of: `none`, `single` or `split`"; pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)"; pub const parse_src_file_hash: &str = "either `md5` or `sha1`"; pub const parse_relocation_model: &str = @@ -280,6 +279,8 @@ macro_rules! options { "one of supported TLS models (`rustc --print tls-models`)"; pub const parse_target_feature: &str = parse_string; pub const parse_wasi_exec_model: &str = "either `command` or `reactor`"; + pub const parse_split_debuginfo: &str = + "one of supported split-debuginfo modes (`off` or `dsymutil`)"; } #[allow(dead_code)] @@ -678,19 +679,6 @@ macro_rules! options { true } - fn parse_split_dwarf_kind( - slot: &mut SplitDwarfKind, - v: Option<&str>, - ) -> bool { - *slot = match v { - Some("none") => SplitDwarfKind::None, - Some("split") => SplitDwarfKind::Split, - Some("single") => SplitDwarfKind::Single, - _ => return false, - }; - true - } - fn parse_symbol_mangling_version( slot: &mut Option, v: Option<&str>, @@ -732,6 +720,14 @@ macro_rules! options { } true } + + fn parse_split_debuginfo(slot: &mut Option, v: Option<&str>) -> bool { + match v.and_then(|s| SplitDebuginfo::from_str(s).ok()) { + Some(e) => *slot = Some(e), + _ => return false, + } + true + } } ) } @@ -830,6 +826,8 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options, "save all temporary output files during compilation (default: no)"), soft_float: bool = (false, parse_bool, [TRACKED], "use soft float ABI (*eabihf targets only) (default: no)"), + split_debuginfo: Option = (None, parse_split_debuginfo, [TRACKED], + "how to handle split-debuginfo, a platform-specific option"), target_cpu: Option = (None, parse_opt_string, [TRACKED], "select target processor (`rustc --print target-cpus` for details)"), target_feature: String = (String::new(), parse_target_feature, [TRACKED], @@ -1073,11 +1071,6 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, "choose which RELRO level to use"), report_delayed_bugs: bool = (false, parse_bool, [TRACKED], "immediately print bugs registered with `delay_span_bug` (default: no)"), - // The default historical behavior was to always run dsymutil, so we're - // preserving that temporarily, but we're likely to switch the default - // soon. - run_dsymutil: bool = (true, parse_bool, [TRACKED], - "if on Mac, run `dsymutil` and delete intermediate object files (default: yes)"), sanitizer: SanitizerSet = (SanitizerSet::empty(), parse_sanitizers, [TRACKED], "use a sanitizer"), sanitizer_memory_track_origins: usize = (0, parse_sanitizer_memory_track_origins, [TRACKED], @@ -1112,8 +1105,6 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"), strip: Strip = (Strip::None, parse_strip, [UNTRACKED], "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"), - split_dwarf: SplitDwarfKind = (SplitDwarfKind::None, parse_split_dwarf_kind, [UNTRACKED], - "enable generation of split dwarf"), split_dwarf_inlining: bool = (true, parse_bool, [UNTRACKED], "provide minimal debug info in the object/executable to facilitate online \ symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF"), diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6d01854228662..dad21e59502de 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -28,7 +28,7 @@ use rustc_span::source_map::{FileLoader, MultiSpan, RealFileLoader, SourceMap, S use rustc_span::{sym, SourceFileHashAlgorithm, Symbol}; use rustc_target::asm::InlineAsmArch; use rustc_target::spec::{CodeModel, PanicStrategy, RelocModel, RelroLevel}; -use rustc_target::spec::{Target, TargetTriple, TlsModel}; +use rustc_target::spec::{SplitDebuginfo, Target, TargetTriple, TlsModel}; use std::cell::{self, RefCell}; use std::env; @@ -804,6 +804,14 @@ impl Session { ) } + pub fn split_debuginfo(&self) -> SplitDebuginfo { + self.opts.cg.split_debuginfo.unwrap_or(self.target.split_debuginfo) + } + + pub fn target_can_use_split_dwarf(&self) -> bool { + !self.target.is_like_windows && !self.target.is_like_osx + } + pub fn must_not_eliminate_frame_pointers(&self) -> bool { // "mcount" function relies on stack pointer. // See . diff --git a/compiler/rustc_target/src/spec/apple_base.rs b/compiler/rustc_target/src/spec/apple_base.rs index 8842239521643..3b458962b3d07 100644 --- a/compiler/rustc_target/src/spec/apple_base.rs +++ b/compiler/rustc_target/src/spec/apple_base.rs @@ -1,6 +1,6 @@ use std::env; -use crate::spec::{LinkArgs, TargetOptions}; +use crate::spec::{LinkArgs, SplitDebuginfo, TargetOptions}; pub fn opts(os: &str) -> TargetOptions { // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6 @@ -36,6 +36,10 @@ pub fn opts(os: &str) -> TargetOptions { emit_debug_gdb_scripts: false, eh_frame_header: false, + // The historical default for macOS targets is to run `dsymutil` which + // generates a packed version of debuginfo split from the main file. + split_debuginfo: SplitDebuginfo::Packed, + // This environment variable is pretty magical but is intended for // producing deterministic builds. This was first discovered to be used // by the `ar` tool as a way to control whether or not mtime entries in diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 90d35efaa25bd..0227febd294a0 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -448,6 +448,69 @@ impl fmt::Display for LinkOutputKind { pub type LinkArgs = BTreeMap>; +#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)] +pub enum SplitDebuginfo { + /// Split debug-information is disabled, meaning that on supported platforms + /// you can find all debug information in the executable itself. This is + /// only supported for ELF effectively. + /// + /// * Windows - not supported + /// * macOS - don't run `dsymutil` + /// * ELF - `.dwarf_*` sections + Off, + + /// Split debug-information can be found in a "packed" location separate + /// from the final artifact. This is supported on all platforms. + /// + /// * Windows - `*.pdb` + /// * macOS - `*.dSYM` (run `dsymutil`) + /// * ELF - `*.dwp` (run `rust-llvm-dwp`) + Packed, + + /// Split debug-information can be found in individual object files on the + /// filesystem. The main executable may point to the object files. + /// + /// * Windows - not supported + /// * macOS - supported, scattered object files + /// * ELF - supported, scattered `*.dwo` files + Unpacked, +} + +impl SplitDebuginfo { + fn as_str(&self) -> &'static str { + match self { + SplitDebuginfo::Off => "off", + SplitDebuginfo::Packed => "packed", + SplitDebuginfo::Unpacked => "unpacked", + } + } +} + +impl FromStr for SplitDebuginfo { + type Err = (); + + fn from_str(s: &str) -> Result { + Ok(match s { + "off" => SplitDebuginfo::Off, + "unpacked" => SplitDebuginfo::Unpacked, + "packed" => SplitDebuginfo::Packed, + _ => return Err(()), + }) + } +} + +impl ToJson for SplitDebuginfo { + fn to_json(&self) -> Json { + self.as_str().to_json() + } +} + +impl fmt::Display for SplitDebuginfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + macro_rules! supported_targets { ( $(($( $triple:literal, )+ $module:ident ),)+ ) => { $(mod $module;)+ @@ -1085,6 +1148,10 @@ pub struct TargetOptions { /// Is true if the target is an ARM architecture using thumb v1 which allows for /// thumb and arm interworking. pub has_thumb_interworking: bool, + + /// How to handle split debug information, if at all. Specifying `None` has + /// target-specific meaning. + pub split_debuginfo: SplitDebuginfo, } impl Default for TargetOptions { @@ -1184,6 +1251,7 @@ impl Default for TargetOptions { use_ctors_section: false, eh_frame_header: true, has_thumb_interworking: false, + split_debuginfo: SplitDebuginfo::Off, } } } @@ -1382,6 +1450,18 @@ impl Target { Some(Ok(())) })).unwrap_or(Ok(())) } ); + ($key_name:ident, SplitDebuginfo) => ( { + let name = (stringify!($key_name)).replace("_", "-"); + obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| { + match s.parse::() { + Ok(level) => base.$key_name = level, + _ => return Some(Err(format!("'{}' is not a valid value for \ + split-debuginfo. Use 'off' or 'dsymutil'.", + s))), + } + Some(Ok(())) + })).unwrap_or(Ok(())) + } ); ($key_name:ident, list) => ( { let name = (stringify!($key_name)).replace("_", "-"); if let Some(v) = obj.find(&name).and_then(Json::as_array) { @@ -1627,6 +1707,7 @@ impl Target { key!(use_ctors_section, bool); key!(eh_frame_header, bool); key!(has_thumb_interworking, bool); + key!(split_debuginfo, SplitDebuginfo)?; // NB: The old name is deprecated, but support for it is retained for // compatibility. @@ -1862,6 +1943,7 @@ impl ToJson for Target { target_option_val!(use_ctors_section); target_option_val!(eh_frame_header); target_option_val!(has_thumb_interworking); + target_option_val!(split_debuginfo); if default.unsupported_abis != self.unsupported_abis { d.insert( diff --git a/compiler/rustc_target/src/spec/msvc_base.rs b/compiler/rustc_target/src/spec/msvc_base.rs index 8cd6735a8c1ec..39c0d5f0bb4ff 100644 --- a/compiler/rustc_target/src/spec/msvc_base.rs +++ b/compiler/rustc_target/src/spec/msvc_base.rs @@ -1,4 +1,4 @@ -use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, TargetOptions}; +use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, SplitDebuginfo, TargetOptions}; pub fn opts() -> TargetOptions { let pre_link_args_msvc = vec![ @@ -27,6 +27,10 @@ pub fn opts() -> TargetOptions { abi_return_struct_as_int: true, emit_debug_gdb_scripts: false, + // Currently this is the only supported method of debuginfo on MSVC + // where `*.pdb` files show up next to the final artifact. + split_debuginfo: SplitDebuginfo::Packed, + ..Default::default() } } diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index 62065e27dd966..2f655e3b396f1 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -1139,10 +1139,18 @@ impl<'a> Builder<'a> { // itself, we skip it by default since we know it's safe to do so in that case. // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag. if target.contains("apple") { - if self.config.rust_run_dsymutil { - rustflags.arg("-Zrun-dsymutil=yes"); + if stage == 0 { + if self.config.rust_run_dsymutil { + rustflags.arg("-Zrun-dsymutil=yes"); + } else { + rustflags.arg("-Zrun-dsymutil=no"); + } } else { - rustflags.arg("-Zrun-dsymutil=no"); + if self.config.rust_run_dsymutil { + rustflags.arg("-Csplit-debuginfo=packed"); + } else { + rustflags.arg("-Csplit-debuginfo=unpacked"); + } } } diff --git a/src/doc/rustc/src/codegen-options/index.md b/src/doc/rustc/src/codegen-options/index.md index f6493e49c3c3e..51e7d987d9d82 100644 --- a/src/doc/rustc/src/codegen-options/index.md +++ b/src/doc/rustc/src/codegen-options/index.md @@ -492,6 +492,34 @@ point instructions in software. It takes one of the following values: * `y`, `yes`, `on`, or no value: use soft floats. * `n`, `no`, or `off`: use hardware floats (the default). +## split-debuginfo + +This option controls the emission of "split debuginfo" for debug information +that `rustc` generates. The default behavior of this option is +platform-specific, and not all possible values for this option work on all +platform. Possible values are: + +* `off` - This is the default for platforms with ELF binaries and windows-gnu + (not Windows MSVC and not macOS). This typically means that dwarf debug + information can be found in the final artifact in sections of the executable. + This option is not supported on Windows MSVC. On macOS this options prevents + the final execution of `dsymutil` to generate debuginfo. + +* `packed` - This is the default for Windows MSVC and macOS platforms. The term + "packed" here means that all the debug information is packed into a separate + file from the main executable. On Windows MSVC this is a `*.pdb` file, on + macOS this is a `*.dSYM` folder, and on other platforms this is a `*.dwp` + files. + +* `unpacked` - This means that debug information will be found in separate + files for each compilation unit (object file). This is not supported on + Windows MSVC. On macOS this means the original object files will contain + debug information. On other Unix platforms this means that `*.dwo` files will + contain debug information. + +Note that `packed` and `unpacked` gated behind `-Zunstable-options` on +non-macOS platforms at this time. + ## target-cpu This instructs `rustc` to generate code specifically for a particular processor. @@ -499,7 +527,7 @@ This instructs `rustc` to generate code specifically for a particular processor. You can run `rustc --print target-cpus` to see the valid options to pass here. Each target has a default base CPU. Special values include: -* `native` can be passed to use the processor of the host machine. +* `native` can be passed to use the processor of the host machine. * `generic` refers to an LLVM target with minimal features but modern tuning. ## target-feature diff --git a/src/test/run-make-fulldeps/split-debuginfo/Makefile b/src/test/run-make-fulldeps/split-debuginfo/Makefile new file mode 100644 index 0000000000000..e8e62efe01c14 --- /dev/null +++ b/src/test/run-make-fulldeps/split-debuginfo/Makefile @@ -0,0 +1,59 @@ +-include ../tools.mk + +all: off packed unpacked + +ifeq ($(UNAME),Darwin) +# If disabled, don't run dsymutil +off: + rm -rf $(TMPDIR)/*.dSYM + $(RUSTC) foo.rs -g -C split-debuginfo=off + [ ! -d $(TMPDIR)/foo.dSYM ] + +# Packed by default, but only if debuginfo is requested +packed: + rm -rf $(TMPDIR)/*.dSYM + $(RUSTC) foo.rs + [ ! -d $(TMPDIR)/foo.dSYM ] + rm -rf $(TMPDIR)/*.dSYM + $(RUSTC) foo.rs -g + [ -d $(TMPDIR)/foo.dSYM ] + rm -rf $(TMPDIR)/*.dSYM + $(RUSTC) foo.rs -g -C split-debuginfo=packed + [ -d $(TMPDIR)/foo.dSYM ] + rm -rf $(TMPDIR)/*.dSYM + +# Object files are preserved with unpacked and `dsymutil` isn't run +unpacked: + $(RUSTC) foo.rs -g -C split-debuginfo=unpacked + ls $(TMPDIR)/*.o + [ ! -d $(TMPDIR)/foo.dSYM ] +else +ifdef IS_WINDOWS +# Windows only supports =off +off: +packed: +unpacked: +else +# If disabled, don't run dsymutil +off: + $(RUSTC) foo.rs -g -C split-debuginfo=off -Z unstable-options + [ ! -f $(TMPDIR)/*.dwp ] + [ ! -f $(TMPDIR)/*.dwo ] + + $(RUSTC) foo.rs -g + [ ! -f $(TMPDIR)/*.dwp ] + [ ! -f $(TMPDIR)/*.dwo ] + +packed: + $(RUSTC) foo.rs -g -C split-debuginfo=packed -Z unstable-options + ls $(TMPDIR)/*.dwp + ls $(TMPDIR)/*.dwo && exit 1 || exit 0 + rm -rf $(TMPDIR)/*.dwp + +unpacked: + $(RUSTC) foo.rs -g -C split-debuginfo=unpacked -Z unstable-options + ls $(TMPDIR)/*.dwp && exit 1 || exit 0 + ls $(TMPDIR)/*.dwo + rm -rf $(TMPDIR)/*.dwo +endif +endif diff --git a/src/test/run-make-fulldeps/split-debuginfo/foo.rs b/src/test/run-make-fulldeps/split-debuginfo/foo.rs new file mode 100644 index 0000000000000..f328e4d9d04c3 --- /dev/null +++ b/src/test/run-make-fulldeps/split-debuginfo/foo.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/src/test/run-make-fulldeps/split-dwarf/Makefile b/src/test/run-make-fulldeps/split-dwarf/Makefile index e1a78e2edfc44..93dfc8e76a961 100644 --- a/src/test/run-make-fulldeps/split-dwarf/Makefile +++ b/src/test/run-make-fulldeps/split-dwarf/Makefile @@ -3,6 +3,6 @@ # only-linux all: - $(RUSTC) -Z split-dwarf=split foo.rs + $(RUSTC) -Z unstable-options -C split-debuginfo=packed foo.rs -g rm $(TMPDIR)/foo.dwp rm $(TMPDIR)/$(call BIN,foo) diff --git a/src/test/ui/backtrace-apple-no-dsymutil.rs b/src/test/ui/backtrace-apple-no-dsymutil.rs new file mode 100644 index 0000000000000..72a21faa4e7ea --- /dev/null +++ b/src/test/ui/backtrace-apple-no-dsymutil.rs @@ -0,0 +1,30 @@ +// run-pass + +// compile-flags:-g -Csplit-debuginfo=off +// only-macos + +#![feature(backtrace)] + +use std::process::Command; +use std::str; + +#[inline(never)] +fn main() { + let args: Vec = std::env::args().collect(); + if args.len() >= 2 { + println!("{}", std::backtrace::Backtrace::force_capture()); + return; + } + let out = Command::new(&args[0]).env("RUST_BACKTRACE", "1").arg("foo").output().unwrap(); + let output = format!( + "{}\n{}", + str::from_utf8(&out.stdout).unwrap(), + str::from_utf8(&out.stderr).unwrap(), + ); + if out.status.success() && output.contains(file!()) { + return; + } + println!("status: {}", out.status); + println!("child output:\n\t{}", output.replace("\n", "\n\t")); + panic!("failed to find {:?} in output", file!()); +} diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 5608ff98417cd..52aed57fc76af 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2015,10 +2015,10 @@ impl<'test> TestCx<'test> { rustc.args(&["-Zchalk"]); } Some(CompareMode::SplitDwarf) => { - rustc.args(&["-Zsplit-dwarf=split"]); + rustc.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]); } Some(CompareMode::SplitDwarfSingle) => { - rustc.args(&["-Zsplit-dwarf=single"]); + rustc.args(&["-Csplit-debuginfo=packed", "-Zunstable-options"]); } None => {} } diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index e687901f212b6..21d05226fb42c 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -7,7 +7,7 @@ use std::path::Path; const ENTRY_LIMIT: usize = 1000; // FIXME: The following limits should be reduced eventually. -const ROOT_ENTRY_LIMIT: usize = 1458; +const ROOT_ENTRY_LIMIT: usize = 1459; const ISSUES_ENTRY_LIMIT: usize = 2669; fn check_entries(path: &Path, bad: &mut bool) { From fdd592acd07265adc9fdb0e618b3c1fd481e8200 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Mon, 25 Jan 2021 15:10:10 -0800 Subject: [PATCH 18/18] Update books --- src/doc/book | 2 +- src/doc/nomicon | 2 +- src/doc/reference | 2 +- src/doc/rust-by-example | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/doc/book b/src/doc/book index ac57a0ddd23d1..e724bd826580f 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit ac57a0ddd23d173b26731ccf939f3ba729753275 +Subproject commit e724bd826580ff95df48a8533af7dec1080693d4 diff --git a/src/doc/nomicon b/src/doc/nomicon index a8584998eacde..bbf06ad39d1f4 160000 --- a/src/doc/nomicon +++ b/src/doc/nomicon @@ -1 +1 @@ -Subproject commit a8584998eacdea7106a1dfafcbf6c1c06fcdf925 +Subproject commit bbf06ad39d1f45654047e9596b750cc6e6d1b693 diff --git a/src/doc/reference b/src/doc/reference index 50af691f83893..f02b09eb6e8af 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit 50af691f838937c300b47812d0507c6d88c14f97 +Subproject commit f02b09eb6e8af340ad1256a54adb7aae2ff3163e diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example index 03e23af01f0b4..f633769acef68 160000 --- a/src/doc/rust-by-example +++ b/src/doc/rust-by-example @@ -1 +1 @@ -Subproject commit 03e23af01f0b4f83a3a513da280e1ca92587f2ec +Subproject commit f633769acef68574427a6fae6c06f13bc2199573