Skip to content

Commit dbfe70d

Browse files
committed
Auto merge of #61027 - Centril:rollup-oewauf1, r=Centril
Rollup of 10 pull requests Successful merges: - #59742 (Move `edition` outside the hygiene lock and avoid accessing it) - #60581 (convert custom try macro to `?`) - #60963 (Update boxed::Box docs on memory layout) - #60973 (Avoid symbol interning in `file_metadata`.) - #60982 (Do not fail on child without DefId) - #60991 (LocalDecl push returns Local len) - #60995 (Add stream_to_parser_with_base_dir) - #60998 (static_assert: make use of anonymous constants) - #61003 (Remove impls for `InternedString`/string equality.) - #61006 (adjust deprecation date of mem::uninitialized) Failed merges: r? @ghost
2 parents 119bbc2 + 2551a54 commit dbfe70d

File tree

60 files changed

+377
-346
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+377
-346
lines changed

src/liballoc/boxed.rs

+64-25
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,6 @@
44
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
55
//! drop their contents when they go out of scope.
66
//!
7-
//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
8-
//! its allocation. It is valid to convert both ways between a [`Box`] and a
9-
//! raw pointer allocated with the [`Global`] allocator, given that the
10-
//! [`Layout`] used with the allocator is correct for the type. More precisely,
11-
//! a `value: *mut T` that has been allocated with the [`Global`] allocator
12-
//! with `Layout::for_value(&*value)` may be converted into a box using
13-
//! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
14-
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
15-
//! [`Global`] allocator with `Layout::for_value(&*value)`.
16-
//!
177
//! # Examples
188
//!
199
//! Move a value from the stack to the heap by creating a [`Box`]:
@@ -61,6 +51,19 @@
6151
//! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
6252
//! big `Cons` needs to be.
6353
//!
54+
//! # Memory layout
55+
//!
56+
//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
57+
//! its allocation. It is valid to convert both ways between a [`Box`] and a
58+
//! raw pointer allocated with the [`Global`] allocator, given that the
59+
//! [`Layout`] used with the allocator is correct for the type. More precisely,
60+
//! a `value: *mut T` that has been allocated with the [`Global`] allocator
61+
//! with `Layout::for_value(&*value)` may be converted into a box using
62+
//! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
63+
//! T` obtained from `Box::<T>::into_raw` may be deallocated using the
64+
//! [`Global`] allocator with `Layout::for_value(&*value)`.
65+
//!
66+
//!
6467
//! [dereferencing]: ../../std/ops/trait.Deref.html
6568
//! [`Box`]: struct.Box.html
6669
//! [`Global`]: ../alloc/struct.Global.html
@@ -127,24 +130,38 @@ impl<T: ?Sized> Box<T> {
127130
///
128131
/// After calling this function, the raw pointer is owned by the
129132
/// resulting `Box`. Specifically, the `Box` destructor will call
130-
/// the destructor of `T` and free the allocated memory. Since the
131-
/// way `Box` allocates and releases memory is unspecified, the
132-
/// only valid pointer to pass to this function is the one taken
133-
/// from another `Box` via the [`Box::into_raw`] function.
133+
/// the destructor of `T` and free the allocated memory. For this
134+
/// to be safe, the memory must have been allocated in accordance
135+
/// with the [memory layout] used by `Box` .
136+
///
137+
/// # Safety
134138
///
135139
/// This function is unsafe because improper use may lead to
136140
/// memory problems. For example, a double-free may occur if the
137141
/// function is called twice on the same raw pointer.
138142
///
139-
/// [`Box::into_raw`]: struct.Box.html#method.into_raw
140-
///
141143
/// # Examples
142-
///
144+
/// Recreate a `Box` which was previously converted to a raw pointer
145+
/// using [`Box::into_raw`]:
143146
/// ```
144147
/// let x = Box::new(5);
145148
/// let ptr = Box::into_raw(x);
146149
/// let x = unsafe { Box::from_raw(ptr) };
147150
/// ```
151+
/// Manually create a `Box` from scratch by using the global allocator:
152+
/// ```
153+
/// use std::alloc::{alloc, Layout};
154+
///
155+
/// unsafe {
156+
/// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
157+
/// *ptr = 5;
158+
/// let x = Box::from_raw(ptr);
159+
/// }
160+
/// ```
161+
///
162+
/// [memory layout]: index.html#memory-layout
163+
/// [`Layout`]: ../alloc/struct.Layout.html
164+
/// [`Box::into_raw`]: struct.Box.html#method.into_raw
148165
#[stable(feature = "box_raw", since = "1.4.0")]
149166
#[inline]
150167
pub unsafe fn from_raw(raw: *mut T) -> Self {
@@ -157,22 +174,40 @@ impl<T: ?Sized> Box<T> {
157174
///
158175
/// After calling this function, the caller is responsible for the
159176
/// memory previously managed by the `Box`. In particular, the
160-
/// caller should properly destroy `T` and release the memory. The
161-
/// proper way to do so is to convert the raw pointer back into a
162-
/// `Box` with the [`Box::from_raw`] function.
177+
/// caller should properly destroy `T` and release the memory, taking
178+
/// into account the [memory layout] used by `Box`. The easiest way to
179+
/// do this is to convert the raw pointer back into a `Box` with the
180+
/// [`Box::from_raw`] function, allowing the `Box` destructor to perform
181+
/// the cleanup.
163182
///
164183
/// Note: this is an associated function, which means that you have
165184
/// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
166185
/// is so that there is no conflict with a method on the inner type.
167186
///
168-
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
169-
///
170187
/// # Examples
171-
///
188+
/// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
189+
/// for automatic cleanup:
172190
/// ```
173-
/// let x = Box::new(5);
191+
/// let x = Box::new(String::from("Hello"));
174192
/// let ptr = Box::into_raw(x);
193+
/// let x = unsafe { Box::from_raw(ptr) };
194+
/// ```
195+
/// Manual cleanup by explicitly running the destructor and deallocating
196+
/// the memory:
175197
/// ```
198+
/// use std::alloc::{dealloc, Layout};
199+
/// use std::ptr;
200+
///
201+
/// let x = Box::new(String::from("Hello"));
202+
/// let p = Box::into_raw(x);
203+
/// unsafe {
204+
/// ptr::drop_in_place(p);
205+
/// dealloc(p as *mut u8, Layout::new::<String>());
206+
/// }
207+
/// ```
208+
///
209+
/// [memory layout]: index.html#memory-layout
210+
/// [`Box::from_raw`]: struct.Box.html#method.from_raw
176211
#[stable(feature = "box_raw", since = "1.4.0")]
177212
#[inline]
178213
pub fn into_raw(b: Box<T>) -> *mut T {
@@ -184,7 +219,7 @@ impl<T: ?Sized> Box<T> {
184219
/// After calling this function, the caller is responsible for the
185220
/// memory previously managed by the `Box`. In particular, the
186221
/// caller should properly destroy `T` and release the memory. The
187-
/// proper way to do so is to convert the `NonNull<T>` pointer
222+
/// easiest way to do so is to convert the `NonNull<T>` pointer
188223
/// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
189224
/// function.
190225
///
@@ -203,6 +238,10 @@ impl<T: ?Sized> Box<T> {
203238
/// fn main() {
204239
/// let x = Box::new(5);
205240
/// let ptr = Box::into_raw_non_null(x);
241+
///
242+
/// // Clean up the memory by converting the NonNull pointer back
243+
/// // into a Box and letting the Box be dropped.
244+
/// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
206245
/// }
207246
/// ```
208247
#[unstable(feature = "box_into_raw_non_null", issue = "47336")]

src/libcore/mem.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ pub unsafe fn zeroed<T>() -> T {
466466
/// [`MaybeUninit<T>`]: union.MaybeUninit.html
467467
/// [inv]: union.MaybeUninit.html#initialization-invariant
468468
#[inline]
469-
#[rustc_deprecated(since = "1.40.0", reason = "use `mem::MaybeUninit` instead")]
469+
#[rustc_deprecated(since = "1.38.0", reason = "use `mem::MaybeUninit` instead")]
470470
#[stable(feature = "rust1", since = "1.0.0")]
471471
pub unsafe fn uninitialized<T>() -> T {
472472
intrinsics::panic_if_uninhabited::<T>();

src/librustc/middle/intrinsicck.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::ty::query::Providers;
66

77
use rustc_target::spec::abi::Abi::RustIntrinsic;
88
use rustc_data_structures::indexed_vec::Idx;
9-
use syntax_pos::Span;
9+
use syntax_pos::{Span, sym};
1010
use crate::hir::intravisit::{self, Visitor, NestedVisitorMap};
1111
use crate::hir;
1212

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

7575
fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {

src/librustc/session/config.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1853,7 +1853,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
18531853

18541854
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
18551855
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
1856-
syntax::with_globals(move || {
1856+
syntax::with_default_globals(move || {
18571857
let cfg = cfgspecs.into_iter().map(|s| {
18581858
let sess = parse::ParseSess::new(FilePathMapping::empty());
18591859
let filename = FileName::cfg_spec_source_code(&s);
@@ -2735,7 +2735,7 @@ mod tests {
27352735
// When the user supplies --test we should implicitly supply --cfg test
27362736
#[test]
27372737
fn test_switch_implies_cfg_test() {
2738-
syntax::with_globals(|| {
2738+
syntax::with_default_globals(|| {
27392739
let matches = &match optgroups().parse(&["--test".to_string()]) {
27402740
Ok(m) => m,
27412741
Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
@@ -2753,7 +2753,7 @@ mod tests {
27532753
#[test]
27542754
fn test_switch_implies_cfg_test_unless_cfg_test() {
27552755
use syntax::symbol::sym;
2756-
syntax::with_globals(|| {
2756+
syntax::with_default_globals(|| {
27572757
let matches = &match optgroups().parse(&["--test".to_string(),
27582758
"--cfg=test".to_string()]) {
27592759
Ok(m) => m,
@@ -2771,15 +2771,15 @@ mod tests {
27712771

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

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

2792-
syntax::with_globals(|| {
2792+
syntax::with_default_globals(|| {
27932793
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
27942794
let registry = errors::registry::Registry::new(&[]);
27952795
let (sessopts, _) = build_session_options_and_crate_config(&matches);

src/librustc/traits/on_unimplemented.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -243,15 +243,15 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedFormatString {
243243
// `{Self}` is allowed
244244
Position::ArgumentNamed(s) if s == "Self" => (),
245245
// `{ThisTraitsName}` is allowed
246-
Position::ArgumentNamed(s) if s == name => (),
246+
Position::ArgumentNamed(s) if s == name.as_str() => (),
247247
// `{from_method}` is allowed
248248
Position::ArgumentNamed(s) if s == "from_method" => (),
249249
// `{from_desugaring}` is allowed
250250
Position::ArgumentNamed(s) if s == "from_desugaring" => (),
251251
// So is `{A}` if A is a type parameter
252-
Position::ArgumentNamed(s) => match generics.params.iter().find(|param|
253-
param.name == s
254-
) {
252+
Position::ArgumentNamed(s) => match generics.params.iter().find(|param| {
253+
param.name.as_str() == s
254+
}) {
255255
Some(_) => (),
256256
None => {
257257
span_err!(tcx.sess, span, E0230,
@@ -301,7 +301,7 @@ impl<'a, 'gcx, 'tcx> OnUnimplementedFormatString {
301301
Piece::NextArgument(a) => match a.position {
302302
Position::ArgumentNamed(s) => match generic_map.get(s) {
303303
Some(val) => val,
304-
None if s == name => {
304+
None if s == name.as_str() => {
305305
&trait_str
306306
}
307307
None => {

src/librustc/ty/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2981,9 +2981,9 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
29812981
}
29822982
}
29832983

2984-
pub fn item_name(self, id: DefId) -> InternedString {
2984+
pub fn item_name(self, id: DefId) -> Symbol {
29852985
if id.index == CRATE_DEF_INDEX {
2986-
self.original_crate_name(id.krate).as_interned_str()
2986+
self.original_crate_name(id.krate)
29872987
} else {
29882988
let def_key = self.def_key(id);
29892989
match def_key.disambiguated_data.data {
@@ -2995,7 +2995,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
29952995
}),
29962996
_ => def_key.disambiguated_data.data.get_opt_name().unwrap_or_else(|| {
29972997
bug!("item_name: no name for {:?}", self.def_path(id));
2998-
}),
2998+
}).as_symbol(),
29992999
}
30003000
}
30013001
}

src/librustc/ty/print/pretty.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -1140,14 +1140,16 @@ impl<F: fmt::Write> PrettyPrinter<'gcx, 'tcx> for FmtPrinter<'_, 'gcx, 'tcx, F>
11401140

11411141
match *region {
11421142
ty::ReEarlyBound(ref data) => {
1143-
data.name != "" && data.name != "'_"
1143+
data.name.as_symbol() != keywords::Invalid.name() &&
1144+
data.name.as_symbol() != keywords::UnderscoreLifetime.name()
11441145
}
11451146

11461147
ty::ReLateBound(_, br) |
11471148
ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
11481149
ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
11491150
if let ty::BrNamed(_, name) = br {
1150-
if name != "" && name != "'_" {
1151+
if name.as_symbol() != keywords::Invalid.name() &&
1152+
name.as_symbol() != keywords::UnderscoreLifetime.name() {
11511153
return true;
11521154
}
11531155
}
@@ -1203,7 +1205,7 @@ impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
12031205
// `explain_region()` or `note_and_explain_region()`.
12041206
match *region {
12051207
ty::ReEarlyBound(ref data) => {
1206-
if data.name != "" {
1208+
if data.name.as_symbol() != keywords::Invalid.name() {
12071209
p!(write("{}", data.name));
12081210
return Ok(self);
12091211
}
@@ -1212,7 +1214,8 @@ impl<F: fmt::Write> FmtPrinter<'_, '_, '_, F> {
12121214
ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
12131215
ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
12141216
if let ty::BrNamed(_, name) = br {
1215-
if name != "" && name != "'_" {
1217+
if name.as_symbol() != keywords::Invalid.name() &&
1218+
name.as_symbol() != keywords::UnderscoreLifetime.name() {
12161219
p!(write("{}", name));
12171220
return Ok(self);
12181221
}

src/librustc_allocator/expand.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use syntax::{
1414
base::{ExtCtxt, Resolver},
1515
build::AstBuilder,
1616
expand::ExpansionConfig,
17-
hygiene::{self, Mark, SyntaxContext},
17+
hygiene::{Mark, SyntaxContext},
1818
},
1919
mut_visit::{self, MutVisitor},
2020
parse::ParseSess,
@@ -96,7 +96,7 @@ impl MutVisitor for ExpandAllocatorDirectives<'_> {
9696
].into()),
9797
allow_internal_unsafe: false,
9898
local_inner_macros: false,
99-
edition: hygiene::default_edition(),
99+
edition: self.sess.edition,
100100
});
101101

102102
// Tie the span to the macro expansion info we just created

0 commit comments

Comments
 (0)