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

Move str to libcore. #70911

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion src/liballoc/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,8 @@ impl ToOwned for str {
}

/// Methods for string slices.
#[lang = "str_alloc"]
#[cfg_attr(bootstrap, lang = "str_alloc")]
#[cfg_attr(not(bootstrap), lang = "str_alloc_impl")]
#[cfg(not(test))]
impl str {
/// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
Expand Down
18 changes: 17 additions & 1 deletion src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,21 @@ pub mod pattern;
#[allow(missing_docs)]
pub mod lossy;

mod sealed {
// HACK(eddyb) sealed away and not named `str` to avoid changing name resolution.
// Only `pub` to avoid the privacy checker producing errors.
#[cfg(not(bootstrap))]
#[lang = "str"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Str([u8]);

#[unstable(feature = "structural_match", issue = "31434")]
impl crate::marker::StructuralPartialEq for str {}

#[unstable(feature = "structural_match", issue = "31434")]
impl crate::marker::StructuralEq for str {}
}

/// Parse a value from a string
///
/// `FromStr`'s [`from_str`] method is often used implicitly, through
Expand Down Expand Up @@ -2224,7 +2239,8 @@ fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
);
}

#[lang = "str"]
#[cfg_attr(bootstrap, lang = "str")]
#[cfg_attr(not(bootstrap), lang = "str_impl")]
#[cfg(not(test))]
impl str {
/// Returns the length of `self`.
Expand Down
8 changes: 6 additions & 2 deletions src/librustc_codegen_llvm/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,9 @@ pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Sp

let ptr_metadata = |ty: Ty<'tcx>| match ty.kind {
ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)),
ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)),
ty::Adt(def, _) if def.is_str() => {
Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span))
}
ty::Dynamic(..) => Ok(MetadataCreationResult::new(
trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
false,
Expand Down Expand Up @@ -601,7 +603,9 @@ pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Sp
ty::Array(typ, _) | ty::Slice(typ) => {
fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span)
}
ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span),
ty::Adt(def, _) if def.is_str() => {
fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span)
}
ty::Dynamic(..) => {
MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false)
}
Expand Down
3 changes: 1 addition & 2 deletions src/librustc_codegen_llvm/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ fn uncached_llvm_type<'a, 'tcx>(
// FIXME(eddyb) producing readable type names for trait objects can result
// in problematically distinct types due to HRTB and subtyping (see #47638).
// ty::Dynamic(..) |
ty::Foreign(..) |
ty::Str => {
ty::Foreign(..) => {
let mut name = String::with_capacity(32);
let printer = DefPathBasedNames::new(cx.tcx, true, true);
printer.push_type_name(layout.ty, &mut name, false);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/debuginfo/type_names.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub fn push_debuginfo_type_name<'tcx>(
match t.kind {
ty::Bool => output.push_str("bool"),
ty::Char => output.push_str("char"),
ty::Str => output.push_str("str"),
ty::Adt(def, _) if def.is_str() => output.push_str("str"),
ty::Never => output.push_str("!"),
ty::Int(int_ty) => output.push_str(int_ty.name_str()),
ty::Uint(uint_ty) => output.push_str(uint_ty.name_str()),
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/glue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn size_and_align_of_dst<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let vtable = info.unwrap();
(meth::SIZE.get_usize(bx, vtable), meth::ALIGN.get_usize(bx, vtable))
}
ty::Slice(_) | ty::Str => {
ty::Slice(_) => {
let unit = layout.field(bx, 0);
// The info in this case is the length of the str, so the size is that
// times the unit size.
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/mir/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
return simple();
}
_ if !field.is_unsized() => return simple(),
ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
ty::Slice(..) | ty::Foreign(..) => return simple(),
ty::Adt(def, _) => {
if def.repr.packed() {
// FIXME(eddyb) generalize the adjustment when we
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_ssa/traits/type_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub trait DerivedTypeMethods<'tcx>: BaseTypeMethods<'tcx> + MiscMethods<'tcx> {
let tail = self.tcx().struct_tail_erasing_lifetimes(ty, param_env);
match tail.kind {
ty::Foreign(..) => false,
ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
ty::Slice(..) | ty::Dynamic(..) => true,
_ => bug!("unexpected unsized tail: {:?}", tail),
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_hir/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,11 @@ language_item_table! {
// Variant name, Name, Method name, Target;
BoolImplItem, "bool", bool_impl, Target::Impl;
CharImplItem, "char", char_impl, Target::Impl;
StrImplItem, "str", str_impl, Target::Impl;
StrItem, "str", str_type, Target::Struct;
StrImplItem, "str_impl", str_impl, Target::Impl;
SliceImplItem, "slice", slice_impl, Target::Impl;
SliceU8ImplItem, "slice_u8", slice_u8_impl, Target::Impl;
StrAllocImplItem, "str_alloc", str_alloc_impl, Target::Impl;
StrAllocImplItem, "str_alloc_impl", str_alloc_impl, Target::Impl;
SliceAllocImplItem, "slice_alloc", slice_alloc_impl, Target::Impl;
SliceU8AllocImplItem, "slice_u8_alloc", slice_u8_alloc_impl, Target::Impl;
ConstPtrImplItem, "const_ptr", const_ptr_impl, Target::Impl;
Expand Down
1 change: 0 additions & 1 deletion src/librustc_infer/infer/canonical/canonicalizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,6 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for Canonicalizer<'cx, 'tcx> {
| ty::Uint(..)
| ty::Float(..)
| ty::Adt(..)
| ty::Str
| ty::Error
| ty::Array(..)
| ty::Slice(..)
Expand Down
1 change: 0 additions & 1 deletion src/librustc_infer/infer/freshen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,6 @@ impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> {
| ty::Uint(..)
| ty::Float(..)
| ty::Adt(..)
| ty::Str
| ty::Error
| ty::Array(..)
| ty::Slice(..)
Expand Down
12 changes: 6 additions & 6 deletions src/librustc_lint/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,12 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
}

match ty.kind {
ty::Adt(def, _) if def.is_str() => FfiUnsafe {
ty,
reason: "string slices have no C equivalent",
help: Some("consider using `*const u8` and a length instead"),
},

ty::Adt(def, substs) => {
if def.is_phantom_data() {
return FfiPhantom(ty);
Expand Down Expand Up @@ -822,12 +828,6 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
FfiUnsafe { ty, reason: "trait objects have no C equivalent", help: None }
}

ty::Str => FfiUnsafe {
ty,
reason: "string slices have no C equivalent",
help: Some("consider using `*const u8` and a length instead"),
},

ty::Tuple(..) => FfiUnsafe {
ty,
reason: "tuples have unspecified layout",
Expand Down
1 change: 0 additions & 1 deletion src/librustc_middle/traits/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
| ty::GeneratorWitness(..)
| ty::RawPtr(_)
| ty::Ref(..)
| ty::Str
| ty::Foreign(..)
| ty::Error => true,

Expand Down
6 changes: 4 additions & 2 deletions src/librustc_middle/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1838,7 +1838,7 @@ macro_rules! sty_debug_print {
for &Interned(t) in types {
let variant = match t.kind {
ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
ty::Float(..) | ty::Str | ty::Never => continue,
ty::Float(..) | ty::Never => continue,
ty::Error => /* unimportant */ continue,
$(ty::$variant(..) => &mut $variant,)*
};
Expand Down Expand Up @@ -2165,7 +2165,9 @@ impl<'tcx> TyCtxt<'tcx> {

#[inline]
pub fn mk_str(self) -> Ty<'tcx> {
self.mk_ty(Str)
let def_id = self.require_lang_item(lang_items::StrItem, None);
let adt_def = self.adt_def(def_id);
self.mk_ty(Adt(adt_def, InternalSubsts::empty()))
}

#[inline]
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_middle/ty/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ impl<'tcx> TyS<'tcx> {
match self.kind {
Bool
| Char
| Str
| Int(_)
| Uint(_)
| Float(_)
| Infer(InferTy::IntVar(_))
| Infer(InferTy::FloatVar(_))
| Infer(InferTy::FreshIntTy(_))
| Infer(InferTy::FreshFloatTy(_)) => true,
Adt(def, _) if def.is_str() => true,
_ => false,
}
}
Expand All @@ -28,14 +28,14 @@ impl<'tcx> TyS<'tcx> {
match self.kind {
Bool
| Char
| Str
| Int(_)
| Uint(_)
| Float(_)
| Infer(InferTy::IntVar(_))
| Infer(InferTy::FloatVar(_))
| Infer(InferTy::FreshIntTy(_))
| Infer(InferTy::FreshFloatTy(_)) => true,
Adt(def, _) if def.is_str() => true,
Ref(_, x, _) | Array(x, _) | Slice(x) => x.peel_refs().is_simple_ty(),
Tuple(tys) if tys.is_empty() => true,
_ => false,
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_middle/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,10 @@ impl<'tcx> TypeError<'tcx> {
impl<'tcx> ty::TyS<'tcx> {
pub fn sort_string(&self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
match self.kind {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => {
format!("`{}`", self).into()
}
ty::Adt(def, _) if def.is_str() => "`str`".into(),
ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),

ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did)).into(),
Expand Down Expand Up @@ -288,8 +289,8 @@ impl<'tcx> ty::TyS<'tcx> {
| ty::Int(_)
| ty::Uint(_)
| ty::Float(_)
| ty::Str
| ty::Never => "type".into(),
ty::Adt(def, _) if def.is_str() => "type".into(),
ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
ty::Adt(def, _) => def.descr().into(),
ty::Foreign(_) => "extern type".into(),
Expand Down
4 changes: 0 additions & 4 deletions src/librustc_middle/ty/fast_reject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ where
UintSimplifiedType(ast::UintTy),
FloatSimplifiedType(ast::FloatTy),
AdtSimplifiedType(D),
StrSimplifiedType,
ArraySimplifiedType,
PtrSimplifiedType,
NeverSimplifiedType,
Expand Down Expand Up @@ -67,7 +66,6 @@ pub fn simplify_type(
ty::Uint(uint_type) => Some(UintSimplifiedType(uint_type)),
ty::Float(float_type) => Some(FloatSimplifiedType(float_type)),
ty::Adt(def, _) => Some(AdtSimplifiedType(def.did)),
ty::Str => Some(StrSimplifiedType),
ty::Array(..) | ty::Slice(_) => Some(ArraySimplifiedType),
ty::RawPtr(_) => Some(PtrSimplifiedType),
ty::Dynamic(ref trait_info, ..) => match trait_info.principal_def_id() {
Expand Down Expand Up @@ -122,7 +120,6 @@ impl<D: Copy + Debug + Ord + Eq> SimplifiedTypeGen<D> {
UintSimplifiedType(t) => UintSimplifiedType(t),
FloatSimplifiedType(t) => FloatSimplifiedType(t),
AdtSimplifiedType(d) => AdtSimplifiedType(map(d)),
StrSimplifiedType => StrSimplifiedType,
ArraySimplifiedType => ArraySimplifiedType,
PtrSimplifiedType => PtrSimplifiedType,
NeverSimplifiedType => NeverSimplifiedType,
Expand All @@ -149,7 +146,6 @@ where
match *self {
BoolSimplifiedType
| CharSimplifiedType
| StrSimplifiedType
| ArraySimplifiedType
| PtrSimplifiedType
| NeverSimplifiedType
Expand Down
1 change: 0 additions & 1 deletion src/librustc_middle/ty/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ impl FlagComputation {
| &ty::Float(_)
| &ty::Uint(_)
| &ty::Never
| &ty::Str
| &ty::Foreign(..) => {}

// You might think that we could just return Error for
Expand Down
13 changes: 2 additions & 11 deletions src/librustc_middle/ty/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
ty::Foreign(..) => {
return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr)));
}
ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)),
ty::Slice(_) => scalar_unit(Int(dl.ptr_sized_integer(), false)),
ty::Dynamic(..) => {
let mut vtable = scalar_unit(Pointer);
vtable.valid_range = 1..=*vtable.valid_range.end();
Expand Down Expand Up @@ -597,14 +597,6 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> {
size: Size::ZERO,
})
}
ty::Str => tcx.intern_layout(Layout {
variants: Variants::Single { index: VariantIdx::new(0) },
fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
abi: Abi::Aggregate { sized: false },
largest_niche: None,
align: dl.i8_align,
size: Size::ZERO,
}),

// Odd unit types.
ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?,
Expand Down Expand Up @@ -2069,7 +2061,7 @@ where
}

match tcx.struct_tail_erasing_lifetimes(pointee, cx.param_env()).kind {
ty::Slice(_) | ty::Str => tcx.types.usize,
ty::Slice(_) => tcx.types.usize,
ty::Dynamic(_, _) => {
tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.usize, 3))
/* FIXME: use actual fn pointers
Expand All @@ -2092,7 +2084,6 @@ where

// Arrays and slices.
ty::Array(element, _) | ty::Slice(element) => element,
ty::Str => tcx.types.u8,

// Tuples, generators and closures.
ty::Closure(_, ref substs) => substs.as_closure().upvar_tys().nth(i).unwrap(),
Expand Down
11 changes: 11 additions & 0 deletions src/librustc_middle/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1864,6 +1864,8 @@ bitflags! {
/// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
/// (i.e., this flag is never set unless this ADT is an enum).
const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 10;
/// Indicates whether the type is `str`.
const IS_STR = 1 << 11;
}
}

Expand Down Expand Up @@ -2254,6 +2256,9 @@ impl<'tcx> AdtDef {
if Some(did) == tcx.lang_items().rc() {
flags |= AdtFlags::IS_RC;
}
if Some(did) == tcx.lang_items().str_type() {
flags |= AdtFlags::IS_STR;
}

AdtDef { did, variants, flags, repr }
}
Expand Down Expand Up @@ -2354,6 +2359,12 @@ impl<'tcx> AdtDef {
self.flags.contains(AdtFlags::IS_MANUALLY_DROP)
}

/// Returns `true` if this is `str`.
#[inline]
pub fn is_str(&self) -> bool {
self.flags.contains(AdtFlags::IS_STR)
}

/// Returns `true` if this type has a destructor.
pub fn has_dtor(&self, tcx: TyCtxt<'tcx>) -> bool {
self.destructor(tcx).is_some()
Expand Down
1 change: 0 additions & 1 deletion src/librustc_middle/ty/outlives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,6 @@ fn compute_components(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, out: &mut SmallVec<[Compo
ty::Adt(..) | // OutlivesNominalType
ty::Opaque(..) | // OutlivesNominalType (ish)
ty::Foreign(..) | // OutlivesNominalType
ty::Str | // OutlivesScalar (ish)
ty::Array(..) | // ...
ty::Slice(..) | // ...
ty::RawPtr(..) | // ...
Expand Down
1 change: 0 additions & 1 deletion src/librustc_middle/ty/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,6 @@ pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option<DefId> {
| ty::Char
| ty::Int(_)
| ty::Uint(_)
| ty::Str
| ty::FnPtr(_)
| ty::Projection(_)
| ty::Placeholder(..)
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_middle/ty/print/obsolete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl DefPathBasedNames<'tcx> {
match t.kind {
ty::Bool => output.push_str("bool"),
ty::Char => output.push_str("char"),
ty::Str => output.push_str("str"),
ty::Adt(def, _) if def.is_str() => output.push_str("str"),
ty::Never => output.push_str("!"),
ty::Int(ty) => output.push_str(ty.name_str()),
ty::Uint(ty) => output.push_str(ty.name_str()),
Expand Down
Loading