Skip to content

Commit

Permalink
Auto merge of #122803 - jhpratt:rollup-nmgs79k, r=jhpratt
Browse files Browse the repository at this point in the history
Rollup of 8 pull requests

Successful merges:

 - #122545 (Ignore paths from expansion in `unused_qualifications`)
 - #122729 (Relax SeqCst ordering in standard library.)
 - #122740 (use more accurate terminology)
 - #122749 (make `type_flags(ReError) & HAS_ERROR`)
 - #122764 (coverage: Remove incorrect assertions from counter allocation)
 - #122765 (Add `usize::MAX` arg tests for Vec)
 - #122776 (Rename `hir::Let` into `hir::LetExpr`)
 - #122786 (compiletest: Introduce `remove_and_create_dir_all()` helper)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Mar 21, 2024
2 parents 6ec953c + f25397a commit 6a6cd65
Show file tree
Hide file tree
Showing 90 changed files with 410 additions and 759 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
hir::ExprKind::AddrOf(*k, *m, ohs)
}
ExprKind::Let(pat, scrutinee, span, is_recovered) => {
hir::ExprKind::Let(self.arena.alloc(hir::Let {
hir::ExprKind::Let(self.arena.alloc(hir::LetExpr {
span: self.lower_span(*span),
pat: self.lower_pat(pat),
ty: None,
Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_borrowck/src/region_infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,10 +434,6 @@ fn check_opaque_type_parameter_valid(
// Only check the parent generics, which will ignore any of the
// duplicated lifetime args that come from reifying late-bounds.
for (i, arg) in opaque_type_key.args.iter().take(parent_generics.count()).enumerate() {
if let Err(guar) = arg.error_reported() {
return Err(guar);
}

let arg_is_param = match arg.unpack() {
GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
GenericArgKind::Lifetime(lt) if is_ty_alias => {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,7 @@ pub struct Arm<'hir> {
/// In an `if let`, imagine it as `if (let <pat> = <expr>) { ... }`; in a let-else, it is part of
/// the desugaring to if-let. Only let-else supports the type annotation at present.
#[derive(Debug, Clone, Copy, HashStable_Generic)]
pub struct Let<'hir> {
pub struct LetExpr<'hir> {
pub span: Span,
pub pat: &'hir Pat<'hir>,
pub ty: Option<&'hir Ty<'hir>>,
Expand Down Expand Up @@ -1852,7 +1852,7 @@ pub enum ExprKind<'hir> {
///
/// These are not `Local` and only occur as expressions.
/// The `let Some(x) = foo()` in `if let Some(x) = foo()` is an example of `Let(..)`.
Let(&'hir Let<'hir>),
Let(&'hir LetExpr<'hir>),
/// An `if` block, with an optional else block.
///
/// I.e., `if <expr> { <expr> } else { <expr> }`.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/intravisit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>)
ExprKind::DropTemps(ref subexpression) => {
try_visit!(visitor.visit_expr(subexpression));
}
ExprKind::Let(Let { span: _, pat, ty, init, is_recovered: _ }) => {
ExprKind::Let(LetExpr { span: _, pat, ty, init, is_recovered: _ }) => {
// match the visit order in walk_local
try_visit!(visitor.visit_expr(init));
try_visit!(visitor.visit_pat(pat));
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1387,7 +1387,7 @@ impl<'a> State<'a> {
// Print `}`:
self.bclose_maybe_open(expr.span, true);
}
hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
hir::ExprKind::Let(&hir::LetExpr { pat, ty, init, .. }) => {
self.print_let(pat, ty, init);
}
hir::ExprKind::If(test, blk, elseopt) => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.note("`if` expressions without `else` evaluate to `()`");
err.help("consider adding an `else` block that evaluates to the expected type");
*error = true;
if let ExprKind::Let(hir::Let { span, pat, init, .. }) = cond_expr.kind
if let ExprKind::Let(hir::LetExpr { span, pat, init, .. }) = cond_expr.kind
&& let ExprKind::Block(block, _) = then_expr.kind
// Refutability checks occur on the MIR, so we approximate it here by checking
// if we have an enum with a single variant or a struct in the pattern.
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1261,7 +1261,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

pub(super) fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>, hir_id: HirId) -> Ty<'tcx> {
pub(super) fn check_expr_let(
&self,
let_expr: &'tcx hir::LetExpr<'tcx>,
hir_id: HirId,
) -> Ty<'tcx> {
// for let statements, this is done in check_stmt
let init = let_expr.init;
self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/expr_use_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
}
}

hir::ExprKind::Let(hir::Let { pat, init, .. }) => {
hir::ExprKind::Let(hir::LetExpr { pat, init, .. }) => {
self.walk_local(init, pat, None, |t| t.borrow_expr(init, ty::ImmBorrow))
}

Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_hir_typeck/src/gather_locals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl<'a> DeclOrigin<'a> {
}
}

/// A declaration is an abstraction of [hir::Local] and [hir::Let].
/// A declaration is an abstraction of [hir::Local] and [hir::LetExpr].
///
/// It must have a hir_id, as this is how we connect gather_locals to the check functions.
pub(super) struct Declaration<'a> {
Expand All @@ -48,9 +48,9 @@ impl<'a> From<&'a hir::Local<'a>> for Declaration<'a> {
}
}

impl<'a> From<(&'a hir::Let<'a>, hir::HirId)> for Declaration<'a> {
fn from((let_expr, hir_id): (&'a hir::Let<'a>, hir::HirId)) -> Self {
let hir::Let { pat, ty, span, init, is_recovered: _ } = *let_expr;
impl<'a> From<(&'a hir::LetExpr<'a>, hir::HirId)> for Declaration<'a> {
fn from((let_expr, hir_id): (&'a hir::LetExpr<'a>, hir::HirId)) -> Self {
let hir::LetExpr { pat, ty, span, init, is_recovered: _ } = *let_expr;
Declaration { hir_id, pat, ty, span, init: Some(init), origin: DeclOrigin::LetExpr }
}
}
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_infer/src/infer/opaque_types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,6 @@ impl<'tcx> InferCtxt<'tcx> {
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> InferResult<'tcx, ()> {
if a.references_error() || b.references_error() {
return Ok(InferOk { value: (), obligations: vec![] });
}
let process = |a: Ty<'tcx>, b: Ty<'tcx>| match *a.kind() {
ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) if def_id.is_local() => {
let def_id = def_id.expect_local();
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/ty/region.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ impl<'tcx> Region<'tcx> {
}
ty::ReError(_) => {
flags = flags | TypeFlags::HAS_FREE_REGIONS;
flags = flags | TypeFlags::HAS_ERROR;
}
}

Expand Down
39 changes: 4 additions & 35 deletions compiler/rustc_mir_transform/src/coverage/counters.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::fmt::{self, Debug};

use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::graph::WithNumNodes;
use rustc_index::bit_set::BitSet;
use rustc_index::IndexVec;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::coverage::{CounterId, CovTerm, Expression, ExpressionId, Op};

use super::graph::{BasicCoverageBlock, CoverageGraph, TraverseCoverageGraphWithLoops};

use std::fmt::{self, Debug};
use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph, TraverseCoverageGraphWithLoops};

/// The coverage counter or counter expression associated with a particular
/// BCB node or BCB edge.
Expand All @@ -18,10 +17,6 @@ pub(super) enum BcbCounter {
}

impl BcbCounter {
fn is_expression(&self) -> bool {
matches!(self, Self::Expression { .. })
}

pub(super) fn as_term(&self) -> CovTerm {
match *self {
BcbCounter::Counter { id, .. } => CovTerm::Counter(id),
Expand Down Expand Up @@ -60,10 +55,6 @@ pub(super) struct CoverageCounters {
/// We currently don't iterate over this map, but if we do in the future,
/// switch it back to `FxIndexMap` to avoid query stability hazards.
bcb_edge_counters: FxHashMap<(BasicCoverageBlock, BasicCoverageBlock), BcbCounter>,
/// Tracks which BCBs have a counter associated with some incoming edge.
/// Only used by assertions, to verify that BCBs with incoming edge
/// counters do not have their own physical counters (expressions are allowed).
bcb_has_incoming_edge_counters: BitSet<BasicCoverageBlock>,
/// Table of expression data, associating each expression ID with its
/// corresponding operator (+ or -) and its LHS/RHS operands.
expressions: IndexVec<ExpressionId, Expression>,
Expand All @@ -83,7 +74,6 @@ impl CoverageCounters {
counter_increment_sites: IndexVec::new(),
bcb_counters: IndexVec::from_elem_n(None, num_bcbs),
bcb_edge_counters: FxHashMap::default(),
bcb_has_incoming_edge_counters: BitSet::new_empty(num_bcbs),
expressions: IndexVec::new(),
};

Expand Down Expand Up @@ -122,14 +112,6 @@ impl CoverageCounters {
}

fn set_bcb_counter(&mut self, bcb: BasicCoverageBlock, counter_kind: BcbCounter) -> BcbCounter {
assert!(
// If the BCB has an edge counter (to be injected into a new `BasicBlock`), it can also
// have an expression (to be injected into an existing `BasicBlock` represented by this
// `BasicCoverageBlock`).
counter_kind.is_expression() || !self.bcb_has_incoming_edge_counters.contains(bcb),
"attempt to add a `Counter` to a BCB target with existing incoming edge counters"
);

if let Some(replaced) = self.bcb_counters[bcb].replace(counter_kind) {
bug!(
"attempt to set a BasicCoverageBlock coverage counter more than once; \
Expand All @@ -146,19 +128,6 @@ impl CoverageCounters {
to_bcb: BasicCoverageBlock,
counter_kind: BcbCounter,
) -> BcbCounter {
// If the BCB has an edge counter (to be injected into a new `BasicBlock`), it can also
// have an expression (to be injected into an existing `BasicBlock` represented by this
// `BasicCoverageBlock`).
if let Some(node_counter) = self.bcb_counter(to_bcb)
&& !node_counter.is_expression()
{
bug!(
"attempt to add an incoming edge counter from {from_bcb:?} \
when the target BCB already has {node_counter:?}"
);
}

self.bcb_has_incoming_edge_counters.insert(to_bcb);
if let Some(replaced) = self.bcb_edge_counters.insert((from_bcb, to_bcb), counter_kind) {
bug!(
"attempt to set an edge counter more than once; from_bcb: \
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4672,7 +4672,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
return;
}

if path.iter().any(|seg| seg.ident.span.from_expansion()) {
if finalize.path_span.from_expansion()
|| path.iter().any(|seg| seg.ident.span.from_expansion())
{
return;
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_type_ir/src/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ bitflags! {
| TypeFlags::HAS_TY_INHERENT.bits()
| TypeFlags::HAS_CT_PROJECTION.bits();

/// Is an error type/const reachable?
/// Is an error type/lifetime/const reachable?
const HAS_ERROR = 1 << 15;

/// Does this have any region that "appears free" in the type?
Expand Down
2 changes: 1 addition & 1 deletion config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -915,6 +915,6 @@
# Available options: fast, balanced, best
#compression-profile = "fast"

# Copy the linker, DLLs, and various libraries from MinGW into the rustc toolchain.
# Copy the linker, DLLs, and various libraries from MinGW into the Rust toolchain.
# Only applies when the host or target is pc-windows-gnu.
#include-mingw-linker = true
2 changes: 1 addition & 1 deletion library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ macro_rules! acquire {
/// let val = Arc::clone(&val);
///
/// thread::spawn(move || {
/// let v = val.fetch_add(1, Ordering::SeqCst);
/// let v = val.fetch_add(1, Ordering::Relaxed);
/// println!("{v:?}");
/// });
/// }
Expand Down
41 changes: 41 additions & 0 deletions library/alloc/tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2643,3 +2643,44 @@ fn test_vec_from_array_ref() {
fn test_vec_from_array_mut_ref() {
assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
}

/// This assortment of tests, in combination with miri, verifies we handle UB on fishy arguments
/// in the stdlib. Draining and extending the allocation are fairly well-tested earlier, but
/// `vec.insert(usize::MAX, val)` once slipped by!
///
/// All code that manipulates the collection types should be tested with "trivially wrong" args.
#[test]
fn max_dont_panic() {
let mut v = vec![0];
let _ = v.get(usize::MAX);
v.shrink_to(usize::MAX);
v.truncate(usize::MAX);
}

#[test]
#[should_panic]
fn max_insert() {
let mut v = vec![0];
v.insert(usize::MAX, 1);
}

#[test]
#[should_panic]
fn max_remove() {
let mut v = vec![0];
v.remove(usize::MAX);
}

#[test]
#[should_panic]
fn max_splice() {
let mut v = vec![0];
v.splice(usize::MAX.., core::iter::once(1));
}

#[test]
#[should_panic]
fn max_swap_remove() {
let mut v = vec![0];
v.swap_remove(usize::MAX);
}
9 changes: 3 additions & 6 deletions library/core/src/alloc/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ use crate::ptr;
/// use std::alloc::{GlobalAlloc, Layout};
/// use std::cell::UnsafeCell;
/// use std::ptr::null_mut;
/// use std::sync::atomic::{
/// AtomicUsize,
/// Ordering::{Acquire, SeqCst},
/// };
/// use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
///
/// const ARENA_SIZE: usize = 128 * 1024;
/// const MAX_SUPPORTED_ALIGN: usize = 4096;
Expand Down Expand Up @@ -61,7 +58,7 @@ use crate::ptr;
/// let mut allocated = 0;
/// if self
/// .remaining
/// .fetch_update(SeqCst, SeqCst, |mut remaining| {
/// .fetch_update(Relaxed, Relaxed, |mut remaining| {
/// if size > remaining {
/// return None;
/// }
Expand All @@ -81,7 +78,7 @@ use crate::ptr;
///
/// fn main() {
/// let _s = format!("allocating a string!");
/// let currently = ALLOCATOR.remaining.load(Acquire);
/// let currently = ALLOCATOR.remaining.load(Relaxed);
/// println!("allocated so far: {}", ARENA_SIZE - currently);
/// }
/// ```
Expand Down
2 changes: 1 addition & 1 deletion library/panic_unwind/src/emcc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
super::__rust_foreign_exception();
}

let was_caught = (*adjusted_ptr).caught.swap(true, Ordering::SeqCst);
let was_caught = (*adjusted_ptr).caught.swap(true, Ordering::Relaxed);
if was_caught {
// Since cleanup() isn't allowed to panic, we just abort instead.
intrinsics::abort();
Expand Down
4 changes: 2 additions & 2 deletions library/proc_macro/src/bridge/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ impl<T> OwnedStore<T> {
pub(super) fn new(counter: &'static AtomicU32) -> Self {
// Ensure the handle counter isn't 0, which would panic later,
// when `NonZero::new` (aka `Handle::new`) is called in `alloc`.
assert_ne!(counter.load(Ordering::SeqCst), 0);
assert_ne!(counter.load(Ordering::Relaxed), 0);

OwnedStore { counter, data: BTreeMap::new() }
}
}

impl<T> OwnedStore<T> {
pub(super) fn alloc(&mut self, x: T) -> Handle {
let counter = self.counter.fetch_add(1, Ordering::SeqCst);
let counter = self.counter.fetch_add(1, Ordering::Relaxed);
let handle = Handle::new(counter).expect("`proc_macro` handle counter overflowed");
assert!(self.data.insert(handle, x).is_none());
handle
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ static HOOK: AtomicPtr<()> = AtomicPtr::new(ptr::null_mut());
/// ```
#[unstable(feature = "alloc_error_hook", issue = "51245")]
pub fn set_alloc_error_hook(hook: fn(Layout)) {
HOOK.store(hook as *mut (), Ordering::SeqCst);
HOOK.store(hook as *mut (), Ordering::Release);
}

/// Unregisters the current allocation error hook, returning it.
Expand All @@ -339,7 +339,7 @@ pub fn set_alloc_error_hook(hook: fn(Layout)) {
/// If no custom hook is registered, the default hook will be returned.
#[unstable(feature = "alloc_error_hook", issue = "51245")]
pub fn take_alloc_error_hook() -> fn(Layout) {
let hook = HOOK.swap(ptr::null_mut(), Ordering::SeqCst);
let hook = HOOK.swap(ptr::null_mut(), Ordering::Acquire);
if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } }
}

Expand All @@ -362,7 +362,7 @@ fn default_alloc_error_hook(layout: Layout) {
#[alloc_error_handler]
#[unstable(feature = "alloc_internals", issue = "none")]
pub fn rust_oom(layout: Layout) -> ! {
let hook = HOOK.load(Ordering::SeqCst);
let hook = HOOK.load(Ordering::Acquire);
let hook: fn(Layout) =
if hook.is_null() { default_alloc_error_hook } else { unsafe { mem::transmute(hook) } };
hook(layout);
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/net/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ use crate::sync::atomic::{AtomicUsize, Ordering};
static PORT: AtomicUsize = AtomicUsize::new(0);

pub fn next_test_ip4() -> SocketAddr {
let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
let port = PORT.fetch_add(1, Ordering::Relaxed) as u16 + base_port();
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
}

pub fn next_test_ip6() -> SocketAddr {
let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();
let port = PORT.fetch_add(1, Ordering::Relaxed) as u16 + base_port();
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), port, 0, 0))
}

Expand Down
2 changes: 1 addition & 1 deletion library/std/src/panicking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ fn default_hook(info: &PanicInfo<'_>) {
drop(backtrace::print(err, crate::backtrace_rs::PrintFmt::Full))
}
Some(BacktraceStyle::Off) => {
if FIRST_PANIC.swap(false, Ordering::SeqCst) {
if FIRST_PANIC.swap(false, Ordering::Relaxed) {
let _ = writeln!(
err,
"note: run with `RUST_BACKTRACE=1` environment variable to display a \
Expand Down
Loading

0 comments on commit 6a6cd65

Please sign in to comment.