Skip to content

Commit

Permalink
Auto merge of #111671 - Dylan-DPC:rollup-1jy5r16, r=Dylan-DPC
Browse files Browse the repository at this point in the history
Rollup of 6 pull requests

Successful merges:

 - #110145 (Share slice of bytes)
 - #111043 (Stabilize feature `cstr_is_empty`)
 - #111648 (Remove `LangItems::require`)
 - #111649 (Add derive for `core::marker::ConstParamTy`)
 - #111654 (Add a conversion from `&mut T` to `&mut UnsafeCell<T>`)
 - #111661 (Erase regions of type in `offset_of!`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed May 17, 2023
2 parents 6c64870 + 0720743 commit c2ccc85
Show file tree
Hide file tree
Showing 34 changed files with 232 additions and 83 deletions.
23 changes: 23 additions & 0 deletions compiler/rustc_builtin_macros/src/deriving/bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,26 @@ pub fn expand_deriving_copy(

trait_def.expand(cx, mitem, item, push);
}

pub fn expand_deriving_const_param_ty(
cx: &mut ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
is_const: bool,
) {
let trait_def = TraitDef {
span,
path: path_std!(marker::ConstParamTy),
skip_path_as_bound: false,
needs_copy_as_bound_if_packed: false,
additional_bounds: Vec::new(),
supports_unions: false,
methods: Vec::new(),
associated_types: Vec::new(),
is_const,
};

trait_def.expand(cx, mitem, item, push);
}
1 change: 1 addition & 0 deletions compiler/rustc_builtin_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
register_derive! {
Clone: clone::expand_deriving_clone,
Copy: bounds::expand_deriving_copy,
ConstParamTy: bounds::expand_deriving_const_param_ty,
Debug: debug::expand_deriving_debug,
Default: default::expand_deriving_default,
Eq: eq::expand_deriving_eq,
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_codegen_cranelift/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -966,11 +966,7 @@ fn codegen_panic_inner<'tcx>(
args: &[Value],
span: Span,
) {
let def_id = fx
.tcx
.lang_items()
.require(lang_item)
.unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
let def_id = fx.tcx.require_lang_item(lang_item, Some(span));

let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
let symbol_name = fx.tcx.symbol_name(instance).name;
Expand Down
9 changes: 4 additions & 5 deletions compiler/rustc_codegen_ssa/src/back/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ use snap::write::FrameEncoder;

use object::elf::NT_GNU_PROPERTY_TYPE_0;
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::owned_slice::try_slice_owned;
use rustc_data_structures::sync::MetadataRef;
use rustc_data_structures::owned_slice::{try_slice_owned, OwnedSlice};
use rustc_metadata::fs::METADATA_FILENAME;
use rustc_metadata::EncodedMetadata;
use rustc_session::cstore::MetadataLoader;
Expand All @@ -39,7 +38,7 @@ pub struct DefaultMetadataLoader;
fn load_metadata_with(
path: &Path,
f: impl for<'a> FnOnce(&'a [u8]) -> Result<&'a [u8], String>,
) -> Result<MetadataRef, String> {
) -> Result<OwnedSlice, String> {
let file =
File::open(path).map_err(|e| format!("failed to open file '{}': {}", path.display(), e))?;

Expand All @@ -49,7 +48,7 @@ fn load_metadata_with(
}

impl MetadataLoader for DefaultMetadataLoader {
fn get_rlib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
fn get_rlib_metadata(&self, _target: &Target, path: &Path) -> Result<OwnedSlice, String> {
load_metadata_with(path, |data| {
let archive = object::read::archive::ArchiveFile::parse(&*data)
.map_err(|e| format!("failed to parse rlib '{}': {}", path.display(), e))?;
Expand All @@ -69,7 +68,7 @@ impl MetadataLoader for DefaultMetadataLoader {
})
}

fn get_dylib_metadata(&self, _target: &Target, path: &Path) -> Result<MetadataRef, String> {
fn get_dylib_metadata(&self, _target: &Target, path: &Path) -> Result<OwnedSlice, String> {
load_metadata_with(path, |data| search_for_section(path, data, ".rustc"))
}
}
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_codegen_ssa/src/traits/backend.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use std::any::Any;

use super::write::WriteBackendMethods;
use super::CodegenObject;
use crate::back::write::TargetMachineFactoryFn;
use crate::{CodegenResults, ModuleCodegen};

use rustc_ast::expand::allocator::AllocatorKind;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_errors::ErrorGuaranteed;
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
Expand All @@ -20,11 +23,6 @@ use rustc_span::symbol::Symbol;
use rustc_target::abi::call::FnAbi;
use rustc_target::spec::Target;

pub use rustc_data_structures::sync::MetadataRef;

use rustc_data_structures::sync::{DynSend, DynSync};
use std::any::Any;

pub trait BackendTypes {
type Value: CodegenObject;
type Function: CodegenObject;
Expand Down
43 changes: 36 additions & 7 deletions compiler/rustc_data_structures/src/owned_slice.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use std::{borrow::Borrow, ops::Deref};

use crate::sync::Lrc;
// Use our fake Send/Sync traits when on not parallel compiler,
// so that `OwnedSlice` only implements/requires Send/Sync
// for parallel compiler builds.
use crate::sync::{Send, Sync};

/// An owned slice.
///
/// This is similar to `Box<[u8]>` but allows slicing and using anything as the
/// This is similar to `Lrc<[u8]>` but allows slicing and using anything as the
/// backing buffer.
///
/// See [`slice_owned`] for `OwnedSlice` construction and examples.
Expand All @@ -16,6 +17,7 @@ use crate::sync::{Send, Sync};
///
/// This is essentially a replacement for `owning_ref` which is a lot simpler
/// and even sound! 🌸
#[derive(Clone)]
pub struct OwnedSlice {
/// This is conceptually a `&'self.owner [u8]`.
bytes: *const [u8],
Expand All @@ -31,7 +33,7 @@ pub struct OwnedSlice {
// \/
// ⊂(´・◡・⊂ )∘˚˳° (I am the phantom remnant of #97770)
#[expect(dead_code)]
owner: Box<dyn Send + Sync>,
owner: Lrc<dyn Send + Sync>,
}

/// Makes an [`OwnedSlice`] out of an `owner` and a `slicer` function.
Expand Down Expand Up @@ -72,23 +74,50 @@ where
O: Send + Sync + 'static,
F: FnOnce(&O) -> Result<&[u8], E>,
{
// We box the owner of the bytes, so it doesn't move.
// We wrap the owner of the bytes in, so it doesn't move.
//
// Since the owner does not move and we don't access it in any way
// before drop, there is nothing that can invalidate the bytes pointer.
// before dropping, there is nothing that can invalidate the bytes pointer.
//
// Thus, "extending" the lifetime of the reference returned from `F` is fine.
// We pretend that we pass it a reference that lives as long as the returned slice.
//
// N.B. the HRTB on the `slicer` is important — without it the caller could provide
// a short lived slice, unrelated to the owner.

let owner = Box::new(owner);
let owner = Lrc::new(owner);
let bytes = slicer(&*owner)?;

Ok(OwnedSlice { bytes, owner })
}

impl OwnedSlice {
/// Slice this slice by `slicer`.
///
/// # Examples
///
/// ```rust
/// # use rustc_data_structures::owned_slice::{OwnedSlice, slice_owned};
/// let vec = vec![1, 2, 3, 4];
///
/// // Identical to slicing via `&v[1..3]` but produces an owned slice
/// let slice: OwnedSlice = slice_owned(vec, |v| &v[..]);
/// assert_eq!(&*slice, [1, 2, 3, 4]);
///
/// let slice = slice.slice(|slice| &slice[1..][..2]);
/// assert_eq!(&*slice, [2, 3]);
/// ```
///
pub fn slice(self, slicer: impl FnOnce(&[u8]) -> &[u8]) -> OwnedSlice {
// This is basically identical to `try_slice_owned`,
// `slicer` can only return slices of its argument or some static data,
// both of which are valid while `owner` is alive.

let bytes = slicer(&self);
OwnedSlice { bytes, ..self }
}
}

impl Deref for OwnedSlice {
type Target = [u8];

Expand All @@ -108,11 +137,11 @@ impl Borrow<[u8]> for OwnedSlice {
}
}

// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Box<dyn Send + Sync>)`, which is `Send`
// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Arc<dyn Send + Sync>)`, which is `Send`
#[cfg(parallel_compiler)]
unsafe impl Send for OwnedSlice {}

// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Box<dyn Send + Sync>)`, which is `Sync`
// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Arc<dyn Send + Sync>)`, which is `Sync`
#[cfg(parallel_compiler)]
unsafe impl Sync for OwnedSlice {}

Expand Down
12 changes: 11 additions & 1 deletion compiler/rustc_data_structures/src/owned_slice/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fn static_storage() {
}

#[test]
fn slice_the_slice() {
fn slice_owned_the_slice() {
let slice = slice_owned(vec![1, 2, 3, 4, 5, 6], Vec::as_slice);
let slice = slice_owned(slice, |s| &s[1..][..4]);
let slice = slice_owned(slice, |s| s);
Expand All @@ -35,6 +35,16 @@ fn slice_the_slice() {
assert_eq!(&*slice, &[1, 2, 3, 4, 5, 6][1..][..4][1..]);
}

#[test]
fn slice_the_slice() {
let slice = slice_owned(vec![1, 2, 3, 4, 5, 6], Vec::as_slice)
.slice(|s| &s[1..][..4])
.slice(|s| s)
.slice(|s| &s[1..]);

assert_eq!(&*slice, &[1, 2, 3, 4, 5, 6][1..][..4][1..]);
}

#[test]
fn try_and_fail() {
let res = try_slice_owned(vec![0], |v| v.get(12..).ok_or(()));
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_data_structures/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
//! [^2] `MTLockRef` is a typedef.

pub use crate::marker::*;
use crate::owned_slice::OwnedSlice;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
use std::ops::{Deref, DerefMut};
Expand Down Expand Up @@ -92,6 +91,7 @@ mod mode {
}

pub use mode::{is_dyn_thread_safe, set_dyn_thread_safe_mode};

cfg_if! {
if #[cfg(not(parallel_compiler))] {
pub unsafe auto trait Send {}
Expand Down Expand Up @@ -244,8 +244,6 @@ cfg_if! {
r
}

pub type MetadataRef = OwnedSlice;

pub use std::rc::Rc as Lrc;
pub use std::rc::Weak as Weak;
pub use std::cell::Ref as ReadGuard;
Expand Down Expand Up @@ -517,8 +515,6 @@ cfg_if! {
}
}

pub type MetadataRef = OwnedSlice;

/// This makes locks panic if they are already held.
/// It is only useful when you are running in a single thread
const ERROR_CHECKING: bool = false;
Expand Down
10 changes: 0 additions & 10 deletions compiler/rustc_hir/src/errors.rs

This file was deleted.

8 changes: 0 additions & 8 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
//! * Functions called by the compiler itself.

use crate::def_id::DefId;
use crate::errors::LangItemError;
use crate::{MethodKind, Target};

use rustc_ast as ast;
Expand Down Expand Up @@ -42,13 +41,6 @@ impl LanguageItems {
self.items[item as usize] = Some(def_id);
}

/// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
/// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
/// returns an error encapsulating the `LangItem`.
pub fn require(&self, it: LangItem) -> Result<DefId, LangItemError> {
self.get(it).ok_or_else(|| LangItemError(it))
}

pub fn iter(&self) -> impl Iterator<Item = (LangItem, DefId)> + '_ {
self.items
.iter()
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ pub mod def;
pub mod def_path_hash_map;
pub mod definitions;
pub mod diagnostic_items;
pub mod errors;
pub use rustc_span::def_id;
mod hir;
pub mod hir_id;
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_hir_analysis/src/coherence/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe

let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, Some(span));

let unsize_trait = tcx.lang_items().require(LangItem::Unsize).unwrap_or_else(|err| {
tcx.sess.fatal(format!("`CoerceUnsized` implementation {}", err.to_string()));
});
let unsize_trait = tcx.require_lang_item(LangItem::Unsize, Some(span));

let source = tcx.type_of(impl_did).subst_identity();
let trait_ref = tcx.impl_trait_ref(impl_did).unwrap().subst_identity();
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_metadata/src/locator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::owned_slice::slice_owned;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::MetadataRef;
use rustc_errors::{DiagnosticArgValue, FatalError, IntoDiagnosticArg};
use rustc_fs_util::try_canonicalize;
use rustc_session::config::{self, CrateType};
Expand Down Expand Up @@ -782,7 +781,7 @@ fn get_metadata_section<'p>(
if !filename.exists() {
return Err(MetadataError::NotPresent(filename));
}
let raw_bytes: MetadataRef = match flavor {
let raw_bytes = match flavor {
CrateFlavor::Rlib => {
loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)?
}
Expand Down Expand Up @@ -843,7 +842,7 @@ fn get_metadata_section<'p>(
slice_owned(mmap, Deref::deref)
}
};
let blob = MetadataBlob::new(raw_bytes);
let blob = MetadataBlob(raw_bytes);
if blob.is_compatible() {
Ok(blob)
} else {
Expand Down
7 changes: 2 additions & 5 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::rmeta::*;
use rustc_ast as ast;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::owned_slice::OwnedSlice;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc, OnceCell};
use rustc_data_structures::unhash::UnhashMap;
Expand Down Expand Up @@ -50,7 +51,7 @@ mod cstore_impl;
/// A `MetadataBlob` internally is just a reference counted pointer to
/// the actual data, so cloning it is cheap.
#[derive(Clone)]
pub(crate) struct MetadataBlob(Lrc<MetadataRef>);
pub(crate) struct MetadataBlob(pub(crate) OwnedSlice);

impl std::ops::Deref for MetadataBlob {
type Target = [u8];
Expand Down Expand Up @@ -660,10 +661,6 @@ impl<'a, 'tcx, I: Idx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyTable<I, T>
implement_ty_decoder!(DecodeContext<'a, 'tcx>);

impl MetadataBlob {
pub(crate) fn new(metadata_ref: MetadataRef) -> MetadataBlob {
MetadataBlob(Lrc::new(metadata_ref))
}

pub(crate) fn is_compatible(&self) -> bool {
self.blob().starts_with(METADATA_HEADER)
}
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::rmeta::DecodeContext;
use crate::rmeta::EncodeContext;
use rustc_data_structures::owned_slice::slice_owned;
use rustc_data_structures::owned_slice::OwnedSlice;
use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap};
use rustc_middle::parameterized_over_tcx;
Expand Down Expand Up @@ -47,7 +46,7 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static>
fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefPathHashMapRef<'static> {
let len = d.read_usize();
let pos = d.position();
let o = slice_owned(d.blob().clone(), |blob| &blob[pos..pos + len]);
let o = d.blob().clone().0.slice(|blob| &blob[pos..pos + len]);

// Although we already have the data we need via the `OwnedSlice`, we still need
// to advance the `DecodeContext`'s position so it's in a valid state after
Expand Down
Loading

0 comments on commit c2ccc85

Please sign in to comment.