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

Rollup of 6 pull requests #103483

Closed
wants to merge 16 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
62 changes: 1 addition & 61 deletions compiler/rustc_ast_passes/src/feature_gate.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use rustc_ast as ast;
use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
use rustc_ast::{AssocConstraint, AssocConstraintKind, NodeId};
use rustc_ast::{PatKind, RangeEnd, VariantData};
use rustc_ast::{PatKind, RangeEnd};
use rustc_errors::{struct_span_err, Applicability, StashKey};
use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP};
use rustc_session::parse::{feature_err, feature_err_issue, feature_warn};
Expand Down Expand Up @@ -116,46 +116,6 @@ impl<'a> PostExpansionVisitor<'a> {
}
}

fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
let has_fields = variants.iter().any(|variant| match variant.data {
VariantData::Tuple(..) | VariantData::Struct(..) => true,
VariantData::Unit(..) => false,
});

let discriminant_spans = variants
.iter()
.filter(|variant| match variant.data {
VariantData::Tuple(..) | VariantData::Struct(..) => false,
VariantData::Unit(..) => true,
})
.filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
.collect::<Vec<_>>();

if !discriminant_spans.is_empty() && has_fields {
let mut err = feature_err(
&self.sess.parse_sess,
sym::arbitrary_enum_discriminant,
discriminant_spans.clone(),
"custom discriminant values are not allowed in enums with tuple or struct variants",
);
for sp in discriminant_spans {
err.span_label(sp, "disallowed custom discriminant");
}
for variant in variants.iter() {
match &variant.data {
VariantData::Struct(..) => {
err.span_label(variant.span, "struct variant defined here");
}
VariantData::Tuple(..) => {
err.span_label(variant.span, "tuple variant defined here");
}
VariantData::Unit(..) => {}
}
}
err.emit();
}
}

/// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
fn check_impl_trait(&self, ty: &ast::Ty) {
struct ImplTraitVisitor<'a> {
Expand Down Expand Up @@ -273,26 +233,6 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
}
}

ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
for variant in variants {
match (&variant.data, &variant.disr_expr) {
(ast::VariantData::Unit(..), _) => {}
(_, Some(disr_expr)) => gate_feature_post!(
&self,
arbitrary_enum_discriminant,
disr_expr.value.span,
"discriminants on non-unit variants are experimental"
),
_ => {}
}
}

let has_feature = self.features.arbitrary_enum_discriminant;
if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
self.maybe_report_invalid_custom_discriminants(&variants);
}
}

ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
if let ast::ImplPolarity::Negative(span) = polarity {
gate_feature_post!(
Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_error_codes/src/error_codes/E0732.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ An `enum` with a discriminant must specify a `#[repr(inttype)]`.
Erroneous code example:

```compile_fail,E0732
#![feature(arbitrary_enum_discriminant)]

enum Enum { // error!
Unit = 1,
Tuple() = 2,
Expand All @@ -20,8 +18,6 @@ is a well-defined way to extract a variant's discriminant from a value;
for instance:

```
#![feature(arbitrary_enum_discriminant)]

#[repr(u8)]
enum Enum {
Unit = 3,
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/accepted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ declare_features! (
(accepted, abi_sysv64, "1.24.0", Some(36167), None),
/// Allows using ADX intrinsics from `core::arch::{x86, x86_64}`.
(accepted, adx_target_feature, "1.61.0", Some(44839), None),
/// Allows explicit discriminants on non-unit enum variants.
(accepted, arbitrary_enum_discriminant, "CURRENT_RUSTC_VERSION", Some(60553), None),
/// Allows using `sym` operands in inline assembly.
(accepted, asm_sym, "CURRENT_RUSTC_VERSION", Some(93333), None),
/// Allows the definition of associated constants in `trait` or `impl` blocks.
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_feature/src/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,6 @@ declare_features! (
(incomplete, adt_const_params, "1.56.0", Some(95174), None),
/// Allows defining an `#[alloc_error_handler]`.
(active, alloc_error_handler, "1.29.0", Some(51540), None),
/// Allows explicit discriminants on non-unit enum variants.
(active, arbitrary_enum_discriminant, "1.37.0", Some(60553), None),
/// Allows trait methods with arbitrary self types.
(active, arbitrary_self_types, "1.23.0", Some(44874), None),
/// Allows using `const` operands in inline assembly.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1180,7 +1180,7 @@ fn check_enum<'tcx>(tcx: TyCtxt<'tcx>, vs: &'tcx [hir::Variant<'tcx>], def_id: L
}
}

if tcx.adt_def(def_id).repr().int.is_none() && tcx.features().arbitrary_enum_discriminant {
if tcx.adt_def(def_id).repr().int.is_none() {
let is_unit = |var: &hir::Variant<'_>| matches!(var.data, hir::VariantData::Unit(..));

let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some();
Expand Down
27 changes: 14 additions & 13 deletions compiler/rustc_hir_analysis/src/collect/generics_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
// Now create the real type and const parameters.
let type_start = own_start - has_self as u32 + params.len() as u32;
let mut i = 0;
let mut next_index = || {
let prev = i;
i += 1;
prev as u32 + type_start
};

const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
`struct`, `enum`, `type`, or `trait` definitions";
Expand Down Expand Up @@ -278,15 +283,13 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {

let kind = ty::GenericParamDefKind::Type { has_default: default.is_some(), synthetic };

let param_def = ty::GenericParamDef {
index: type_start + i as u32,
Some(ty::GenericParamDef {
index: next_index(),
name: param.name.ident().name,
def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
pure_wrt_drop: param.pure_wrt_drop,
kind,
};
i += 1;
Some(param_def)
})
}
GenericParamKind::Const { default, .. } => {
if !matches!(allow_defaults, Defaults::Allowed) && default.is_some() {
Expand All @@ -297,15 +300,13 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
);
}

let param_def = ty::GenericParamDef {
index: type_start + i as u32,
Some(ty::GenericParamDef {
index: next_index(),
name: param.name.ident().name,
def_id: tcx.hir().local_def_id(param.hir_id).to_def_id(),
pure_wrt_drop: param.pure_wrt_drop,
kind: ty::GenericParamDefKind::Const { has_default: default.is_some() },
};
i += 1;
Some(param_def)
})
}
}));

Expand All @@ -323,8 +324,8 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
&["<closure_kind>", "<closure_signature>", "<upvars>"][..]
};

params.extend(dummy_args.iter().enumerate().map(|(i, &arg)| ty::GenericParamDef {
index: type_start + i as u32,
params.extend(dummy_args.iter().map(|&arg| ty::GenericParamDef {
index: next_index(),
name: Symbol::intern(arg),
def_id,
pure_wrt_drop: false,
Expand All @@ -337,7 +338,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Generics {
let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
if let Node::Expr(&Expr { kind: ExprKind::ConstBlock(_), .. }) = parent_node {
params.push(ty::GenericParamDef {
index: type_start,
index: next_index(),
name: Symbol::intern("<const_ty>"),
def_id,
pure_wrt_drop: false,
Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_hir_typeck/src/upvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

// We now fake capture information for all variables that are mentioned within the closure
// We do this after handling migrations so that min_captures computes before
if !enable_precise_capture(self.tcx, span) {
if !enable_precise_capture(self.tcx, span)
// (ouz-a) #93242 - ICE happens because closure_min_captures is empty with
// 2021 edition, because it sets `enable_precise_capture` to true, which won't allow us
// fake capture information this check sidesteps that and avoids the ICE.
|| (infer_kind == None && self.typeck_results.borrow().closure_min_captures.is_empty())
{
let mut capture_information: InferredCaptureInformation<'tcx> = Default::default();

if let Some(upvars) = self.tcx.upvars_mentioned(closure_def_id) {
Expand Down
42 changes: 29 additions & 13 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ type Res = def::Res<ast::NodeId>;
/// A field or associated item from self type suggested in case of resolution failure.
enum AssocSuggestion {
Field,
MethodWithSelf,
AssocFn,
MethodWithSelf { called: bool },
AssocFn { called: bool },
AssocType,
AssocConst,
}
Expand All @@ -48,8 +48,14 @@ impl AssocSuggestion {
fn action(&self) -> &'static str {
match self {
AssocSuggestion::Field => "use the available field",
AssocSuggestion::MethodWithSelf => "call the method with the fully-qualified path",
AssocSuggestion::AssocFn => "call the associated function",
AssocSuggestion::MethodWithSelf { called: true } => {
"call the method with the fully-qualified path"
}
AssocSuggestion::MethodWithSelf { called: false } => {
"refer to the method with the fully-qualified path"
}
AssocSuggestion::AssocFn { called: true } => "call the associated function",
AssocSuggestion::AssocFn { called: false } => "refer to the associated function",
AssocSuggestion::AssocConst => "use the associated `const`",
AssocSuggestion::AssocType => "use the associated type",
}
Expand Down Expand Up @@ -516,7 +522,9 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
let typo_sugg =
self.lookup_typo_candidate(path, source.namespace(), is_expected).to_opt_suggestion();
if path.len() == 1 && self.self_type_is_available() {
if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
if let Some(candidate) =
self.lookup_assoc_candidate(ident, ns, is_expected, source.is_call())
{
let self_is_available = self.self_value_is_available(path[0].ident.span);
match candidate {
AssocSuggestion::Field => {
Expand All @@ -531,16 +539,21 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
err.span_label(span, "a field by this name exists in `Self`");
}
}
AssocSuggestion::MethodWithSelf if self_is_available => {
AssocSuggestion::MethodWithSelf { called } if self_is_available => {
let msg = if called {
"you might have meant to call the method"
} else {
"you might have meant to refer to the method"
};
err.span_suggestion(
span,
"you might have meant to call the method",
msg,
format!("self.{path_str}"),
Applicability::MachineApplicable,
);
}
AssocSuggestion::MethodWithSelf
| AssocSuggestion::AssocFn
AssocSuggestion::MethodWithSelf { .. }
| AssocSuggestion::AssocFn { .. }
| AssocSuggestion::AssocConst
| AssocSuggestion::AssocType => {
err.span_suggestion(
Expand Down Expand Up @@ -1498,6 +1511,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
ident: Ident,
ns: Namespace,
filter_fn: FilterFn,
called: bool,
) -> Option<AssocSuggestion>
where
FilterFn: Fn(Res) -> bool,
Expand Down Expand Up @@ -1539,9 +1553,9 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
return Some(match &assoc_item.kind {
ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
AssocSuggestion::MethodWithSelf
AssocSuggestion::MethodWithSelf { called }
}
ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn { called },
ast::AssocItemKind::Type(..) => AssocSuggestion::AssocType,
ast::AssocItemKind::MacCall(_) => continue,
});
Expand All @@ -1560,10 +1574,12 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
let res = binding.res();
if filter_fn(res) {
if self.r.has_self.contains(&res.def_id()) {
return Some(AssocSuggestion::MethodWithSelf);
return Some(AssocSuggestion::MethodWithSelf { called });
} else {
match res {
Res::Def(DefKind::AssocFn, _) => return Some(AssocSuggestion::AssocFn),
Res::Def(DefKind::AssocFn, _) => {
return Some(AssocSuggestion::AssocFn { called });
}
Res::Def(DefKind::AssocConst, _) => {
return Some(AssocSuggestion::AssocConst);
}
Expand Down
18 changes: 18 additions & 0 deletions library/std/src/sys/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,11 @@ impl Thread {

#[cfg(target_os = "linux")]
pub fn set_name(name: &CStr) {
const TASK_COMM_LEN: usize = 16;

unsafe {
// Available since glibc 2.12, musl 1.1.16, and uClibc 1.0.20.
let name = truncate_cstr(name, TASK_COMM_LEN);
libc::pthread_setname_np(libc::pthread_self(), name.as_ptr());
}
}
Expand All @@ -148,6 +151,7 @@ impl Thread {
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
pub fn set_name(name: &CStr) {
unsafe {
let name = truncate_cstr(name, libc::MAXTHREADNAMESIZE);
libc::pthread_setname_np(name.as_ptr());
}
}
Expand Down Expand Up @@ -276,6 +280,20 @@ impl Drop for Thread {
}
}

#[cfg(any(target_os = "linux", target_os = "macos", target_os = "ios", target_os = "watchos"))]
fn truncate_cstr(cstr: &CStr, max_with_nul: usize) -> crate::borrow::Cow<'_, CStr> {
use crate::{borrow::Cow, ffi::CString};

if cstr.to_bytes_with_nul().len() > max_with_nul {
let bytes = cstr.to_bytes()[..max_with_nul - 1].to_vec();
// SAFETY: the non-nul bytes came straight from a CStr.
// (CString will add the terminating nul.)
Cow::Owned(unsafe { CString::from_vec_unchecked(bytes) })
} else {
Cow::Borrowed(cstr)
}
}

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
cfg_if::cfg_if! {
if #[cfg(any(
Expand Down
31 changes: 31 additions & 0 deletions library/std/src/thread/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,37 @@ fn test_named_thread() {
.unwrap();
}

#[cfg(any(
// Note: musl didn't add pthread_getname_np until 1.2.3
all(target_os = "linux", target_env = "gnu"),
target_os = "macos",
target_os = "ios",
target_os = "watchos"
))]
#[test]
fn test_named_thread_truncation() {
use crate::ffi::CStr;

let long_name = crate::iter::once("test_named_thread_truncation")
.chain(crate::iter::repeat(" yada").take(100))
.collect::<String>();

let result = Builder::new().name(long_name.clone()).spawn(move || {
// Rust remembers the full thread name itself.
assert_eq!(thread::current().name(), Some(long_name.as_str()));

// But the system is limited -- make sure we successfully set a truncation.
let mut buf = vec![0u8; long_name.len() + 1];
unsafe {
libc::pthread_getname_np(libc::pthread_self(), buf.as_mut_ptr().cast(), buf.len());
}
let cstr = CStr::from_bytes_until_nul(&buf).unwrap();
assert!(cstr.to_bytes().len() > 0);
assert!(long_name.as_bytes().starts_with(cstr.to_bytes()));
});
result.unwrap().join().unwrap();
}

#[test]
#[should_panic]
fn test_invalid_named_thread() {
Expand Down
Loading