Skip to content

Commit d3c7934

Browse files
committed
Auto merge of #69590 - Dylan-DPC:rollup-i3z0sic, r=Dylan-DPC
Rollup of 7 pull requests Successful merges: - #69504 (Use assert_ne in hash tests) - #69571 (remove unneeded .as_ref() calls.) - #69572 (use .iter() instead of .into_iter() on references) - #69581 (fix aliasing violation in align_to_mut) - #69582 (improve transmute and Vec::from_raw_parts docs) - #69584 (Correct comment to match behavior) - #69587 (rustc_parse: Tweak the function parameter name check) Failed merges: r? @ghost
2 parents 4f0edbd + ad200af commit d3c7934

File tree

29 files changed

+65
-46
lines changed

29 files changed

+65
-46
lines changed

src/liballoc/vec.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,10 @@ impl<T> Vec<T> {
404404
///
405405
/// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
406406
/// (at least, it's highly likely to be incorrect if it wasn't).
407-
/// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
407+
/// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
408+
/// (`T` having a less strict alignment is not sufficient, the alignment really
409+
/// needs to be equal to satsify the [`dealloc`] requirement that memory must be
410+
/// allocated and deallocated with the same layout.)
408411
/// * `length` needs to be less than or equal to `capacity`.
409412
/// * `capacity` needs to be the capacity that the pointer was allocated with.
410413
///
@@ -423,6 +426,7 @@ impl<T> Vec<T> {
423426
/// function.
424427
///
425428
/// [`String`]: ../../std/string/struct.String.html
429+
/// [`dealloc`]: ../../alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
426430
///
427431
/// # Examples
428432
///

src/libcore/intrinsics.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -881,7 +881,8 @@ extern "rust-intrinsic" {
881881
/// // clone the vector as we will reuse them later
882882
/// let v_clone = v_orig.clone();
883883
///
884-
/// // Using transmute: this is Undefined Behavior, and a bad idea.
884+
/// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
885+
/// // bad idea and could cause Undefined Behavior.
885886
/// // However, it is no-copy.
886887
/// let v_transmuted = unsafe {
887888
/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
@@ -897,13 +898,14 @@ extern "rust-intrinsic" {
897898
///
898899
/// let v_clone = v_orig.clone();
899900
///
900-
/// // The no-copy, unsafe way, still using transmute, but not UB.
901-
/// // This is equivalent to the original, but safer, and reuses the
902-
/// // same `Vec` internals. Therefore, the new inner type must have the
903-
/// // exact same size, and the same alignment, as the old type.
901+
/// // The no-copy, unsafe way, still using transmute, but not relying on the data layout.
902+
/// // Like the first approach, this reuses the `Vec` internals.
903+
/// // Therefore, the new inner type must have the
904+
/// // exact same size, *and the same alignment*, as the old type.
904905
/// // The same caveats exist for this method as transmute, for
905906
/// // the original inner type (`&i32`) to the converted inner type
906-
/// // (`Option<&i32>`), so read the nomicon pages linked above.
907+
/// // (`Option<&i32>`), so read the nomicon pages linked above and also
908+
/// // consult the [`from_raw_parts`] documentation.
907909
/// let v_from_raw = unsafe {
908910
// FIXME Update this when vec_into_raw_parts is stabilized
909911
/// // Ensure the original vector is not dropped.
@@ -914,6 +916,8 @@ extern "rust-intrinsic" {
914916
/// };
915917
/// ```
916918
///
919+
/// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts
920+
///
917921
/// Implementing `split_at_mut`:
918922
///
919923
/// ```

src/libcore/slice/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -2571,11 +2571,13 @@ impl<T> [T] {
25712571
let (left, rest) = self.split_at_mut(offset);
25722572
// now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
25732573
let (us_len, ts_len) = rest.align_to_offsets::<U>();
2574+
let rest_len = rest.len();
25742575
let mut_ptr = rest.as_mut_ptr();
2576+
// We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
25752577
(
25762578
left,
25772579
from_raw_parts_mut(mut_ptr as *mut U, us_len),
2578-
from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len),
2580+
from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
25792581
)
25802582
}
25812583
}

src/libcore/tests/slice.rs

+12
Original file line numberDiff line numberDiff line change
@@ -1570,6 +1570,18 @@ fn test_align_to_empty_mid() {
15701570
}
15711571
}
15721572

1573+
#[test]
1574+
fn test_align_to_mut_aliasing() {
1575+
let mut val = [1u8, 2, 3, 4, 5];
1576+
// `align_to_mut` used to create `mid` in a way that there was some intermediate
1577+
// incorrect aliasing, invalidating the resulting `mid` slice.
1578+
let (begin, mid, end) = unsafe { val.align_to_mut::<[u8; 2]>() };
1579+
assert!(begin.len() == 0);
1580+
assert!(end.len() == 1);
1581+
mid[0] = mid[1];
1582+
assert_eq!(val, [3, 4, 3, 4, 5])
1583+
}
1584+
15731585
#[test]
15741586
fn test_slice_partition_dedup_by() {
15751587
let mut slice: [i32; 9] = [1, -1, 2, 3, 1, -5, 5, -2, 2];

src/librustc/ty/context.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2291,13 +2291,13 @@ impl<'tcx> TyCtxt<'tcx> {
22912291

22922292
#[inline]
22932293
pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> {
2294-
let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2294+
let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
22952295
self.mk_ty(Tuple(self.intern_substs(&kinds)))
22962296
}
22972297

22982298
pub fn mk_tup<I: InternAs<[Ty<'tcx>], Ty<'tcx>>>(self, iter: I) -> I::Output {
22992299
iter.intern_with(|ts| {
2300-
let kinds: Vec<_> = ts.into_iter().map(|&t| GenericArg::from(t)).collect();
2300+
let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect();
23012301
self.mk_ty(Tuple(self.intern_substs(&kinds)))
23022302
})
23032303
}

src/librustc_builtin_macros/proc_macro_harness.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ impl<'a> CollectProcMacros<'a> {
149149
.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
150150
&[]
151151
})
152-
.into_iter()
152+
.iter()
153153
.filter_map(|attr| {
154154
let attr = match attr.meta_item() {
155155
Some(meta_item) => meta_item,

src/librustc_infer/infer/canonical/query_response.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,7 @@ pub fn make_query_region_constraints<'tcx>(
630630
assert!(givens.is_empty());
631631

632632
let outlives: Vec<_> = constraints
633-
.into_iter()
633+
.iter()
634634
.map(|(k, _)| match *k {
635635
// Swap regions because we are going from sub (<=) to outlives
636636
// (>=).

src/librustc_infer/traits/on_unimplemented.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -237,10 +237,8 @@ impl<'tcx> OnUnimplementedDirective {
237237
}
238238
}
239239

240-
let options: FxHashMap<Symbol, String> = options
241-
.into_iter()
242-
.filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned())))
243-
.collect();
240+
let options: FxHashMap<Symbol, String> =
241+
options.iter().filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned()))).collect();
244242
OnUnimplementedNote {
245243
label: label.map(|l| l.format(tcx, trait_ref, &options)),
246244
message: message.map(|m| m.format(tcx, trait_ref, &options)),

src/librustc_infer/traits/select.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2411,7 +2411,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
24112411

24122412
types
24132413
.skip_binder()
2414-
.into_iter()
2414+
.iter()
24152415
.flat_map(|ty| {
24162416
// binder moved -\
24172417
let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/

src/librustc_lint/builtin.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,7 @@ impl EarlyLintPass for DeprecatedAttr {
739739
}
740740

741741
fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
742-
let mut attrs = attrs.into_iter().peekable();
742+
let mut attrs = attrs.iter().peekable();
743743

744744
// Accumulate a single span for sugared doc comments.
745745
let mut sugared_span: Option<Span> = None;

src/librustc_mir/borrow_check/diagnostics/move_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
519519
}
520520

521521
fn add_move_error_details(&self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local]) {
522-
for (j, local) in binds_to.into_iter().enumerate() {
522+
for (j, local) in binds_to.iter().enumerate() {
523523
let bind_to = &self.body.local_decls[*local];
524524
let binding_span = bind_to.source_info.span;
525525

src/librustc_mir/dataflow/generic/engine.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -419,7 +419,7 @@ impl RustcMirAttrs {
419419
let mut ret = RustcMirAttrs::default();
420420

421421
let rustc_mir_attrs = attrs
422-
.into_iter()
422+
.iter()
423423
.filter(|attr| attr.check_name(sym::rustc_mir))
424424
.flat_map(|attr| attr.meta_item_list().into_iter().flat_map(|v| v.into_iter()));
425425

src/librustc_mir/dataflow/impls/borrows.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ impl<'a, 'tcx> Borrows<'a, 'tcx> {
195195
.local_map
196196
.get(&place.local)
197197
.into_iter()
198-
.flat_map(|bs| bs.into_iter())
198+
.flat_map(|bs| bs.iter())
199199
.copied();
200200

201201
// If the borrowed place is a local with no projections, all other borrows of this

src/librustc_mir/interpret/operand.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
509509
&self,
510510
ops: &[mir::Operand<'tcx>],
511511
) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::PointerTag>>> {
512-
ops.into_iter().map(|op| self.eval_operand(op, None)).collect()
512+
ops.iter().map(|op| self.eval_operand(op, None)).collect()
513513
}
514514

515515
// Used when the miri-engine runs into a constant and for extracting information from constants

src/librustc_mir/monomorphize/collector.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -401,10 +401,8 @@ fn record_accesses<'tcx>(
401401
// We collect this into a `SmallVec` to avoid calling `is_inlining_candidate` in the lock.
402402
// FIXME: Call `is_inlining_candidate` when pushing to `neighbors` in `collect_items_rec`
403403
// instead to avoid creating this `SmallVec`.
404-
let accesses: SmallVec<[_; 128]> = callees
405-
.into_iter()
406-
.map(|mono_item| (*mono_item, is_inlining_candidate(mono_item)))
407-
.collect();
404+
let accesses: SmallVec<[_; 128]> =
405+
callees.iter().map(|mono_item| (*mono_item, is_inlining_candidate(mono_item))).collect();
408406

409407
inlining_map.lock_mut().record_accesses(caller, &accesses);
410408
}

src/librustc_mir/transform/check_unsafety.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,7 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
644644
}
645645
}
646646

647-
let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
647+
let mut unsafe_blocks: Vec<_> = unsafe_blocks.iter().collect();
648648
unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
649649
let used_unsafe: FxHashSet<_> =
650650
unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();

src/librustc_mir/transform/uninhabited_enum_branching.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching {
100100
&mut body.basic_blocks_mut()[bb].terminator_mut().kind
101101
{
102102
let vals = &*values;
103-
let zipped = vals.iter().zip(targets.into_iter());
103+
let zipped = vals.iter().zip(targets.iter());
104104

105105
let mut matched_values = Vec::with_capacity(allowed_variants.len());
106106
let mut matched_targets = Vec::with_capacity(allowed_variants.len() + 1);

src/librustc_parse/parser/item.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use crate::maybe_whole;
66

77
use rustc_ast_pretty::pprust;
88
use rustc_errors::{struct_span_err, Applicability, PResult, StashKey};
9+
use rustc_span::edition::Edition;
910
use rustc_span::source_map::{self, Span};
1011
use rustc_span::symbol::{kw, sym, Symbol};
1112
use syntax::ast::{self, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
@@ -636,7 +637,7 @@ impl<'a> Parser<'a> {
636637
}
637638

638639
pub fn parse_trait_item(&mut self) -> PResult<'a, Option<Option<P<AssocItem>>>> {
639-
self.parse_assoc_item(|t| t.span.rust_2018())
640+
self.parse_assoc_item(|edition| edition >= Edition::Edition2018)
640641
}
641642

642643
/// Parses associated items.
@@ -1380,7 +1381,7 @@ impl<'a> Parser<'a> {
13801381
/// The parsing configuration used to parse a parameter list (see `parse_fn_params`).
13811382
///
13821383
/// The function decides if, per-parameter `p`, `p` must have a pattern or just a type.
1383-
type ReqName = fn(&token::Token) -> bool;
1384+
type ReqName = fn(Edition) -> bool;
13841385

13851386
/// Parsing of functions and methods.
13861387
impl<'a> Parser<'a> {
@@ -1536,7 +1537,7 @@ impl<'a> Parser<'a> {
15361537

15371538
let is_name_required = match self.token.kind {
15381539
token::DotDotDot => false,
1539-
_ => req_name(&self.normalized_token),
1540+
_ => req_name(self.normalized_token.span.edition()),
15401541
};
15411542
let (pat, ty) = if is_name_required || self.is_named_param() {
15421543
debug!("parse_param_general parse_pat (is_name_required:{})", is_name_required);

src/librustc_privacy/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,7 @@ impl EmbargoVisitor<'tcx> {
657657
.map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id))
658658
{
659659
if let hir::ItemKind::Mod(m) = &item.kind {
660-
for item_id in m.item_ids.as_ref() {
660+
for item_id in m.item_ids {
661661
let item = self.tcx.hir().expect_item(item_id.id);
662662
let def_id = self.tcx.hir().local_def_id(item_id.id);
663663
if !self.tcx.hygienic_eq(segment.ident, item.ident, def_id) {

src/librustc_resolve/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1426,7 +1426,7 @@ crate fn show_candidates(
14261426
// we want consistent results across executions, but candidates are produced
14271427
// by iterating through a hash map, so make sure they are ordered:
14281428
let mut path_strings: Vec<_> =
1429-
candidates.into_iter().map(|c| path_names_to_string(&c.path)).collect();
1429+
candidates.iter().map(|c| path_names_to_string(&c.path)).collect();
14301430
path_strings.sort();
14311431
path_strings.dedup();
14321432

src/librustc_save_analysis/sig.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ impl Sig for ast::Item {
430430
sig.text.push_str(" = ");
431431
let ty = match ty {
432432
Some(ty) => ty.make(offset + sig.text.len(), id, scx)?,
433-
None => Err("Ty")?,
433+
None => return Err("Ty"),
434434
};
435435
sig.text.push_str(&ty.text);
436436
sig.text.push(';');

src/librustc_span/source_map.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ impl SourceMap {
395395
.unwrap_or_else(|x| x);
396396
let special_chars = end_width_idx - start_width_idx;
397397
let non_narrow: usize = f.non_narrow_chars[start_width_idx..end_width_idx]
398-
.into_iter()
398+
.iter()
399399
.map(|x| x.width())
400400
.sum();
401401
col.0 - special_chars + non_narrow
@@ -413,7 +413,7 @@ impl SourceMap {
413413
.binary_search_by_key(&pos, |x| x.pos())
414414
.unwrap_or_else(|x| x);
415415
let non_narrow: usize =
416-
f.non_narrow_chars[0..end_width_idx].into_iter().map(|x| x.width()).sum();
416+
f.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
417417
chpos.0 - end_width_idx + non_narrow
418418
};
419419
Loc { file: f, line: 0, col: chpos, col_display }

src/librustc_traits/lowering/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ fn program_clauses_for_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Clauses<'_> {
256256

257257
// `WellFormed(WC)`
258258
let wf_conditions = where_clauses
259-
.into_iter()
259+
.iter()
260260
.map(|wc| wc.subst(tcx, bound_vars))
261261
.map(|wc| wc.map_bound(|goal| goal.into_well_formed_goal()));
262262

src/librustc_typeck/collect/type_of.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
239239
.segments
240240
.iter()
241241
.filter_map(|seg| seg.args.as_ref())
242-
.map(|generic_args| generic_args.args.as_ref())
242+
.map(|generic_args| generic_args.args)
243243
.find_map(|args| {
244244
args.iter()
245245
.filter(|arg| arg.is_const())

src/librustdoc/clean/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -2388,9 +2388,9 @@ impl Clean<TypeBindingKind> for hir::TypeBindingKind<'_> {
23882388
hir::TypeBindingKind::Equality { ref ty } => {
23892389
TypeBindingKind::Equality { ty: ty.clean(cx) }
23902390
}
2391-
hir::TypeBindingKind::Constraint { ref bounds } => TypeBindingKind::Constraint {
2392-
bounds: bounds.into_iter().map(|b| b.clean(cx)).collect(),
2393-
},
2391+
hir::TypeBindingKind::Constraint { ref bounds } => {
2392+
TypeBindingKind::Constraint { bounds: bounds.iter().map(|b| b.clean(cx)).collect() }
2393+
}
23942394
}
23952395
}
23962396
}

src/librustdoc/html/markdown.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ impl Markdown<'_> {
738738
return String::new();
739739
}
740740
let replacer = |_: &str, s: &str| {
741-
if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
741+
if let Some(&(_, ref replace)) = links.iter().find(|link| &*link.0 == s) {
742742
Some((replace.clone(), s.to_owned()))
743743
} else {
744744
None
@@ -816,7 +816,7 @@ impl MarkdownSummaryLine<'_> {
816816
}
817817

818818
let replacer = |_: &str, s: &str| {
819-
if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
819+
if let Some(&(_, ref replace)) = links.iter().find(|link| &*link.0 == s) {
820820
Some((replace.clone(), s.to_owned()))
821821
} else {
822822
None

src/librustdoc/html/render/cache.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option
670670
match *clean_type {
671671
clean::ResolvedPath { ref path, .. } => {
672672
let segments = &path.segments;
673-
let path_segment = segments.into_iter().last().unwrap_or_else(|| panic!(
673+
let path_segment = segments.iter().last().unwrap_or_else(|| panic!(
674674
"get_index_type_name(clean_type: {:?}, accept_generic: {:?}) had length zero path",
675675
clean_type, accept_generic
676676
));

src/libstd/path.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2011,7 +2011,7 @@ impl Path {
20112011
#[stable(feature = "rust1", since = "1.0.0")]
20122012
pub fn file_name(&self) -> Option<&OsStr> {
20132013
self.components().next_back().and_then(|p| match p {
2014-
Component::Normal(p) => Some(p.as_ref()),
2014+
Component::Normal(p) => Some(p),
20152015
_ => None,
20162016
})
20172017
}

src/libstd/time.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ impl Instant {
284284
}
285285

286286
/// Returns the amount of time elapsed from another instant to this one,
287-
/// or zero duration if that instant is earlier than this one.
287+
/// or zero duration if that instant is later than this one.
288288
///
289289
/// # Examples
290290
///

0 commit comments

Comments
 (0)