Skip to content

Commit

Permalink
Auto merge of #66485 - JohnTitor:rollup-vbwhg6r, r=JohnTitor
Browse files Browse the repository at this point in the history
Rollup of 11 pull requests

Successful merges:

 - #65739 (Improve documentation of `Vec::split_off(...)`)
 - #66271 (syntax: Keep string literals in ABIs and `asm!` more precisely)
 - #66344 (rustc_plugin: Remove `Registry::register_attribute`)
 - #66381 (find_deprecation: deprecation attr may be ill-formed meta.)
 - #66395 (Centralize panic macro documentation)
 - #66456 (Move `DIAGNOSTICS` usage to `rustc_driver`)
 - #66465 (add missing 'static lifetime in docs)
 - #66466 (miri panic_unwind: fix hack for SEH platforms)
 - #66469 (Use "field is never read" instead of "field is never used")
 - #66471 (Add test for issue 63116)
 - #66477 (Clarify transmute_copy documentation example)

Failed merges:

r? @ghost
  • Loading branch information
bors committed Nov 17, 2019
2 parents 2cdc289 + f65cb87 commit 8831d76
Show file tree
Hide file tree
Showing 63 changed files with 472 additions and 461 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3522,6 +3522,7 @@ dependencies = [
"rustc",
"rustc_codegen_utils",
"rustc_data_structures",
"rustc_error_codes",
"rustc_errors",
"rustc_interface",
"rustc_lint",
Expand Down Expand Up @@ -3595,7 +3596,6 @@ dependencies = [
"rustc_codegen_ssa",
"rustc_codegen_utils",
"rustc_data_structures",
"rustc_error_codes",
"rustc_errors",
"rustc_incremental",
"rustc_lint",
Expand Down
7 changes: 3 additions & 4 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1333,10 +1333,9 @@ impl<T> Vec<T> {

/// Splits the collection into two at the given index.
///
/// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
/// and the returned `Self` contains elements `[at, len)`.
///
/// Note that the capacity of `self` does not change.
/// Returns a newly allocated vector containing the elements in the range
/// `[at, len)`. After the call, the original vector will be left containing
/// the elements `[0, at)` with its previous capacity unchanged.
///
/// # Panics
///
Expand Down
4 changes: 1 addition & 3 deletions src/libcore/macros.rs → src/libcore/macros/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/// Panics the current thread.
///
/// For details, see `std::macros`.
#[doc(include = "panic.md")]
#[macro_export]
#[allow_internal_unstable(core_panic,
// FIXME(anp, eddyb) `core_intrinsics` is used here to allow calling
Expand Down
47 changes: 47 additions & 0 deletions src/libcore/macros/panic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
Panics the current thread.

This allows a program to terminate immediately and provide feedback
to the caller of the program. `panic!` should be used when a program reaches
an unrecoverable state.

This macro is the perfect way to assert conditions in example code and in
tests. `panic!` is closely tied with the `unwrap` method of both [`Option`]
and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set
to None or Err variants.

This macro is used to inject panic into a Rust thread, causing the thread to
panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
and the single-argument form of the `panic!` macro will be the value which
is transmitted.

[`Result`] enum is often a better solution for recovering from errors than
using the `panic!` macro. This macro should be used to avoid proceeding using
incorrect values, such as from external sources. Detailed information about
error handling is found in the [book].

The multi-argument form of this macro panics with a string and has the
[`format!`] syntax for building a string.

See also the macro [`compile_error!`], for raising errors during compilation.

[runwrap]: ../std/result/enum.Result.html#method.unwrap
[`Option`]: ../std/option/enum.Option.html#method.unwrap
[`Result`]: ../std/result/enum.Result.html
[`format!`]: ../std/macro.format.html
[`compile_error!`]: ../std/macro.compile_error.html
[book]: ../book/ch09-00-error-handling.html

# Current implementation

If the main thread panics it will terminate all your threads and end your
program with code `101`.

# Examples

```should_panic
# #![allow(unreachable_code)]
panic!();
panic!("this is a terrible mistake!");
panic!(4); // panic with the value of 4 to be collected elsewhere
panic!("this is a {} {message}", "fancy", message = "message");
```
10 changes: 5 additions & 5 deletions src/libcore/mem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,20 +744,20 @@ pub fn drop<T>(_x: T) { }
/// bar: u8,
/// }
///
/// let foo_slice = [10u8];
/// let foo_array = [10u8];
///
/// unsafe {
/// // Copy the data from 'foo_slice' and treat it as a 'Foo'
/// let mut foo_struct: Foo = mem::transmute_copy(&foo_slice);
/// // Copy the data from 'foo_array' and treat it as a 'Foo'
/// let mut foo_struct: Foo = mem::transmute_copy(&foo_array);
/// assert_eq!(foo_struct.bar, 10);
///
/// // Modify the copied data
/// foo_struct.bar = 20;
/// assert_eq!(foo_struct.bar, 20);
/// }
///
/// // The contents of 'foo_slice' should not have changed
/// assert_eq!(foo_slice, [10]);
/// // The contents of 'foo_array' should not have changed
/// assert_eq!(foo_array, [10]);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
5 changes: 0 additions & 5 deletions src/libpanic_unwind/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,6 @@ cfg_if::cfg_if! {
if #[cfg(miri)] {
#[path = "miri.rs"]
mod imp;
// On MSVC we need the SEH lang items as well...
// This should match the conditions of the `seh.rs` import below.
#[cfg(all(target_env = "msvc", not(target_arch = "aarch64")))]
#[allow(unused)]
mod seh;
} else if #[cfg(target_os = "emscripten")] {
#[path = "emcc.rs"]
mod imp;
Expand Down
21 changes: 20 additions & 1 deletion src/libpanic_unwind/miri.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(nonstandard_style)]

use core::any::Any;
use alloc::boxed::Box;

Expand All @@ -13,11 +15,28 @@ pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
Box::from_raw(ptr)
}


// This is required by the compiler to exist (e.g., it's a lang item),
// but is never used by Miri. Therefore, we just use a stub here
#[lang = "eh_personality"]
#[cfg(not(test))]
fn rust_eh_personality() {
unsafe { core::intrinsics::abort() }
}

// The rest is required on *some* targets to exist (specifically, MSVC targets that use SEH).
// We just add it on all targets. Copied from `seh.rs`.
#[repr(C)]
pub struct _TypeDescriptor {
pub pVFTable: *const u8,
pub spare: *mut u8,
pub name: [u8; 11],
}

const TYPE_NAME: [u8; 11] = *b"rust_panic\0";

#[cfg_attr(not(test), lang = "eh_catch_typeinfo")]
static mut TYPE_DESCRIPTOR: _TypeDescriptor = _TypeDescriptor {
pVFTable: core::ptr::null(),
spare: core::ptr::null_mut(),
name: TYPE_NAME,
};
6 changes: 1 addition & 5 deletions src/librustc/hir/def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ pub enum NonMacroAttrKind {
DeriveHelper,
/// Single-segment custom attribute registered with `#[register_attr]`.
Registered,
/// Single-segment custom attribute registered by a legacy plugin (`register_attribute`).
LegacyPluginHelper,
}

#[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, HashStable)]
Expand Down Expand Up @@ -330,7 +328,6 @@ impl NonMacroAttrKind {
NonMacroAttrKind::Tool => "tool attribute",
NonMacroAttrKind::DeriveHelper => "derive helper attribute",
NonMacroAttrKind::Registered => "explicitly registered attribute",
NonMacroAttrKind::LegacyPluginHelper => "legacy plugin helper attribute",
}
}

Expand All @@ -345,8 +342,7 @@ impl NonMacroAttrKind {
pub fn is_used(self) -> bool {
match self {
NonMacroAttrKind::Tool | NonMacroAttrKind::DeriveHelper => true,
NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered |
NonMacroAttrKind::LegacyPluginHelper => false,
NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false,
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1219,7 +1219,7 @@ impl<'a> LoweringContext<'a> {
ImplTraitContext::disallowed(),
),
unsafety: f.unsafety,
abi: this.lower_abi(f.abi),
abi: this.lower_extern(f.ext),
decl: this.lower_fn_decl(&f.decl, None, false, None),
param_names: this.lower_fn_params_to_names(&f.decl),
}))
Expand Down
18 changes: 13 additions & 5 deletions src/librustc/hir/lowering/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ impl LoweringContext<'_> {

fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod {
hir::ForeignMod {
abi: self.lower_abi(fm.abi),
abi: fm.abi.map_or(abi::Abi::C, |abi| self.lower_abi(abi)),
items: fm.items
.iter()
.map(|x| self.lower_foreign_item(x))
Expand Down Expand Up @@ -1283,18 +1283,26 @@ impl LoweringContext<'_> {
unsafety: h.unsafety,
asyncness: self.lower_asyncness(h.asyncness.node),
constness: h.constness.node,
abi: self.lower_abi(h.abi),
abi: self.lower_extern(h.ext),
}
}

pub(super) fn lower_abi(&mut self, abi: Abi) -> abi::Abi {
abi::lookup(&abi.symbol.as_str()).unwrap_or_else(|| {
pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
self.error_on_invalid_abi(abi);
abi::Abi::Rust
})
}

fn error_on_invalid_abi(&self, abi: Abi) {
pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
match ext {
Extern::None => abi::Abi::Rust,
Extern::Implicit => abi::Abi::C,
Extern::Explicit(abi) => self.lower_abi(abi),
}
}

fn error_on_invalid_abi(&self, abi: StrLit) {
struct_span_err!(
self.sess,
abi.span,
Expand Down
14 changes: 5 additions & 9 deletions src/librustc/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ use errors::emitter::{Emitter, EmitterWriter};
use errors::emitter::HumanReadableErrorType;
use errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
use syntax::edition::Edition;
use syntax::feature_gate::{self, AttributeType};
use syntax::feature_gate;
use errors::json::JsonEmitter;
use syntax::source_map;
use syntax::sess::{ParseSess, ProcessCfgMod};
use syntax::symbol::Symbol;
use syntax_pos::{MultiSpan, Span};

use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
Expand Down Expand Up @@ -79,7 +78,6 @@ pub struct Session {
/// in order to avoid redundantly verbose output (Issue #24690, #44953).
pub one_time_diagnostics: Lock<FxHashSet<(DiagnosticMessageId, Option<Span>, String)>>,
pub plugin_llvm_passes: OneThread<RefCell<Vec<String>>>,
pub plugin_attributes: Lock<Vec<(Symbol, AttributeType)>>,
pub crate_types: Once<Vec<config::CrateType>>,
/// The `crate_disambiguator` is constructed out of all the `-C metadata`
/// arguments passed to the compiler. Its value together with the crate-name
Expand Down Expand Up @@ -1039,12 +1037,11 @@ pub fn build_session_with_source_map(

let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;

let emitter = match diagnostics_output {
DiagnosticOutput::Default => default_emitter(&sopts, registry, &source_map, None),
DiagnosticOutput::Raw(write) => {
default_emitter(&sopts, registry, &source_map, Some(write))
}
let write_dest = match diagnostics_output {
DiagnosticOutput::Default => None,
DiagnosticOutput::Raw(write) => Some(write),
};
let emitter = default_emitter(&sopts, registry, &source_map, write_dest);

let diagnostic_handler = errors::Handler::with_emitter_and_flags(
emitter,
Expand Down Expand Up @@ -1166,7 +1163,6 @@ fn build_session_(
working_dir,
one_time_diagnostics: Default::default(),
plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
plugin_attributes: Lock::new(Vec::new()),
crate_types: Once::new(),
crate_disambiguator: Once::new(),
features: Once::new(),
Expand Down
1 change: 1 addition & 0 deletions src/librustc_driver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ rustc_plugin = { path = "../librustc_plugin/deprecated" } # To get this in the s
rustc_plugin_impl = { path = "../librustc_plugin" }
rustc_save_analysis = { path = "../librustc_save_analysis" }
rustc_codegen_utils = { path = "../librustc_codegen_utils" }
rustc_error_codes = { path = "../librustc_error_codes" }
rustc_interface = { path = "../librustc_interface" }
rustc_serialize = { path = "../libserialize", package = "serialize" }
rustc_resolve = { path = "../librustc_resolve" }
Expand Down
16 changes: 10 additions & 6 deletions src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use rustc::ty::TyCtxt;
use rustc::util::common::{set_time_depth, time, print_time_passes_entry, ErrorReported};
use rustc_metadata::locator;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use errors::PResult;
use errors::{PResult, registry::Registry};
use rustc_interface::interface;
use rustc_interface::util::get_codegen_sysroot;
use rustc_data_structures::sync::SeqCst;
Expand Down Expand Up @@ -140,6 +140,10 @@ impl Callbacks for TimePassesCallbacks {
}
}

pub fn diagnostics_registry() -> Registry {
Registry::new(&rustc_error_codes::DIAGNOSTICS)
}

// Parse args and run the compiler. This is the primary entry point for rustc.
// See comments on CompilerCalls below for details about the callbacks argument.
// The FileLoader provides a way to load files from sources other than the file system.
Expand Down Expand Up @@ -182,13 +186,14 @@ pub fn run_compiler(
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
registry: diagnostics_registry(),
};
callbacks.config(&mut config);
config
};

if let Some(ref code) = matches.opt_str("explain") {
handle_explain(code, sopts.error_format);
handle_explain(diagnostics_registry(), code, sopts.error_format);
return Ok(());
}

Expand Down Expand Up @@ -261,6 +266,7 @@ pub fn run_compiler(
lint_caps: Default::default(),
register_lints: None,
override_queries: None,
registry: diagnostics_registry(),
};

callbacks.config(&mut config);
Expand Down Expand Up @@ -510,15 +516,13 @@ fn stdout_isatty() -> bool {
}
}

fn handle_explain(code: &str,
output: ErrorOutputType) {
let descriptions = rustc_interface::util::diagnostics_registry();
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
let normalised = if code.starts_with("E") {
code.to_string()
} else {
format!("E{0:0>4}", code)
};
match descriptions.find_description(&normalised) {
match registry.find_description(&normalised) {
Some(ref description) => {
let mut is_in_code_block = false;
let mut text = String::new();
Expand Down
3 changes: 1 addition & 2 deletions src/librustc_error_codes/error_codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
// Error messages' format must follow the RFC 1567 available here:
// https://github.com/rust-lang/rfcs/pull/1567

crate::register_diagnostics! {

register_diagnostics! {
E0001: include_str!("./error_codes/E0001.md"),
E0002: include_str!("./error_codes/E0002.md"),
E0004: include_str!("./error_codes/E0004.md"),
Expand Down
11 changes: 3 additions & 8 deletions src/librustc_error_codes/lib.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
//! This library is used to gather all error codes into one place. The goal
//! being to make their maintenance easier.
//! This library is used to gather all error codes into one place,
//! the goal being to make their maintenance easier.
#[macro_export]
macro_rules! register_diagnostics {
($($ecode:ident: $message:expr,)*) => (
$crate::register_diagnostics!{$($ecode:$message,)* ;}
);

($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => (
pub static DIAGNOSTICS: &[(&str, &str)] = &[
$( (stringify!($ecode), $message), )*
];

$(
pub const $ecode: &str = $message;
pub const $ecode: () = ();
)*
$(
pub const $code: () = ();
Expand Down
1 change: 0 additions & 1 deletion src/librustc_interface/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ rustc_errors = { path = "../librustc_errors" }
rustc_plugin = { path = "../librustc_plugin", package = "rustc_plugin_impl" }
rustc_privacy = { path = "../librustc_privacy" }
rustc_resolve = { path = "../librustc_resolve" }
rustc_error_codes = { path = "../librustc_error_codes" }
tempfile = "3.0.5"
once_cell = "1"

Expand Down
Loading

0 comments on commit 8831d76

Please sign in to comment.