Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Rollup of 8 pull requests #61025

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a7e1431
Update boxed::Box docs on memory layout
blkerby May 19, 2019
178b753
Remove trailing whitespaces to satisfy tidy
blkerby May 19, 2019
d320c7c
Do not fail on child without DefId
estebank May 20, 2019
419ca9d
LocalDecl push returns Local len
spastorino May 20, 2019
4e37785
Create and reference Memory Layout section of boxed docs
blkerby May 21, 2019
e186d3f
Add stream_to_parser_with_base_dir
topecongiro May 21, 2019
5ea5fe3
static_assert: make use of anonymous constants
RalfJung May 21, 2019
b557567
Remove impls for `InternedString`/string equality.
nnethercote May 14, 2019
61735ab
adjust deprecation date of mem::uninitialized
RalfJung May 21, 2019
b07dbe1
Add doc comment
topecongiro May 21, 2019
1f1a917
Fix tidy: remove a trailing whitespace
topecongiro May 21, 2019
a2168b0
update doc comment
RalfJung May 21, 2019
a1f2dce
Move `edition` outside the hygiene lock and avoid accessing it
Zoxc Apr 5, 2019
0b37900
Specify the edition for the rustdoc thread-pool
Zoxc May 20, 2019
0efaeb2
Rollup merge of #59742 - Zoxc:edition-cleanup, r=petrochenkov
Centril May 22, 2019
3e23201
Rollup merge of #60963 - blkerby:boxed_docs, r=alexcrichton
Centril May 22, 2019
8041c3c
Rollup merge of #60982 - estebank:fix-60976, r=petrochenkov
Centril May 22, 2019
643db3a
Rollup merge of #60991 - spastorino:local-decls-push, r=oli-obk
Centril May 22, 2019
03712a8
Rollup merge of #60995 - topecongiro:parser-from-stream-and-base-dir,…
Centril May 22, 2019
9c784b3
Rollup merge of #60998 - RalfJung:static_assert, r=Centril
Centril May 22, 2019
4ab7a0e
Rollup merge of #61003 - nnethercote:rm-InternedString-PartialEq-impl…
Centril May 22, 2019
166542c
Rollup merge of #61006 - RalfJung:maybe-uninit, r=Centril
Centril May 22, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 64 additions & 25 deletions src/liballoc/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,6 @@
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
//! its allocation. It is valid to convert both ways between a [`Box`] and a
//! raw pointer allocated with the [`Global`] allocator, given that the
//! [`Layout`] used with the allocator is correct for the type. More precisely,
//! a `value: *mut T` that has been allocated with the [`Global`] allocator
//! with `Layout::for_value(&*value)` may be converted into a box using
//! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
//! [`Global`] allocator with `Layout::for_value(&*value)`.
//!
//! # Examples
//!
//! Move a value from the stack to the heap by creating a [`Box`]:
Expand Down Expand Up @@ -61,6 +51,19 @@
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
//! big `Cons` needs to be.
//!
//! # Memory layout
//!
//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
//! its allocation. It is valid to convert both ways between a [`Box`] and a
//! raw pointer allocated with the [`Global`] allocator, given that the
//! [`Layout`] used with the allocator is correct for the type. More precisely,
//! a `value: *mut T` that has been allocated with the [`Global`] allocator
//! with `Layout::for_value(&*value)` may be converted into a box using
//! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
//! [`Global`] allocator with `Layout::for_value(&*value)`.
//!
//!
//! [dereferencing]: ../../std/ops/trait.Deref.html
//! [`Box`]: struct.Box.html
//! [`Global`]: ../alloc/struct.Global.html
Expand Down Expand Up @@ -127,24 +130,38 @@ impl<T: ?Sized> Box<T> {
///
/// After calling this function, the raw pointer is owned by the
/// resulting `Box`. Specifically, the `Box` destructor will call
/// the destructor of `T` and free the allocated memory. Since the
/// way `Box` allocates and releases memory is unspecified, the
/// only valid pointer to pass to this function is the one taken
/// from another `Box` via the [`Box::into_raw`] function.
/// the destructor of `T` and free the allocated memory. For this
/// to be safe, the memory must have been allocated in accordance
/// with the [memory layout] used by `Box` .
///
/// # Safety
///
/// This function is unsafe because improper use may lead to
/// memory problems. For example, a double-free may occur if the
/// function is called twice on the same raw pointer.
///
/// [`Box::into_raw`]: struct.Box.html#method.into_raw
///
/// # Examples
///
/// Recreate a `Box` which was previously converted to a raw pointer
/// using [`Box::into_raw`]:
/// ```
/// let x = Box::new(5);
/// let ptr = Box::into_raw(x);
/// let x = unsafe { Box::from_raw(ptr) };
/// ```
/// Manually create a `Box` from scratch by using the global allocator:
/// ```
/// use std::alloc::{alloc, Layout};
///
/// unsafe {
/// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
/// *ptr = 5;
/// let x = Box::from_raw(ptr);
/// }
/// ```
///
/// [memory layout]: index.html#memory-layout
/// [`Layout`]: ../alloc/struct.Layout.html
/// [`Box::into_raw`]: struct.Box.html#method.into_raw
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
pub unsafe fn from_raw(raw: *mut T) -> Self {
Expand All @@ -157,22 +174,40 @@ impl<T: ?Sized> Box<T> {
///
/// After calling this function, the caller is responsible for the
/// memory previously managed by the `Box`. In particular, the
/// caller should properly destroy `T` and release the memory. The
/// proper way to do so is to convert the raw pointer back into a
/// `Box` with the [`Box::from_raw`] function.
/// caller should properly destroy `T` and release the memory, taking
/// into account the [memory layout] used by `Box`. The easiest way to
/// do this is to convert the raw pointer back into a `Box` with the
/// [`Box::from_raw`] function, allowing the `Box` destructor to perform
/// the cleanup.
///
/// Note: this is an associated function, which means that you have
/// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
/// is so that there is no conflict with a method on the inner type.
///
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
///
/// # Examples
///
/// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
/// for automatic cleanup:
/// ```
/// let x = Box::new(5);
/// let x = Box::new(String::from("Hello"));
/// let ptr = Box::into_raw(x);
/// let x = unsafe { Box::from_raw(ptr) };
/// ```
/// Manual cleanup by explicitly running the destructor and deallocating
/// the memory:
/// ```
/// use std::alloc::{dealloc, Layout};
/// use std::ptr;
///
/// let x = Box::new(String::from("Hello"));
/// let p = Box::into_raw(x);
/// unsafe {
/// ptr::drop_in_place(p);
/// dealloc(p as *mut u8, Layout::new::<String>());
/// }
/// ```
///
/// [memory layout]: index.html#memory-layout
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
#[stable(feature = "box_raw", since = "1.4.0")]
#[inline]
pub fn into_raw(b: Box<T>) -> *mut T {
Expand All @@ -184,7 +219,7 @@ impl<T: ?Sized> Box<T> {
/// After calling this function, the caller is responsible for the
/// memory previously managed by the `Box`. In particular, the
/// caller should properly destroy `T` and release the memory. The
/// proper way to do so is to convert the `NonNull<T>` pointer
/// easiest way to do so is to convert the `NonNull<T>` pointer
/// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
/// function.
///
Expand All @@ -203,6 +238,10 @@ impl<T: ?Sized> Box<T> {
/// fn main() {
/// let x = Box::new(5);
/// let ptr = Box::into_raw_non_null(x);
///
/// // Clean up the memory by converting the NonNull pointer back
/// // into a Box and letting the Box be dropped.
/// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
/// }
/// ```
#[unstable(feature = "box_into_raw_non_null", issue = "47336")]
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ pub unsafe fn zeroed<T>() -> T {
/// [`MaybeUninit<T>`]: union.MaybeUninit.html
/// [inv]: union.MaybeUninit.html#initialization-invariant
#[inline]
#[rustc_deprecated(since = "1.40.0", reason = "use `mem::MaybeUninit` instead")]
#[rustc_deprecated(since = "1.38.0", reason = "use `mem::MaybeUninit` instead")]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::panic_if_uninhabited::<T>();
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/intrinsicck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::ty::query::Providers;

use rustc_target::spec::abi::Abi::RustIntrinsic;
use rustc_data_structures::indexed_vec::Idx;
use syntax_pos::Span;
use syntax_pos::{Span, sym};
use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
use crate::hir;

Expand Down Expand Up @@ -69,7 +69,7 @@ fn unpack_option_like<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
impl<'a, 'tcx> ExprVisitor<'a, 'tcx> {
fn def_id_is_transmute(&self, def_id: DefId) -> bool {
self.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
self.tcx.item_name(def_id) == "transmute"
self.tcx.item_name(def_id) == sym::transmute
}

fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
Expand Down
12 changes: 6 additions & 6 deletions src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1853,7 +1853,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {

// Convert strings provided as --cfg [cfgspec] into a crate_cfg
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
syntax::with_globals(move || {
syntax::with_default_globals(move || {
let cfg = cfgspecs.into_iter().map(|s| {
let sess = parse::ParseSess::new(FilePathMapping::empty());
let filename = FileName::cfg_spec_source_code(&s);
Expand Down Expand Up @@ -2735,7 +2735,7 @@ mod tests {
// When the user supplies --test we should implicitly supply --cfg test
#[test]
fn test_switch_implies_cfg_test() {
syntax::with_globals(|| {
syntax::with_default_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string()]) {
Ok(m) => m,
Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
Expand All @@ -2753,7 +2753,7 @@ mod tests {
#[test]
fn test_switch_implies_cfg_test_unless_cfg_test() {
use syntax::symbol::sym;
syntax::with_globals(|| {
syntax::with_default_globals(|| {
let matches = &match optgroups().parse(&["--test".to_string(),
"--cfg=test".to_string()]) {
Ok(m) => m,
Expand All @@ -2771,15 +2771,15 @@ mod tests {

#[test]
fn test_can_print_warnings() {
syntax::with_globals(|| {
syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
assert!(!sess.diagnostic().flags.can_emit_warnings);
});

syntax::with_globals(|| {
syntax::with_default_globals(|| {
let matches = optgroups()
.parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
.unwrap();
Expand All @@ -2789,7 +2789,7 @@ mod tests {
assert!(sess.diagnostic().flags.can_emit_warnings);
});

syntax::with_globals(|| {
syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
Expand Down
10 changes: 5 additions & 5 deletions src/librustc/traits/on_unimplemented.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,15 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedFormatString {
// `{Self}` is allowed
Position::ArgumentNamed(s) if s == "Self" => (),
// `{ThisTraitsName}` is allowed
Position::ArgumentNamed(s) if s == name => (),
Position::ArgumentNamed(s) if s == name.as_str() => (),
// `{from_method}` is allowed
Position::ArgumentNamed(s) if s == "from_method" => (),
// `{from_desugaring}` is allowed
Position::ArgumentNamed(s) if s == "from_desugaring" => (),
// So is `{A}` if A is a type parameter
Position::ArgumentNamed(s) => match generics.params.iter().find(|param|
param.name == s
) {
Position::ArgumentNamed(s) => match generics.params.iter().find(|param| {
param.name.as_str() == s
}) {
Some(_) => (),
None => {
span_err!(tcx.sess, span, E0230,
Expand Down Expand Up @@ -301,7 +301,7 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedFormatString {
Piece::NextArgument(a) => match a.position {
Position::ArgumentNamed(s) => match generic_map.get(s) {
Some(val) => val,
None if s == name => {
None if s == name.as_str() => {
&trait_str
}
None => {
Expand Down
6 changes: 3 additions & 3 deletions src/librustc/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2981,9 +2981,9 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}
}

pub fn item_name(self, id: DefId) -> InternedString {
pub fn item_name(self, id: DefId) -> Symbol {
if id.index == CRATE_DEF_INDEX {
self.original_crate_name(id.krate).as_interned_str()
self.original_crate_name(id.krate)
} else {
let def_key = self.def_key(id);
match def_key.disambiguated_data.data {
Expand All @@ -2995,7 +2995,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}),
_ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
bug!("item_name: no name for {:?}", self.def_path(id));
}),
}).as_symbol(),
}
}
}
Expand Down
11 changes: 7 additions & 4 deletions src/librustc/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1140,14 +1140,16 @@ impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F>

match *region {
ty::ReEarlyBound(ref data) => {
data.name != "" && data.name != "'_"
data.name.as_symbol() != keywords::Invalid.name() &&
data.name.as_symbol() != keywords::UnderscoreLifetime.name()
}

ty::ReLateBound(_, br) |
ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
if let ty::BrNamed(_, name) = br {
if name != "" && name != "'_" {
if name.as_symbol() != keywords::Invalid.name() &&
name.as_symbol() != keywords::UnderscoreLifetime.name() {
return true;
}
}
Expand Down Expand Up @@ -1203,7 +1205,7 @@ impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
// `explain_region()` or `note_and_explain_region()`.
match *region {
ty::ReEarlyBound(ref data) => {
if data.name != "" {
if data.name.as_symbol() != keywords::Invalid.name() {
p!(write("{}", data.name));
return Ok(self);
}
Expand All @@ -1212,7 +1214,8 @@ impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
if let ty::BrNamed(_, name) = br {
if name != "" && name != "'_" {
if name.as_symbol() != keywords::Invalid.name() &&
name.as_symbol() != keywords::UnderscoreLifetime.name() {
p!(write("{}", name));
return Ok(self);
}
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_allocator/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use syntax::{
base::{ExtCtxt, Resolver},
build::AstBuilder,
expand::ExpansionConfig,
hygiene::{self, Mark, SyntaxContext},
hygiene::{Mark, SyntaxContext},
},
mut_visit::{self, MutVisitor},
parse::ParseSess,
Expand Down Expand Up @@ -96,7 +96,7 @@ impl MutVisitor for ExpandAllocatorDirectives<'_> {
].into()),
allow_internal_unsafe: false,
local_inner_macros: false,
edition: hygiene::default_edition(),
edition: self.sess.edition,
});

// Tie the span to the macro expansion info we just created
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_codegen_utils/symbol_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ fn compute_symbol_name(tcx: TyCtxt<'_, 'tcx, 'tcx>, instance: Instance<'tcx>) ->
return name.as_interned_str();
}
// Don't mangle foreign items.
return tcx.item_name(def_id);
return tcx.item_name(def_id).as_interned_str();
}

if let Some(name) = &attrs.export_name {
Expand All @@ -274,7 +274,7 @@ fn compute_symbol_name(tcx: TyCtxt<'_, 'tcx, 'tcx>, instance: Instance<'tcx>) ->

if attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE) {
// Don't mangle
return tcx.item_name(def_id);
return tcx.item_name(def_id).as_interned_str();
}

// We want to compute the "type" of this item. Unfortunately, some
Expand Down
9 changes: 4 additions & 5 deletions src/librustc_data_structures/macros.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
/// A simple static assertion macro. The first argument should be a unique
/// ALL_CAPS identifier that describes the condition.
/// A simple static assertion macro.
#[macro_export]
#[allow_internal_unstable(type_ascription)]
#[allow_internal_unstable(type_ascription, underscore_const_names)]
macro_rules! static_assert {
($name:ident: $test:expr) => {
($test:expr) => {
// Use the bool to access an array such that if the bool is false, the access
// is out-of-bounds.
#[allow(dead_code)]
static $name: () = [()][!($test: bool) as usize];
const _: () = [()][!($test: bool) as usize];
}
}

Expand Down
Loading