Auto merge of #3803 - RalfJung:rustup, r=RalfJung

Rustup
This commit is contained in:
bors 2024-08-14 05:52:50 +00:00
commit f25ca7eca8
677 changed files with 9250 additions and 5423 deletions

View File

@ -167,11 +167,21 @@ ast_lowering_template_modifier = template modifier
ast_lowering_this_not_async = this is not `async`
ast_lowering_underscore_array_length_unstable =
using `_` for array lengths is unstable
ast_lowering_underscore_expr_lhs_assign =
in expressions, `_` can only be used on the left-hand side of an assignment
.label = `_` not allowed here
ast_lowering_unstable_inline_assembly = inline assembly is not stable yet on this architecture
ast_lowering_unstable_inline_assembly_label_operands =
label operands for inline assembly are unstable
ast_lowering_unstable_may_unwind = the `may_unwind` option is unstable
ast_lowering_use_angle_brackets = use angle brackets instead
ast_lowering_yield = yield syntax is experimental
ast_lowering_yield_in_closure =
`yield` can only be used in `#[coroutine]` closures, or `gen` blocks
.suggestion = use `#[coroutine]` to make this closure a coroutine

View File

@ -19,10 +19,12 @@ use super::errors::{
InvalidRegisterClass, RegisterClassOnlyClobber, RegisterConflict,
};
use super::LoweringContext;
use crate::{ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt};
use crate::{
fluent_generated as fluent, ImplTraitContext, ImplTraitPosition, ParamMode,
ResolverAstLoweringExt,
};
impl<'a, 'hir> LoweringContext<'a, 'hir> {
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
pub(crate) fn lower_inline_asm(
&mut self,
sp: Span,
@ -52,7 +54,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&self.tcx.sess,
sym::asm_experimental_arch,
sp,
"inline assembly is not stable yet on this architecture",
fluent::ast_lowering_unstable_inline_assembly,
)
.emit();
}
@ -64,8 +66,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.dcx().emit_err(AttSyntaxOnlyX86 { span: sp });
}
if asm.options.contains(InlineAsmOptions::MAY_UNWIND) && !self.tcx.features().asm_unwind {
feature_err(&self.tcx.sess, sym::asm_unwind, sp, "the `may_unwind` option is unstable")
.emit();
feature_err(
&self.tcx.sess,
sym::asm_unwind,
sp,
fluent::ast_lowering_unstable_may_unwind,
)
.emit();
}
let mut clobber_abis = FxIndexMap::default();
@ -176,20 +183,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
out_expr: out_expr.as_ref().map(|expr| self.lower_expr(expr)),
}
}
InlineAsmOperand::Const { anon_const } => {
if !self.tcx.features().asm_const {
feature_err(
sess,
sym::asm_const,
*op_sp,
"const operands for inline assembly are unstable",
)
.emit();
}
hir::InlineAsmOperand::Const {
anon_const: self.lower_anon_const_to_anon_const(anon_const),
}
}
InlineAsmOperand::Const { anon_const } => hir::InlineAsmOperand::Const {
anon_const: self.lower_anon_const_to_anon_const(anon_const),
},
InlineAsmOperand::Sym { sym } => {
let static_def_id = self
.resolver
@ -246,7 +242,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
sess,
sym::asm_goto,
*op_sp,
"label operands for inline assembly are unstable",
fluent::ast_lowering_unstable_inline_assembly_label_operands,
)
.emit();
}

View File

@ -23,7 +23,7 @@ use super::{
ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs, ResolverAstLoweringExt,
};
use crate::errors::YieldInClosure;
use crate::{FnDeclKind, ImplTraitPosition};
use crate::{fluent_generated, FnDeclKind, ImplTraitPosition};
impl<'hir> LoweringContext<'_, 'hir> {
fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
@ -1540,7 +1540,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
}
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
let yielded =
opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
@ -1575,7 +1574,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&self.tcx.sess,
sym::coroutines,
span,
"yield syntax is experimental",
fluent_generated::ast_lowering_yield,
)
.emit();
}
@ -1587,7 +1586,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
&self.tcx.sess,
sym::coroutines,
span,
"yield syntax is experimental",
fluent_generated::ast_lowering_yield,
)
.emit();
}

View File

@ -2326,7 +2326,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.expr_block(block)
}
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen<'hir> {
match c.value.kind {
ExprKind::Underscore => {
@ -2340,7 +2339,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
&self.tcx.sess,
sym::generic_arg_infer,
c.value.span,
"using `_` for array lengths is unstable",
fluent_generated::ast_lowering_underscore_array_length_unstable,
)
.stash(c.value.span, StashKey::UnderscoreForArrayLengths);
hir::ArrayLen::Body(self.lower_anon_const_to_const_arg(c))

View File

@ -104,6 +104,9 @@ attr_unknown_meta_item =
attr_unknown_version_literal =
unknown version literal format, assuming it refers to a future version
attr_unstable_cfg_target_compact =
compact `cfg(target(..))` is experimental and subject to change
attr_unsupported_literal_cfg_string =
literal in `cfg` predicate value must be a string
attr_unsupported_literal_deprecated_kv_pair =

View File

@ -20,6 +20,7 @@ use rustc_span::hygiene::Transparency;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span;
use crate::fluent_generated;
use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
/// The version placeholder that recently stabilized features contain inside the
@ -521,7 +522,6 @@ pub struct Condition {
}
/// Tests if a cfg-pattern matches the cfg set
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
pub fn cfg_matches(
cfg: &ast::MetaItem,
sess: &Session,
@ -593,7 +593,6 @@ pub fn parse_version(s: Symbol) -> Option<RustcVersion> {
/// Evaluate a cfg-like condition (with `any` and `all`), using `eval` to
/// evaluate individual items.
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
pub fn eval_condition(
cfg: &ast::MetaItem,
sess: &Session,
@ -680,7 +679,7 @@ pub fn eval_condition(
sess,
sym::cfg_target_compact,
cfg.span,
"compact `cfg(target(..))` is experimental and subject to change",
fluent_generated::attr_unstable_cfg_target_compact,
)
.emit();
}

View File

@ -62,6 +62,9 @@ borrowck_could_not_normalize =
borrowck_could_not_prove =
could not prove `{$predicate}`
borrowck_dereference_suggestion =
dereference the return value
borrowck_func_take_self_moved_place =
`{$func}` takes ownership of the receiver `self`, which moves {$place_name}
@ -74,9 +77,24 @@ borrowck_higher_ranked_lifetime_error =
borrowck_higher_ranked_subtype_error =
higher-ranked subtype error
borrowck_implicit_static =
this has an implicit `'static` lifetime requirement
borrowck_implicit_static_introduced =
calling this method introduces the `impl`'s `'static` requirement
borrowck_implicit_static_relax =
consider relaxing the implicit `'static` requirement
borrowck_lifetime_constraints_error =
lifetime may not live long enough
borrowck_limitations_implies_static =
due to current limitations in the borrow checker, this implies a `'static` lifetime
borrowck_move_closure_suggestion =
consider adding 'move' keyword before the nested closure
borrowck_move_out_place_here =
{$place} is moved here
@ -163,6 +181,9 @@ borrowck_partial_var_move_by_use_in_coroutine =
*[false] moved
} due to use in coroutine
borrowck_restrict_to_static =
consider restricting the type parameter to the `'static` lifetime
borrowck_returned_async_block_escaped =
returns an `async` block that contains a reference to a captured variable, which then escapes the closure body

View File

@ -3989,7 +3989,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
} else {
let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity();
match ty.kind() {
ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig(
ty::FnDef(_, _) | ty::FnPtr(..) => self.annotate_fn_sig(
self.mir_def_id(),
self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(),
),

View File

@ -3,6 +3,8 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]
use std::assert_matches::assert_matches;
use rustc_errors::{Applicability, Diag};
use rustc_hir as hir;
use rustc_hir::intravisit::Visitor;
@ -116,7 +118,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
// path_span must be `Some` as otherwise the if condition is true
let path_span = path_span.unwrap();
// path_span is only present in the case of closure capture
assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
assert_matches!(later_use_kind, LaterUseKind::ClosureCapture);
if !borrow_span.is_some_and(|sp| sp.overlaps(var_or_use_span)) {
let path_label = "used here by closure";
let capture_kind_label = message;
@ -147,7 +149,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
// path_span must be `Some` as otherwise the if condition is true
let path_span = path_span.unwrap();
// path_span is only present in the case of closure capture
assert!(matches!(later_use_kind, LaterUseKind::ClosureCapture));
assert_matches!(later_use_kind, LaterUseKind::ClosureCapture);
if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
let path_label = "used here by closure";
let capture_kind_label = message;

View File

@ -35,7 +35,7 @@ use crate::session_diagnostics::{
LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote,
};
use crate::universal_regions::DefiningTy;
use crate::{borrowck_errors, MirBorrowckCtxt};
use crate::{borrowck_errors, fluent_generated as fluent, MirBorrowckCtxt};
impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> {
fn description(&self) -> &'static str {
@ -198,7 +198,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
// from higher-ranked trait bounds (HRTB). Try to locate span of the trait
// and the span which bounded to the trait for adding 'static lifetime suggestion
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn suggest_static_lifetime_for_gat_from_hrtb(
&self,
diag: &mut Diag<'_>,
@ -251,23 +250,28 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
debug!(?hrtb_bounds);
hrtb_bounds.iter().for_each(|bound| {
let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }, _) = bound else { return; };
diag.span_note(
*trait_span,
"due to current limitations in the borrow checker, this implies a `'static` lifetime"
);
let Some(generics_fn) = hir.get_generics(self.body.source.def_id().expect_local()) else { return; };
let Def(_, trait_res_defid) = trait_ref.path.res else { return; };
let Trait(PolyTraitRef { trait_ref, span: trait_span, .. }, _) = bound else {
return;
};
diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
let Some(generics_fn) = hir.get_generics(self.body.source.def_id().expect_local())
else {
return;
};
let Def(_, trait_res_defid) = trait_ref.path.res else {
return;
};
debug!(?generics_fn);
generics_fn.predicates.iter().for_each(|predicate| {
let BoundPredicate(
WhereBoundPredicate {
span: bounded_span,
bounded_ty,
bounds,
..
}
) = predicate else { return; };
let BoundPredicate(WhereBoundPredicate {
span: bounded_span,
bounded_ty,
bounds,
..
}) = predicate
else {
return;
};
bounds.iter().for_each(|bd| {
if let Trait(PolyTraitRef { trait_ref: tr_ref, .. }, _) = bd
&& let Def(_, res_defid) = tr_ref.path.res
@ -277,16 +281,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
&& generics_fn.params
.iter()
.rfind(|param| param.def_id.to_def_id() == defid)
.is_some() {
suggestions.push((bounded_span.shrink_to_hi(), " + 'static".to_string()));
}
.is_some()
{
suggestions.push((bounded_span.shrink_to_hi(), " + 'static".to_string()));
}
});
});
});
if suggestions.len() > 0 {
suggestions.dedup();
diag.multipart_suggestion_verbose(
"consider restricting the type parameter to the `'static` lifetime",
fluent::borrowck_restrict_to_static,
suggestions,
Applicability::MaybeIncorrect,
);
@ -976,7 +981,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
}
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
#[instrument(skip(self, err), level = "debug")]
fn suggest_constrain_dyn_trait_in_impl(
&self,
@ -994,16 +998,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
debug!("trait spans found: {:?}", traits);
for span in &traits {
let mut multi_span: MultiSpan = vec![*span].into();
multi_span
.push_span_label(*span, "this has an implicit `'static` lifetime requirement");
multi_span.push_span_label(
ident.span,
"calling this method introduces the `impl`'s `'static` requirement",
);
multi_span.push_span_label(*span, fluent::borrowck_implicit_static);
multi_span.push_span_label(ident.span, fluent::borrowck_implicit_static_introduced);
err.subdiagnostic(RequireStaticErr::UsedImpl { multi_span });
err.span_suggestion_verbose(
span.shrink_to_hi(),
"consider relaxing the implicit `'static` requirement",
fluent::borrowck_implicit_static_relax,
" + '_",
Applicability::MaybeIncorrect,
);
@ -1045,7 +1045,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
}
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
/// When encountering a lifetime error caused by the return type of a closure, check the
/// corresponding trait bound and see if dereferencing the closure return value would satisfy
/// them. If so, we produce a structured suggestion.
@ -1166,7 +1165,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
if ocx.select_all_or_error().is_empty() && count > 0 {
diag.span_suggestion_verbose(
tcx.hir().body(*body).value.peel_blocks().span.shrink_to_lo(),
"dereference the return value",
fluent::borrowck_dereference_suggestion,
"*".repeat(count),
Applicability::MachineApplicable,
);
@ -1174,7 +1173,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
}
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
let map = self.infcx.tcx.hir();
let body = map.body_owned_by(self.mir_def_id());
@ -1213,7 +1211,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
if let Some(closure_span) = closure_span {
diag.span_suggestion_verbose(
closure_span,
"consider adding 'move' keyword before the nested closure",
fluent::borrowck_move_closure_suggestion,
"move ",
Applicability::MaybeIncorrect,
);

View File

@ -1644,7 +1644,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
| ty::Pat(_, _)
| ty::Slice(_)
| ty::FnDef(_, _)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Dynamic(_, _, _)
| ty::Closure(_, _)
| ty::CoroutineClosure(_, _)
@ -1689,7 +1689,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
| ty::RawPtr(_, _)
| ty::Ref(_, _, _)
| ty::FnDef(_, _)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Dynamic(_, _, _)
| ty::CoroutineWitness(..)
| ty::Never

View File

@ -7,6 +7,7 @@ use rustc_middle::mir::ConstraintCategory;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, Upcast};
use rustc_span::def_id::DefId;
use rustc_span::Span;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
use rustc_trait_selection::traits::query::type_op::{self, TypeOpOutput};
use rustc_trait_selection::traits::ObligationCause;
@ -165,6 +166,52 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
result.unwrap_or(value)
}
#[instrument(skip(self), level = "debug")]
pub(super) fn struct_tail(
&mut self,
ty: Ty<'tcx>,
location: impl NormalizeLocation,
) -> Ty<'tcx> {
let tcx = self.tcx();
if self.infcx.next_trait_solver() {
let body = self.body;
let param_env = self.param_env;
self.fully_perform_op(
location.to_locations(),
ConstraintCategory::Boring,
CustomTypeOp::new(
|ocx| {
let structurally_normalize = |ty| {
ocx.structurally_normalize(
&ObligationCause::misc(
location.to_locations().span(body),
body.source.def_id().expect_local(),
),
param_env,
ty,
)
.unwrap_or_else(|_| bug!("struct tail should have been computable, since we computed it in HIR"))
};
let tail = tcx.struct_tail_raw(
ty,
structurally_normalize,
|| {},
);
Ok(tail)
},
"normalizing struct tail",
),
)
.unwrap_or_else(|guar| Ty::new_error(tcx, guar))
} else {
let mut normalize = |ty| self.normalize(ty, location);
let tail = tcx.struct_tail_raw(ty, &mut normalize, || {});
normalize(tail)
}
}
#[instrument(skip(self), level = "debug")]
pub(super) fn ascribe_user_type(
&mut self,

View File

@ -1364,7 +1364,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
debug!("func_ty.kind: {:?}", func_ty.kind());
let sig = match func_ty.kind() {
ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
_ => {
span_mirbug!(self, term, "call to non-function {:?}", func_ty);
return;
@ -1989,9 +1989,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let ty_fn_ptr_from = Ty::new_fn_ptr(tcx, fn_sig);
if let Err(terr) = self.eq_types(
*ty,
if let Err(terr) = self.sub_types(
ty_fn_ptr_from,
*ty,
location.to_locations(),
ConstraintCategory::Cast { unsize_to: None },
) {
@ -2014,9 +2014,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let ty_fn_ptr_from =
Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, *safety));
if let Err(terr) = self.eq_types(
*ty,
if let Err(terr) = self.sub_types(
ty_fn_ptr_from,
*ty,
location.to_locations(),
ConstraintCategory::Cast { unsize_to: None },
) {
@ -2329,17 +2329,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let cast_ty_to = CastTy::from_ty(*ty);
match (cast_ty_from, cast_ty_to) {
(Some(CastTy::Ptr(src)), Some(CastTy::Ptr(dst))) => {
let mut normalize = |t| self.normalize(t, location);
// N.B. `struct_tail_with_normalize` only "structurally resolves"
// the type. It is not fully normalized, so we have to normalize it
// afterwards.
let src_tail =
tcx.struct_tail_with_normalize(src.ty, &mut normalize, || ());
let src_tail = normalize(src_tail);
let dst_tail =
tcx.struct_tail_with_normalize(dst.ty, &mut normalize, || ());
let dst_tail = normalize(dst_tail);
let src_tail = self.struct_tail(src.ty, location);
let dst_tail = self.struct_tail(dst.ty, location);
// This checks (lifetime part of) vtable validity for pointer casts,
// which is irrelevant when there are aren't principal traits on both sides (aka only auto traits).
@ -2420,7 +2411,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let ty_left = left.ty(body, tcx);
match ty_left.kind() {
// Types with regions are comparable if they have a common super-type.
ty::RawPtr(_, _) | ty::FnPtr(_) => {
ty::RawPtr(_, _) | ty::FnPtr(..) => {
let ty_right = right.ty(body, tcx);
let common_ty = self.infcx.next_ty_var(body.source_info(location).span);
self.sub_types(

View File

@ -69,7 +69,7 @@ fn clif_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<types::Typ
FloatTy::F64 => types::F64,
FloatTy::F128 => unimplemented!("f16_f128"),
},
ty::FnPtr(_) => pointer_ty(tcx),
ty::FnPtr(..) => pointer_ty(tcx),
ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) => {
if has_ptr_meta(tcx, *pointee_ty) {
return None;

View File

@ -725,7 +725,8 @@ fn codegen_regular_intrinsic_call<'tcx>(
// Cranelift treats stores as volatile by default
// FIXME correctly handle unaligned_volatile_store
// FIXME actually do nontemporal stores if requested
// FIXME actually do nontemporal stores if requested (but do not just emit MOVNT on x86;
// see the LLVM backend for details)
let dest = CPlace::for_ptr(Pointer::new(ptr), val.layout());
dest.write_cvalue(fx, val);
}

View File

@ -874,7 +874,7 @@ pub(crate) fn assert_assignable<'tcx>(
(ty::Ref(_, a, _), ty::RawPtr(b, _)) | (ty::RawPtr(a, _), ty::Ref(_, b, _)) => {
assert_assignable(fx, *a, *b, limit - 1);
}
(ty::FnPtr(_), ty::FnPtr(_)) => {
(ty::FnPtr(..), ty::FnPtr(..)) => {
let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
ParamEnv::reveal_all(),
from_ty.fn_sig(fx.tcx),

View File

@ -552,7 +552,7 @@ fn asm_tests(env: &Env, args: &TestArg) -> Result<(), String> {
&"--stage",
&"0",
&"tests/assembly/asm",
&"--rustc-args",
&"--compiletest-rustc-args",
&rustc_args,
],
Some(&rust_dir),
@ -1020,7 +1020,7 @@ where
&"--stage",
&"0",
&format!("tests/{}", test_type),
&"--rustc-args",
&"--compiletest-rustc-args",
&rustc_args,
],
Some(&rust_path),

View File

@ -1127,6 +1127,8 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> {
self.llbb().add_assignment(self.location, aligned_destination, val);
// TODO(antoyo): handle align and flags.
// NOTE: dummy value here since it's never used. FIXME(antoyo): API should not return a value here?
// When adding support for NONTEMPORAL, make sure to not just emit MOVNT on x86; see the
// LLVM backend for details.
self.cx.context.new_rvalue_zero(self.type_i32())
}

View File

@ -160,6 +160,11 @@ impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
self.context.new_struct_constructor(None, struct_type.as_type(), None, values)
}
fn const_vector(&self, values: &[RValue<'gcc>]) -> RValue<'gcc> {
let typ = self.type_vector(values[0].get_type(), values.len() as u64);
self.context.new_rvalue_from_vector(None, typ, values)
}
fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
// TODO(antoyo)
None

View File

@ -213,9 +213,8 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> {
// NOTE: we cannot remove this match like in the LLVM codegen because the call
// to fn_ptr_backend_type handle the on-stack attribute.
// TODO(antoyo): find a less hackish way to hande the on-stack attribute.
ty::FnPtr(sig) => {
cx.fn_ptr_backend_type(cx.fn_abi_of_fn_ptr(sig, ty::List::empty()))
}
ty::FnPtr(sig_tys, hdr) => cx
.fn_ptr_backend_type(cx.fn_abi_of_fn_ptr(sig_tys.with(hdr), ty::List::empty())),
_ => self.scalar_gcc_type_at(cx, scalar, Size::ZERO),
};
cx.scalar_types.borrow_mut().insert(self.ty, ty);

View File

@ -3,12 +3,10 @@
// Run-time:
// status: 0
#![feature(asm_const)]
#[cfg(target_arch="x86_64")]
#[cfg(target_arch = "x86_64")]
use std::arch::{asm, global_asm};
#[cfg(target_arch="x86_64")]
#[cfg(target_arch = "x86_64")]
global_asm!(
"
.global add_asm
@ -22,7 +20,7 @@ extern "C" {
fn add_asm(a: i64, b: i64) -> i64;
}
#[cfg(target_arch="x86_64")]
#[cfg(target_arch = "x86_64")]
pub unsafe fn mem_cpy(dst: *mut u8, src: *const u8, len: usize) {
asm!(
"rep movsb",
@ -33,7 +31,7 @@ pub unsafe fn mem_cpy(dst: *mut u8, src: *const u8, len: usize) {
);
}
#[cfg(target_arch="x86_64")]
#[cfg(target_arch = "x86_64")]
fn asm() {
unsafe {
asm!("nop");
@ -178,9 +176,8 @@ fn asm() {
assert_eq!(array1, array2);
}
#[cfg(not(target_arch="x86_64"))]
fn asm() {
}
#[cfg(not(target_arch = "x86_64"))]
fn asm() {}
fn main() {
asm();

View File

@ -430,9 +430,32 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
i += 1;
i - 1
};
let apply_range_attr = |idx: AttributePlace, scalar: rustc_target::abi::Scalar| {
if cx.sess().opts.optimize != config::OptLevel::No
&& llvm_util::get_version() >= (19, 0, 0)
&& matches!(scalar.primitive(), Int(..))
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected
// by the LLVM verifier.
&& !scalar.is_bool()
// LLVM also rejects full range.
&& !scalar.is_always_valid(cx)
{
attributes::apply_to_llfn(
llfn,
idx,
&[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))],
);
}
};
match &self.ret.mode {
PassMode::Direct(attrs) => {
attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
}
}
PassMode::Indirect { attrs, meta_attrs: _, on_stack } => {
assert!(!on_stack);
@ -471,8 +494,13 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
);
attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
}
PassMode::Direct(attrs)
| PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
PassMode::Direct(attrs) => {
let i = apply(attrs);
if let abi::Abi::Scalar(scalar) = arg.layout.abi {
apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
}
}
PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => {
apply(attrs);
}
PassMode::Indirect { attrs, meta_attrs: Some(meta_attrs), on_stack } => {
@ -481,8 +509,12 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
apply(meta_attrs);
}
PassMode::Pair(a, b) => {
apply(a);
apply(b);
let i = apply(a);
let ii = apply(b);
if let abi::Abi::ScalarPair(scalar_a, scalar_b) = arg.layout.abi {
apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
}
}
PassMode::Cast { cast, pad_i32 } => {
if *pad_i32 {
@ -537,15 +569,18 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
}
_ => {}
}
if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected
// by the LLVM verifier.
if let Int(..) = scalar.primitive() {
if !scalar.is_bool() && !scalar.is_always_valid(bx) {
bx.range_metadata(callsite, scalar.valid_range(bx));
}
}
if bx.cx.sess().opts.optimize != config::OptLevel::No
&& llvm_util::get_version() < (19, 0, 0)
&& let abi::Abi::Scalar(scalar) = self.ret.layout.abi
&& matches!(scalar.primitive(), Int(..))
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected
// by the LLVM verifier.
&& !scalar.is_bool()
// LLVM also rejects full range.
&& !scalar.is_always_valid(bx)
{
bx.range_metadata(callsite, scalar.valid_range(bx));
}
for arg in self.args.iter() {
match &arg.mode {

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use libc::{c_char, c_uint};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_codegen_ssa::mir::operand::OperandValue;
@ -89,7 +91,7 @@ impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
// if the target feature needed by the register class is
// disabled. This is necessary otherwise LLVM will try
// to actually allocate a register for the dummy output.
assert!(matches!(reg, InlineAsmRegOrRegClass::Reg(_)));
assert_matches!(reg, InlineAsmRegOrRegClass::Reg(_));
clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
continue;
} else {

View File

@ -728,13 +728,32 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
llvm::LLVMSetVolatile(store, llvm::True);
}
if flags.contains(MemFlags::NONTEMPORAL) {
// According to LLVM [1] building a nontemporal store must
// *always* point to a metadata value of the integer 1.
//
// [1]: https://llvm.org/docs/LangRef.html#store-instruction
let one = self.cx.const_i32(1);
let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
// Make sure that the current target architectures supports "sane" non-temporal
// stores, i.e., non-temporal stores that are equivalent to regular stores except
// for performance. LLVM doesn't seem to care about this, and will happily treat
// `!nontemporal` stores as-if they were normal stores (for reordering optimizations
// etc) even on x86, despite later lowering them to MOVNT which do *not* behave like
// regular stores but require special fences.
// So we keep a list of architectures where `!nontemporal` is known to be truly just
// a hint, and use regular stores everywhere else.
// (In the future, we could alternatively ensure that an sfence gets emitted after a sequence of movnt
// before any kind of synchronizing operation. But it's not clear how to do that with LLVM.)
// For more context, see <https://github.com/rust-lang/rust/issues/114582> and
// <https://github.com/llvm/llvm-project/issues/64521>.
const WELL_BEHAVED_NONTEMPORAL_ARCHS: &[&str] =
&["aarch64", "arm", "riscv32", "riscv64"];
let use_nontemporal =
WELL_BEHAVED_NONTEMPORAL_ARCHS.contains(&&*self.cx.tcx.sess.target.arch);
if use_nontemporal {
// According to LLVM [1] building a nontemporal store must
// *always* point to a metadata value of the integer 1.
//
// [1]: https://llvm.org/docs/LangRef.html#store-instruction
let one = self.cx.const_i32(1);
let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1);
llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node);
}
}
store
}

View File

@ -97,11 +97,6 @@ impl<'ll> CodegenCx<'ll, '_> {
unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
}
pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
}
pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
bytes_in_context(self.llcx, bytes)
}
@ -221,6 +216,11 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
struct_in_context(self.llcx, elts, packed)
}
fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
}
fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
try_as_const_integral(v).and_then(|v| unsafe {
let mut i = 0u64;

View File

@ -456,7 +456,7 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D
{
build_pointer_or_reference_di_node(cx, t, t.boxed_ty(), unique_type_id)
}
ty::FnDef(..) | ty::FnPtr(_) => build_subroutine_type_di_node(cx, unique_type_id),
ty::FnDef(..) | ty::FnPtr(..) => build_subroutine_type_di_node(cx, unique_type_id),
ty::Closure(..) => build_closure_env_di_node(cx, unique_type_id),
ty::CoroutineClosure(..) => build_closure_env_di_node(cx, unique_type_id),
ty::Coroutine(..) => enums::build_coroutine_di_node(cx, unique_type_id),

View File

@ -1,3 +1,4 @@
use std::assert_matches::assert_matches;
use std::cmp::Ordering;
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
@ -1142,7 +1143,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
if cfg!(debug_assertions) {
for (ty, arg) in arg_tys.iter().zip(args) {
if ty.is_simd() {
assert!(matches!(arg.val, OperandValue::Immediate(_)));
assert_matches!(arg.val, OperandValue::Immediate(_));
}
}
}

View File

@ -8,6 +8,7 @@
#![allow(internal_features)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(exact_size_is_empty)]
#![feature(extern_types)]
#![feature(hash_raw_entry)]

View File

@ -1575,6 +1575,12 @@ extern "C" {
pub fn LLVMRustCreateAllocSizeAttr(C: &Context, size_arg: u32) -> &Attribute;
pub fn LLVMRustCreateAllocKindAttr(C: &Context, size_arg: u64) -> &Attribute;
pub fn LLVMRustCreateMemoryEffectsAttr(C: &Context, effects: MemoryEffects) -> &Attribute;
pub fn LLVMRustCreateRangeAttribute(
C: &Context,
num_bits: c_uint,
lower_words: *const u64,
upper_words: *const u64,
) -> &Attribute;
// Operations on functions
pub fn LLVMRustGetOrInsertFunction<'a>(

View File

@ -8,7 +8,7 @@ use std::string::FromUtf8Error;
use libc::c_uint;
use rustc_data_structures::small_c_str::SmallCStr;
use rustc_llvm::RustString;
use rustc_target::abi::Align;
use rustc_target::abi::{Align, Size, WrappingRange};
pub use self::AtomicRmwBinOp::*;
pub use self::CallConv::*;
@ -105,6 +105,21 @@ pub fn CreateAllocKindAttr(llcx: &Context, kind_arg: AllocKindFlags) -> &Attribu
unsafe { LLVMRustCreateAllocKindAttr(llcx, kind_arg.bits()) }
}
pub fn CreateRangeAttr(llcx: &Context, size: Size, range: WrappingRange) -> &Attribute {
let lower = range.start;
let upper = range.end.wrapping_add(1);
let lower_words = [lower as u64, (lower >> 64) as u64];
let upper_words = [upper as u64, (upper >> 64) as u64];
unsafe {
LLVMRustCreateRangeAttribute(
llcx,
size.bits().try_into().unwrap(),
lower_words.as_ptr(),
upper_words.as_ptr(),
)
}
}
#[derive(Copy, Clone)]
pub enum AttributePlace {
ReturnValue,

View File

@ -1,4 +1,5 @@
use std::any::Any;
use std::assert_matches::assert_matches;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver, Sender};
@ -1963,7 +1964,7 @@ impl SharedEmitterMain {
sess.dcx().abort_if_errors();
}
Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
assert!(matches!(level, Level::Error | Level::Warning | Level::Note));
assert_matches!(level, Level::Error | Level::Warning | Level::Note);
let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
let mut err = Diag::<()>::new(sess.dcx(), level, msg);

View File

@ -331,7 +331,7 @@ fn push_debuginfo_type_name<'tcx>(
output.push(')');
}
}
ty::FnDef(..) | ty::FnPtr(_) => {
ty::FnDef(..) | ty::FnPtr(..) => {
// We've encountered a weird 'recursive type'
// Currently, the only way to generate such a type
// is by using 'impl trait':

View File

@ -4,6 +4,7 @@
#![allow(rustc::untranslatable_diagnostic)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(if_let_guard)]
#![feature(let_chains)]

View File

@ -846,7 +846,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
),
None,
),
ty::FnPtr(_) => (None, Some(callee.immediate())),
ty::FnPtr(..) => (None, Some(callee.immediate())),
_ => bug!("{} is not callable", callee.layout.ty),
};
@ -923,8 +923,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
// third argument must be constant. This is
// checked by the type-checker.
if i == 2 && intrinsic.name == sym::simd_shuffle {
// FIXME: the simd_shuffle argument is actually an array,
// not a vector, so we need this special hack to make sure
// it is passed as an immediate. We should pass the
// shuffle indices as a vector instead to avoid this hack.
if let mir::Operand::Constant(constant) = &arg.node {
let (llval, ty) = self.simd_shuffle_indices(bx, constant);
let (llval, ty) = self.immediate_const_vector(bx, constant);
return OperandRef {
val: Immediate(llval),
layout: bx.layout_of(ty),

View File

@ -1,6 +1,6 @@
use rustc_middle::mir::interpret::ErrorHandled;
use rustc_middle::ty::layout::HasTyCtxt;
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{self, Ty, ValTree};
use rustc_middle::{bug, mir, span_bug};
use rustc_target::abi::Abi;
@ -28,7 +28,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
.expect("erroneous constant missed by mono item collection")
}
/// This is a convenience helper for `simd_shuffle_indices`. It has the precondition
/// This is a convenience helper for `immediate_const_vector`. It has the precondition
/// that the given `constant` is an `Const::Unevaluated` and must be convertible to
/// a `ValTree`. If you want a more general version of this, talk to `wg-const-eval` on zulip.
///
@ -59,23 +59,42 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
self.cx.tcx().const_eval_resolve_for_typeck(ty::ParamEnv::reveal_all(), uv, constant.span)
}
/// process constant containing SIMD shuffle indices
pub fn simd_shuffle_indices(
/// process constant containing SIMD shuffle indices & constant vectors
pub fn immediate_const_vector(
&mut self,
bx: &Bx,
constant: &mir::ConstOperand<'tcx>,
) -> (Bx::Value, Ty<'tcx>) {
let ty = self.monomorphize(constant.ty());
let ty_is_simd = ty.is_simd();
// FIXME: ideally we'd assert that this is a SIMD type, but simd_shuffle
// in its current form relies on a regular array being passed as an
// immediate argument. This hack can be removed once that is fixed.
let field_ty = if ty_is_simd {
ty.simd_size_and_type(bx.tcx()).1
} else {
ty.builtin_index().unwrap()
};
let val = self
.eval_unevaluated_mir_constant_to_valtree(constant)
.ok()
.map(|x| x.ok())
.flatten()
.map(|val| {
let field_ty = ty.builtin_index().unwrap();
let values: Vec<_> = val
.unwrap_branch()
.iter()
// Depending on whether this is a SIMD type with an array field
// or a type with many fields (one for each elements), the valtree
// is either a single branch with N children, or a root node
// with exactly one child which then in turn has many children.
// So we look at the first child to determine whether it is a
// leaf or whether we have to go one more layer down.
let branch_or_leaf = val.unwrap_branch();
let first = branch_or_leaf.get(0).unwrap();
let field_iter = match first {
ValTree::Branch(_) => first.unwrap_branch().iter(),
ValTree::Leaf(_) => branch_or_leaf.iter(),
};
let values: Vec<_> = field_iter
.map(|field| {
if let Some(prim) = field.try_to_scalar() {
let layout = bx.layout_of(field_ty);
@ -84,11 +103,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
};
bx.scalar_to_backend(prim, scalar, bx.immediate_backend_type(layout))
} else {
bug!("simd shuffle field {:?}", field)
bug!("field is not a scalar {:?}", field)
}
})
.collect();
bx.const_struct(&values, false)
if ty_is_simd { bx.const_vector(&values) } else { bx.const_struct(&values, false) }
})
.unwrap_or_else(|| {
bx.tcx().dcx().emit_err(errors::ShuffleIndicesEvaluation { span: constant.span });

View File

@ -1,3 +1,4 @@
use std::assert_matches::assert_matches;
use std::fmt;
use arrayvec::ArrayVec;
@ -389,7 +390,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
}
// Newtype vector of array, e.g. #[repr(simd)] struct S([i32; 4]);
(OperandValue::Immediate(llval), Abi::Aggregate { sized: true }) => {
assert!(matches!(self.layout.abi, Abi::Vector { .. }));
assert_matches!(self.layout.abi, Abi::Vector { .. });
let llfield_ty = bx.cx().backend_type(field);
@ -635,7 +636,24 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
self.codegen_consume(bx, place.as_ref())
}
mir::Operand::Constant(ref constant) => self.eval_mir_constant_to_operand(bx, constant),
mir::Operand::Constant(ref constant) => {
let constant_ty = self.monomorphize(constant.ty());
// Most SIMD vector constants should be passed as immediates.
// (In particular, some intrinsics really rely on this.)
if constant_ty.is_simd() {
// However, some SIMD types do not actually use the vector ABI
// (in particular, packed SIMD types do not). Ensure we exclude those.
let layout = bx.layout_of(constant_ty);
if let Abi::Vector { .. } = layout.abi {
let (llval, ty) = self.immediate_const_vector(bx, constant);
return OperandRef {
val: OperandValue::Immediate(llval),
layout: bx.layout_of(ty),
};
}
}
self.eval_mir_constant_to_operand(bx, constant)
}
}
}
}

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use arrayvec::ArrayVec;
use rustc_middle::ty::adjustment::PointerCoercion;
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
@ -220,7 +222,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
match operand.val {
OperandValue::Ref(source_place_val) => {
assert_eq!(source_place_val.llextra, None);
assert!(matches!(operand_kind, OperandValueKind::Ref));
assert_matches!(operand_kind, OperandValueKind::Ref);
Some(bx.load_operand(source_place_val.with_type(cast)).val)
}
OperandValue::ZeroSized => {

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
use rustc_middle::ty::layout::{HasParamEnv, TyAndLayout};
use rustc_middle::ty::{Instance, Ty};
@ -254,10 +256,10 @@ pub trait BuilderMethods<'a, 'tcx>:
} else {
(in_ty, dest_ty)
};
assert!(matches!(
assert_matches!(
self.cx().type_kind(float_ty),
TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::FP128
));
);
assert_eq!(self.cx().type_kind(int_ty), TypeKind::Integer);
if let Some(false) = self.cx().sess().opts.unstable_opts.saturating_float_casts {

View File

@ -30,6 +30,7 @@ pub trait ConstMethods<'tcx>: BackendTypes {
fn const_str(&self, s: &str) -> (Self::Value, Self::Value);
fn const_struct(&self, elts: &[Self::Value], packed: bool) -> Self::Value;
fn const_vector(&self, elts: &[Self::Value]) -> Self::Value;
fn const_to_opt_uint(&self, v: Self::Value) -> Option<u64>;
fn const_to_opt_u128(&self, v: Self::Value, sign_ext: bool) -> Option<u128>;

View File

@ -41,6 +41,8 @@ const_eval_const_context = {$kind ->
*[other] {""}
}
const_eval_const_stable = const-stable functions can only call other const-stable functions
const_eval_copy_nonoverlapping_overlapping =
`copy_nonoverlapping` called on overlapping ranges
@ -201,6 +203,9 @@ const_eval_invalid_vtable_pointer =
const_eval_invalid_vtable_trait =
using vtable for trait `{$vtable_trait}` but trait `{$expected_trait}` was expected
const_eval_lazy_lock =
consider wrapping this expression in `std::sync::LazyLock::new(|| ...)`
const_eval_live_drop =
destructor of `{$dropped_ty}` cannot be evaluated at compile-time
.label = the destructor for this type cannot be evaluated in {const_eval_const_context}s

View File

@ -1,5 +1,6 @@
//! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
use std::assert_matches::assert_matches;
use std::mem;
use std::ops::Deref;
@ -170,7 +171,7 @@ struct LocalReturnTyVisitor<'ck, 'mir, 'tcx> {
impl<'ck, 'mir, 'tcx> TypeVisitor<TyCtxt<'tcx>> for LocalReturnTyVisitor<'ck, 'mir, 'tcx> {
fn visit_ty(&mut self, t: Ty<'tcx>) {
match t.kind() {
ty::FnPtr(_) => {}
ty::FnPtr(..) => {}
ty::Ref(_, _, hir::Mutability::Mut) => {
self.checker.check_op(ops::mut_ref::MutRef(self.kind));
t.super_visit_with(self)
@ -590,7 +591,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
if is_int_bool_or_char(lhs_ty) && is_int_bool_or_char(rhs_ty) {
// Int, bool, and char operations are fine.
} else if lhs_ty.is_fn_ptr() || lhs_ty.is_unsafe_ptr() {
assert!(matches!(
assert_matches!(
op,
BinOp::Eq
| BinOp::Ne
@ -599,7 +600,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
| BinOp::Ge
| BinOp::Gt
| BinOp::Offset
));
);
self.check_op(ops::RawPtrComparison);
} else if lhs_ty.is_floating_point() || rhs_ty.is_floating_point() {
@ -725,7 +726,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
let (mut callee, mut fn_args) = match *fn_ty.kind() {
ty::FnDef(def_id, fn_args) => (def_id, fn_args),
ty::FnPtr(_) => {
ty::FnPtr(..) => {
self.check_op(ops::FnCallIndirect);
return;
}

View File

@ -23,7 +23,7 @@ use rustc_trait_selection::traits::SelectionContext;
use tracing::debug;
use super::ConstCx;
use crate::errors;
use crate::{errors, fluent_generated};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
@ -310,7 +310,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> {
}
if let ConstContext::Static(_) = ccx.const_kind() {
err.note("consider wrapping this expression in `std::sync::LazyLock::new(|| ...)`");
err.note(fluent_generated::const_eval_lazy_lock);
}
err
@ -334,7 +334,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallUnstable {
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
if ccx.is_const_stable_const_fn() {
err.help("const-stable functions can only call other const-stable functions");
err.help(fluent_generated::const_eval_const_stable);
} else if ccx.tcx.sess.is_nightly_build() {
if let Some(feature) = feature {
err.help(format!("add `#![feature({feature})]` to the crate attributes to enable"));
@ -605,8 +605,6 @@ impl<'tcx> NonConstOp<'tcx> for StaticAccess {
span,
format!("referencing statics in {}s is unstable", ccx.const_kind(),),
);
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
err
.note("`static` and `const` variables can refer to other `const` variables. A `const` variable, however, cannot refer to a `static` variable.")
.help("to fix this, the value can be extracted to a `const` and then used.");

View File

@ -226,7 +226,7 @@ pub(super) fn op_to_const<'tcx>(
let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap(); // `false` = no raw ptrs
debug_assert!(
matches!(
ecx.tcx.struct_tail_without_normalization(pointee_ty).kind(),
ecx.tcx.struct_tail_for_codegen(pointee_ty, ecx.param_env).kind(),
ty::Str | ty::Slice(..),
),
"`ConstValue::Slice` is for slice-tailed types only, but got {}",

View File

@ -132,7 +132,7 @@ fn const_to_valtree_inner<'tcx>(
// Technically we could allow function pointers (represented as `ty::Instance`), but this is not guaranteed to
// agree with runtime equality tests.
ty::FnPtr(_) => Err(ValTreeCreationError::NonSupportedType(ty)),
ty::FnPtr(..) => Err(ValTreeCreationError::NonSupportedType(ty)),
ty::Ref(_, _, _) => {
let derefd_place = ecx.deref_pointer(place)?;
@ -195,7 +195,7 @@ fn reconstruct_place_meta<'tcx>(
let mut last_valtree = valtree;
// Traverse the type, and update `last_valtree` as we go.
let tail = tcx.struct_tail_with_normalize(
let tail = tcx.struct_tail_raw(
layout.ty,
|ty| ty,
|| {
@ -353,7 +353,7 @@ pub fn valtree_to_const_value<'tcx>(
| ty::CoroutineClosure(..)
| ty::Coroutine(..)
| ty::CoroutineWitness(..)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Str
| ty::Slice(_)
| ty::Dynamic(..) => bug!("no ValTree should have been created for type {:?}", ty.kind()),

View File

@ -1,5 +1,6 @@
//! Manages calling a concrete function (with known MIR body) with argument passing,
//! and returning the return value to the caller.
use std::assert_matches::assert_matches;
use std::borrow::Cow;
use either::{Left, Right};
@ -557,7 +558,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
unwind,
)? {
assert!(!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden);
assert!(matches!(fallback.def, ty::InstanceKind::Item(_)));
assert_matches!(fallback.def, ty::InstanceKind::Item(_));
return self.init_fn_call(
FnVal::Instance(fallback),
(caller_abi, caller_fn_abi),

View File

@ -97,7 +97,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer) => {
let src = self.read_immediate(src)?;
match cast_ty.kind() {
ty::FnPtr(_) => {
ty::FnPtr(..) => {
// No change to value
self.write_immediate(*src, dest)?;
}
@ -230,7 +230,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
src: &ImmTy<'tcx, M::Provenance>,
cast_to: TyAndLayout<'tcx>,
) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
assert_matches!(src.layout.ty.kind(), ty::RawPtr(_, _) | ty::FnPtr(_));
assert_matches!(src.layout.ty.kind(), ty::RawPtr(_, _) | ty::FnPtr(..));
assert!(cast_to.ty.is_integral());
let scalar = src.to_scalar();
@ -400,6 +400,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
}
(ty::Dynamic(data_a, _, ty::Dyn), ty::Dynamic(data_b, _, ty::Dyn)) => {
let val = self.read_immediate(src)?;
// MIR building generates odd NOP casts, prevent them from causing unexpected trouble.
// See <https://github.com/rust-lang/rust/issues/128880>.
// FIXME: ideally we wouldn't have to do this.
if data_a == data_b {
return self.write_immediate(*val, dest);
}
// Take apart the old pointer, and find the dynamic type.
let (old_data, old_vptr) = val.to_scalar_pair();
let old_data = old_data.to_pointer(self)?;

View File

@ -2,6 +2,8 @@
//! looking at their MIR. Intrinsics/functions supported here are shared by CTFE
//! and miri.
use std::assert_matches::assert_matches;
use rustc_hir::def_id::DefId;
use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic};
use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout, ValidityRequirement};
@ -79,7 +81,7 @@ pub(crate) fn eval_nullary_intrinsic<'tcx>(
| ty::RawPtr(_, _)
| ty::Ref(_, _, _)
| ty::FnDef(_, _)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Dynamic(_, _, _)
| ty::Closure(_, _)
| ty::CoroutineClosure(_, _)
@ -510,7 +512,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
dest: &MPlaceTy<'tcx, M::Provenance>,
) -> InterpResult<'tcx> {
assert_eq!(a.layout.ty, b.layout.ty);
assert!(matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..)));
assert_matches!(a.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
// Performs an exact division, resulting in undefined behavior where
// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`.
@ -536,8 +538,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
r: &ImmTy<'tcx, M::Provenance>,
) -> InterpResult<'tcx, Scalar<M::Provenance>> {
assert_eq!(l.layout.ty, r.layout.ty);
assert!(matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..)));
assert!(matches!(mir_op, BinOp::Add | BinOp::Sub));
assert_matches!(l.layout.ty.kind(), ty::Int(..) | ty::Uint(..));
assert_matches!(mir_op, BinOp::Add | BinOp::Sub);
let (val, overflowed) =
self.binary_op(mir_op.wrapping_to_overflowing().unwrap(), l, r)?.to_scalar_pair();

View File

@ -19,7 +19,7 @@ use rustc_target::spec::abi::Abi as CallAbi;
use super::{
throw_unsup, throw_unsup_format, AllocBytes, AllocId, AllocKind, AllocRange, Allocation,
ConstAllocation, CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy,
MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance,
MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, CTFE_ALLOC_SALT,
};
/// Data returned by [`Machine::after_stack_pop`], and consumed by
@ -575,6 +575,14 @@ pub trait Machine<'tcx>: Sized {
{
eval(ecx, val, span, layout)
}
/// Returns the salt to be used for a deduplicated global alloation.
/// If the allocation is for a function, the instance is provided as well
/// (this lets Miri ensure unique addresses for some functions).
fn get_global_alloc_salt(
ecx: &InterpCx<'tcx, Self>,
instance: Option<ty::Instance<'tcx>>,
) -> usize;
}
/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
@ -677,4 +685,12 @@ pub macro compile_time_machine(<$tcx: lifetime>) {
let (prov, offset) = ptr.into_parts();
Some((prov.alloc_id(), offset, prov.immutable()))
}
#[inline(always)]
fn get_global_alloc_salt(
_ecx: &InterpCx<$tcx, Self>,
_instance: Option<ty::Instance<$tcx>>,
) -> usize {
CTFE_ALLOC_SALT
}
}

View File

@ -195,7 +195,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
pub fn fn_ptr(&mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>) -> Pointer<M::Provenance> {
let id = match fn_val {
FnVal::Instance(instance) => self.tcx.reserve_and_set_fn_alloc(instance),
FnVal::Instance(instance) => {
let salt = M::get_global_alloc_salt(self, Some(instance));
self.tcx.reserve_and_set_fn_alloc(instance, salt)
}
FnVal::Other(extra) => {
// FIXME(RalfJung): Should we have a cache here?
let id = self.tcx.reserve_alloc_id();

View File

@ -342,7 +342,7 @@ impl<'tcx, Prov: Provenance> ImmTy<'tcx, Prov> {
}
// extract fields from types with `ScalarPair` ABI
(Immediate::ScalarPair(a_val, b_val), Abi::ScalarPair(a, b)) => {
assert!(matches!(layout.abi, Abi::Scalar(..)));
assert_matches!(layout.abi, Abi::Scalar(..));
Immediate::from(if offset.bytes() == 0 {
debug_assert_eq!(layout.size, a.size(cx));
a_val

View File

@ -1008,7 +1008,8 @@ where
// Use cache for immutable strings.
let ptr = if mutbl.is_not() {
// Use dedup'd allocation function.
let id = tcx.allocate_bytes_dedup(str.as_bytes());
let salt = M::get_global_alloc_salt(self, None);
let id = tcx.allocate_bytes_dedup(str.as_bytes(), salt);
// Turn untagged "global" pointers (obtained via `tcx`) into the machine pointer to the allocation.
M::adjust_alloc_root_pointer(&self, Pointer::from(id), Some(kind))?

View File

@ -483,7 +483,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
| ty::Bool
| ty::Float(_)
| ty::FnDef(..)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::RawPtr(..)
| ty::Char
| ty::Ref(..)

View File

@ -424,7 +424,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
self.tcx.mk_type_list_from_iter(extra_args.iter().map(|arg| arg.layout().ty));
let (callee, fn_abi, with_caller_location) = match *func.layout.ty.kind() {
ty::FnPtr(_sig) => {
ty::FnPtr(..) => {
let fn_ptr = self.read_pointer(&func)?;
let fn_val = self.get_ptr_fn(fn_ptr)?;
(fn_val, self.fn_abi_of_fn_ptr(fn_sig_binder, extra_args)?, false)

View File

@ -28,7 +28,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
ensure_monomorphic_enough(*self.tcx, ty)?;
ensure_monomorphic_enough(*self.tcx, poly_trait_ref)?;
let vtable_symbolic_allocation = self.tcx.reserve_and_set_vtable_alloc(ty, poly_trait_ref);
let salt = M::get_global_alloc_salt(self, None);
let vtable_symbolic_allocation =
self.tcx.reserve_and_set_vtable_alloc(ty, poly_trait_ref, salt);
let vtable_ptr = self.global_root_pointer(Pointer::from(vtable_symbolic_allocation))?;
Ok(vtable_ptr.into())
}

View File

@ -616,7 +616,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
self.check_safe_pointer(value, PointerKind::Ref(*mutbl))?;
Ok(true)
}
ty::FnPtr(_sig) => {
ty::FnPtr(..) => {
let value = self.read_scalar(value, ExpectedKind::FnPtr)?;
// If we check references recursively, also check that this points to a function.

View File

@ -35,7 +35,7 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
| ty::Slice(_)
| ty::RawPtr(_, _)
| ty::Ref(_, _, _)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Never
| ty::Tuple(_)
| ty::Dynamic(_, _, _) => self.pretty_print_type(ty),

View File

@ -8,6 +8,7 @@
//! Typical examples would include: minimum element in SCC, maximum element
//! reachable from it, etc.
use std::assert_matches::debug_assert_matches;
use std::fmt::Debug;
use std::ops::Range;
@ -569,7 +570,7 @@ where
// This None marks that we still have the initialize this node's frame.
debug!(?depth, ?node);
debug_assert!(matches!(self.node_states[node], NodeState::NotVisited));
debug_assert_matches!(self.node_states[node], NodeState::NotVisited);
// Push `node` onto the stack.
self.node_states[node] = NodeState::BeingVisited {

View File

@ -18,6 +18,7 @@
#![feature(array_windows)]
#![feature(ascii_char)]
#![feature(ascii_char_variants)]
#![feature(assert_matches)]
#![feature(auto_traits)]
#![feature(cfg_match)]
#![feature(core_intrinsics)]

View File

@ -10,6 +10,7 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(array_windows)]
#![feature(assert_matches)]
#![feature(associated_type_defaults)]
#![feature(box_into_inner)]
#![feature(box_patterns)]
@ -28,6 +29,7 @@
extern crate self as rustc_errors;
use std::assert_matches::assert_matches;
use std::backtrace::{Backtrace, BacktraceStatus};
use std::borrow::Cow;
use std::cell::Cell;
@ -1490,7 +1492,7 @@ impl DiagCtxtInner {
// Future breakages aren't emitted if they're `Level::Allow` or
// `Level::Expect`, but they still need to be constructed and
// stashed below, so they'll trigger the must_produce_diag check.
assert!(matches!(diagnostic.level, Error | Warning | Allow | Expect(_)));
assert_matches!(diagnostic.level, Error | Warning | Allow | Expect(_));
self.future_breakage_diagnostics.push(diagnostic.clone());
}
@ -1835,23 +1837,23 @@ impl DelayedDiagInner {
}
}
/// Level is_error EmissionGuarantee Top-level Sub Used in lints?
/// ----- -------- ----------------- --------- --- --------------
/// Bug yes BugAbort yes - -
/// Fatal yes FatalAbort/FatalError(*) yes - -
/// Error yes ErrorGuaranteed yes - yes
/// DelayedBug yes ErrorGuaranteed yes - -
/// ForceWarning - () yes - lint-only
/// Warning - () yes yes yes
/// Note - () rare yes -
/// OnceNote - () - yes lint-only
/// Help - () rare yes -
/// OnceHelp - () - yes lint-only
/// FailureNote - () rare - -
/// Allow - () yes - lint-only
/// Expect - () yes - lint-only
/// | Level | is_error | EmissionGuarantee | Top-level | Sub | Used in lints?
/// | ----- | -------- | ----------------- | --------- | --- | --------------
/// | Bug | yes | BugAbort | yes | - | -
/// | Fatal | yes | FatalAbort/FatalError[^star] | yes | - | -
/// | Error | yes | ErrorGuaranteed | yes | - | yes
/// | DelayedBug | yes | ErrorGuaranteed | yes | - | -
/// | ForceWarning | - | () | yes | - | lint-only
/// | Warning | - | () | yes | yes | yes
/// | Note | - | () | rare | yes | -
/// | OnceNote | - | () | - | yes | lint-only
/// | Help | - | () | rare | yes | -
/// | OnceHelp | - | () | - | yes | lint-only
/// | FailureNote | - | () | rare | - | -
/// | Allow | - | () | yes | - | lint-only
/// | Expect | - | () | yes | - | lint-only
///
/// (*) `FatalAbort` normally, `FatalError` in the non-aborting "almost fatal" case that is
/// [^star]: `FatalAbort` normally, `FatalError` in the non-aborting "almost fatal" case that is
/// occasionally used.
///
#[derive(Copy, PartialEq, Eq, Clone, Hash, Debug, Encodable, Decodable)]

View File

@ -129,6 +129,9 @@ expand_module_multiple_candidates =
expand_must_repeat_once =
this must repeat at least once
expand_non_inline_modules_in_proc_macro_input_are_unstable =
non-inline modules in proc macro input are unstable
expand_not_a_meta_item =
not a meta item

View File

@ -1398,8 +1398,6 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) {
};
if crate_matches {
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
sess.dcx().emit_fatal(errors::ProcMacroBackCompat {
crate_name: "rental".to_string(),
fixed_version: "0.5.6".to_string(),

View File

@ -39,6 +39,7 @@ use crate::errors::{
RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue,
WrongFragmentKind,
};
use crate::fluent_generated;
use crate::mbe::diagnostics::annotate_err_with_kind;
use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod};
use crate::placeholders::{placeholder, PlaceholderExpander};
@ -882,7 +883,6 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
}
impl<'ast, 'a> Visitor<'ast> for GateProcMacroInput<'a> {
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn visit_item(&mut self, item: &'ast ast::Item) {
match &item.kind {
ItemKind::Mod(_, mod_kind)
@ -892,7 +892,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
self.sess,
sym::proc_macro_hygiene,
item.span,
"non-inline modules in proc macro input are unstable",
fluent_generated::expand_non_inline_modules_in_proc_macro_input_are_unstable,
)
.emit();
}
@ -1876,7 +1876,6 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
// Detect use of feature-gated or invalid attributes on macro invocations
// since they will not be detected after macro expansion.
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) {
let features = self.cx.ecfg.features;
let mut attrs = attrs.iter().peekable();

View File

@ -60,6 +60,8 @@ declare_features! (
(accepted, adx_target_feature, "1.61.0", Some(44839)),
/// Allows explicit discriminants on non-unit enum variants.
(accepted, arbitrary_enum_discriminant, "1.66.0", Some(60553)),
/// Allows using `const` operands in inline assembly.
(accepted, asm_const, "CURRENT_RUSTC_VERSION", Some(93332)),
/// Allows using `sym` operands in inline assembly.
(accepted, asm_sym, "1.66.0", Some(93333)),
/// Allows the definition of associated constants in `trait` or `impl` blocks.

View File

@ -643,8 +643,8 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
through unstable paths"
),
rustc_attr!(
rustc_deprecated_safe_2024, Normal, template!(Word), WarnFollowing,
EncodeCrossCrate::Yes,
rustc_deprecated_safe_2024, Normal, template!(List: r#"audit_that = "...""#),
ErrorFollowing, EncodeCrossCrate::Yes,
"rustc_deprecated_safe_2024 is supposed to be used in libstd only",
),

View File

@ -348,8 +348,6 @@ declare_features! (
(unstable, alloc_error_handler, "1.29.0", Some(51540)),
/// Allows trait methods with arbitrary self types.
(unstable, arbitrary_self_types, "1.23.0", Some(44874)),
/// Allows using `const` operands in inline assembly.
(unstable, asm_const, "1.58.0", Some(93332)),
/// Enables experimental inline assembly support for additional architectures.
(unstable, asm_experimental_arch, "1.58.0", Some(93335)),
/// Allows using `label` operands in inline assembly.

View File

@ -1,3 +1,5 @@
use std::assert_matches::debug_assert_matches;
use rustc_ast::InlineAsmTemplatePiece;
use rustc_data_structures::fx::FxIndexSet;
use rustc_hir::{self as hir, LangItem};
@ -66,7 +68,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
ty::Float(FloatTy::F32) => Some(InlineAsmType::F32),
ty::Float(FloatTy::F64) => Some(InlineAsmType::F64),
ty::Float(FloatTy::F128) => Some(InlineAsmType::F128),
ty::FnPtr(_) => Some(asm_ty_isize),
ty::FnPtr(..) => Some(asm_ty_isize),
ty::RawPtr(ty, _) if self.is_thin_ptr_ty(ty) => Some(asm_ty_isize),
ty::Adt(adt, args) if adt.repr().simd() => {
let fields = &adt.non_enum_variant().fields;
@ -457,17 +459,17 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
}
// Typeck has checked that Const operands are integers.
hir::InlineAsmOperand::Const { anon_const } => {
debug_assert!(matches!(
debug_assert_matches!(
self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(),
ty::Error(_) | ty::Int(_) | ty::Uint(_)
));
);
}
// Typeck has checked that SymFn refers to a function.
hir::InlineAsmOperand::SymFn { anon_const } => {
debug_assert!(matches!(
debug_assert_matches!(
self.tcx.type_of(anon_const.def_id).instantiate_identity().kind(),
ty::Error(_) | ty::FnDef(..)
));
);
}
// AST lowering guarantees that SymStatic points to a static.
hir::InlineAsmOperand::SymStatic { .. } => {}

View File

@ -951,7 +951,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) -> Result<(),
} else {
let mut diag = match ty.kind() {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Error(_) => return Ok(()),
ty::FnPtr(_) => tcx.dcx().struct_span_err(
ty::FnPtr(..) => tcx.dcx().struct_span_err(
hir_ty.span,
"using function pointers as const generic parameters is forbidden",
),

View File

@ -1,6 +1,7 @@
//! Check properties that are required by built-in traits and set
//! up data structures required by type-checking/codegen.
use std::assert_matches::assert_matches;
use std::collections::BTreeMap;
use rustc_data_structures::fx::FxHashSet;
@ -129,7 +130,7 @@ fn visit_implementation_of_const_param_ty(
checker: &Checker<'_>,
kind: LangItem,
) -> Result<(), ErrorGuaranteed> {
assert!(matches!(kind, LangItem::ConstParamTy | LangItem::UnsizedConstParamTy));
assert_matches!(kind, LangItem::ConstParamTy | LangItem::UnsizedConstParamTy);
let tcx = checker.tcx;
let header = checker.impl_header;

View File

@ -172,7 +172,7 @@ impl<'tcx> InherentCollect<'tcx> {
| ty::RawPtr(_, _)
| ty::Ref(..)
| ty::Never
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Tuple(..) => self.check_primitive_impl(id, self_ty),
ty::Alias(ty::Projection | ty::Inherent | ty::Opaque, _) | ty::Param(_) => {
Err(self.tcx.dcx().emit_err(errors::InherentNominal { span: item_span }))

View File

@ -1700,6 +1700,8 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTrai
trait_ref: ty::EarlyBinder::bind(trait_ref),
safety: impl_.safety,
polarity: polarity_of_impl(tcx, def_id, impl_, item.span),
do_not_recommend: tcx.features().do_not_recommend
&& tcx.has_attrs_with_path(def_id, &[sym::diagnostic, sym::do_not_recommend]),
}
})
}

View File

@ -1,3 +1,4 @@
use std::assert_matches::assert_matches;
use std::ops::ControlFlow;
use hir::intravisit::{self, Visitor};
@ -207,9 +208,9 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
..
}) => {
if in_trait {
assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn))
assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn);
} else {
assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn))
assert_matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn);
}
Some(fn_def_id.to_def_id())
}
@ -218,9 +219,9 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
..
}) => {
if in_assoc_ty {
assert!(matches!(tcx.def_kind(parent), DefKind::AssocTy));
assert_matches!(tcx.def_kind(parent), DefKind::AssocTy);
} else {
assert!(matches!(tcx.def_kind(parent), DefKind::TyAlias));
assert_matches!(tcx.def_kind(parent), DefKind::TyAlias);
}
debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent);
// Opaque types are always nested within another item, and

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use hir::{HirId, Node};
use rustc_data_structures::fx::FxIndexSet;
use rustc_hir as hir;
@ -601,7 +603,7 @@ pub(super) fn implied_predicates_with_filter(
let Some(trait_def_id) = trait_def_id.as_local() else {
// if `assoc_name` is None, then the query should've been redirected to an
// external provider
assert!(matches!(filter, PredicateFilter::SelfThatDefines(_)));
assert_matches!(filter, PredicateFilter::SelfThatDefines(_));
return tcx.explicit_super_predicates_of(trait_def_id);
};

View File

@ -1,3 +1,5 @@
use std::assert_matches::debug_assert_matches;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
@ -63,7 +65,7 @@ enum FnKind {
}
fn fn_kind<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> FnKind {
debug_assert!(matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn));
debug_assert_matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn);
let parent = tcx.parent(def_id);
match tcx.def_kind(parent) {

View File

@ -8,6 +8,8 @@
//! specialization errors. These things can (and probably should) be
//! fixed, but for the moment it's easier to do these checks early.
use std::assert_matches::debug_assert_matches;
use min_specialization::check_min_specialization;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::codes::*;
@ -54,7 +56,7 @@ mod min_specialization;
pub fn check_impl_wf(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
let min_specialization = tcx.features().min_specialization;
let mut res = Ok(());
debug_assert!(matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. }));
debug_assert_matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. });
res = res.and(enforce_impl_params_are_constrained(tcx, impl_def_id));
if min_specialization {
res = res.and(check_min_specialization(tcx, impl_def_id));

View File

@ -62,6 +62,7 @@ This API is completely unstable and subject to change.
#![allow(rustc::untranslatable_diagnostic)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(control_flow_enum)]
#![feature(if_let_guard)]
#![feature(iter_intersperse)]

View File

@ -317,8 +317,8 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
self.add_constraint(current, data.index, variance);
}
ty::FnPtr(sig) => {
self.add_constraints_from_sig(current, sig, variance);
ty::FnPtr(sig_tys, hdr) => {
self.add_constraints_from_sig(current, sig_tys.with(hdr), variance);
}
ty::Error(_) => {

View File

@ -137,7 +137,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// If the callee is a bare function or a closure, then we're all set.
match *adjusted_ty.kind() {
ty::FnDef(..) | ty::FnPtr(_) => {
ty::FnDef(..) | ty::FnPtr(..) => {
let adjustments = self.adjust_steps(autoderef);
self.apply_adjustments(callee_expr, adjustments);
return Some(CallStep::Builtin(adjusted_ty));
@ -467,7 +467,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(fn_sig, Some(def_id))
}
// FIXME(effects): these arms should error because we can't enforce them
ty::FnPtr(sig) => (sig, None),
ty::FnPtr(sig_tys, hdr) => (sig_tys.with(hdr), None),
_ => {
for arg in arg_exprs {
self.check_expr(arg);

View File

@ -97,6 +97,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
return Ok(Some(PointerKind::Thin));
}
let t = self.try_structurally_resolve_type(span, t);
Ok(match *t.kind() {
ty::Slice(_) | ty::Str => Some(PointerKind::Length),
ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty)),

View File

@ -160,15 +160,11 @@ pub(super) fn check_fn<'a, 'tcx>(
fcx.demand_suptype(span, ret_ty, actual_return_ty);
// Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !`
if let Some(panic_impl_did) = tcx.lang_items().panic_impl()
&& panic_impl_did == fn_def_id.to_def_id()
{
check_panic_info_fn(tcx, panic_impl_did.expect_local(), fn_sig);
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::PanicImpl) {
check_panic_info_fn(tcx, fn_def_id, fn_sig);
}
if let Some(lang_start_defid) = tcx.lang_items().start_fn()
&& lang_start_defid == fn_def_id.to_def_id()
{
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::Start) {
check_lang_start_fn(tcx, fn_sig, fn_def_id);
}

View File

@ -336,9 +336,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.into_iter()
.map(|obl| (obl.predicate, obl.cause.span)),
),
ty::FnPtr(sig) => match closure_kind {
ty::FnPtr(sig_tys, hdr) => match closure_kind {
hir::ClosureKind::Closure => {
let expected_sig = ExpectedSig { cause_span: None, sig };
let expected_sig = ExpectedSig { cause_span: None, sig: sig_tys.with(hdr) };
(Some(expected_sig), Some(ty::ClosureKind::Fn))
}
hir::ClosureKind::Coroutine(_) | hir::ClosureKind::CoroutineClosure(_) => {

View File

@ -137,7 +137,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
at.lub(DefineOpaqueTypes::Yes, b, a)
} else {
at.sup(DefineOpaqueTypes::Yes, b, a)
.map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
.map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
};
// In the new solver, lazy norm may allow us to shallowly equate
@ -225,10 +225,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// items to drop the unsafe qualifier.
self.coerce_from_fn_item(a, b)
}
ty::FnPtr(a_f) => {
ty::FnPtr(a_sig_tys, a_hdr) => {
// We permit coercion of fn pointers to drop the
// unsafe qualifier.
self.coerce_from_fn_pointer(a, a_f, b)
self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
}
ty::Closure(closure_def_id_a, args_a) => {
// Non-capturing closures are coercible to
@ -788,9 +788,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
self.commit_if_ok(|snapshot| {
let outer_universe = self.infcx.universe();
let result = if let ty::FnPtr(fn_ty_b) = b.kind()
&& let (hir::Safety::Safe, hir::Safety::Unsafe) =
(fn_ty_a.safety(), fn_ty_b.safety())
let result = if let ty::FnPtr(_, hdr_b) = b.kind()
&& let (hir::Safety::Safe, hir::Safety::Unsafe) = (fn_ty_a.safety(), hdr_b.safety)
{
let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
self.unify_and(unsafe_a, b, to_unsafe)
@ -842,7 +841,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
match b.kind() {
ty::FnPtr(b_sig) => {
ty::FnPtr(_, b_hdr) => {
let a_sig = a.fn_sig(self.tcx);
if let ty::FnDef(def_id, _) = *a.kind() {
// Intrinsics are not coercible to function pointers
@ -852,7 +851,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
if b_sig.safety() == hir::Safety::Safe
if b_hdr.safety == hir::Safety::Safe
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
{
return Err(TypeError::TargetFeatureCast(def_id));
@ -910,7 +909,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
//
// All we care here is if any variable is being captured and not the exact paths,
// so we check `upvars_mentioned` for root variables being captured.
ty::FnPtr(fn_ty)
ty::FnPtr(_, hdr)
if self
.tcx
.upvars_mentioned(closure_def_id_a.expect_local())
@ -923,7 +922,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// or
// `unsafe fn(arg0,arg1,...) -> _`
let closure_sig = args_a.as_closure().sig();
let safety = fn_ty.safety();
let safety = hdr.safety;
let pointer_ty =
Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, safety));
debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);

View File

@ -70,7 +70,8 @@ impl<'a, 'tcx> Expectation<'tcx> {
/// See the test case `test/ui/coerce-expect-unsized.rs` and #20169
/// for examples of where this comes up,.
pub(super) fn rvalue_hint(fcx: &FnCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
match fcx.tcx.struct_tail_without_normalization(ty).kind() {
// FIXME: This is not right, even in the old solver...
match fcx.tcx.struct_tail_raw(ty, |ty| ty, || {}).kind() {
ty::Slice(_) | ty::Str | ty::Dynamic(..) => ExpectRvalueLikeUnsized(ty),
_ => ExpectHasType(ty),
}

View File

@ -404,7 +404,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
code: traits::ObligationCauseCode<'tcx>,
) {
if !ty.references_error() {
let tail = self.tcx.struct_tail_with_normalize(
let tail = self.tcx.struct_tail_raw(
ty,
|ty| {
if self.next_trait_solver() {

View File

@ -1530,7 +1530,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ty::Int(_) | ty::Uint(_) => Some(ty),
ty::Char => Some(tcx.types.u8),
ty::RawPtr(..) => Some(tcx.types.usize),
ty::FnDef(..) | ty::FnPtr(_) => Some(tcx.types.usize),
ty::FnDef(..) | ty::FnPtr(..) => Some(tcx.types.usize),
_ => None,
});
opt_ty.unwrap_or_else(|| self.next_int_var())

View File

@ -604,7 +604,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expected: Ty<'tcx>,
found: Ty<'tcx>,
) -> bool {
if let (ty::FnPtr(_), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
if let (ty::FnPtr(..), ty::Closure(def_id, _)) = (expected.kind(), found.kind()) {
if let Some(upvars) = self.tcx.upvars_mentioned(*def_id) {
// Report upto four upvars being captured to reduce the amount error messages
// reported back to the user.

View File

@ -50,7 +50,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Not all of these (e.g., unsafe fns) implement `FnOnce`,
// so we look for these beforehand.
// FIXME(async_closures): These don't impl `FnOnce` by default.
ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true,
ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(..) => true,
// If it's not a simple function, look for things which implement `FnOnce`.
_ => {
let Some(fn_once) = tcx.lang_items().fn_once_trait() else {

View File

@ -438,7 +438,7 @@ impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for Canonicalizer<'cx, 'tcx> {
| ty::RawPtr(..)
| ty::Ref(..)
| ty::FnDef(..)
| ty::FnPtr(_)
| ty::FnPtr(..)
| ty::Dynamic(..)
| ty::Never
| ty::Tuple(..)

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use rustc_middle::ty::{self, OutlivesPredicate, Ty, TyCtxt};
use rustc_type_ir::outlives::{compute_alias_components_recursive, Component};
use smallvec::smallvec;
@ -181,7 +183,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
&self,
generic_ty: Ty<'tcx>,
) -> Vec<ty::PolyTypeOutlivesPredicate<'tcx>> {
assert!(matches!(generic_ty.kind(), ty::Param(_) | ty::Placeholder(_)));
assert_matches!(generic_ty.kind(), ty::Param(_) | ty::Placeholder(_));
self.declared_generic_bounds_from_env_for_erased_ty(generic_ty)
}

View File

@ -18,6 +18,7 @@
#![allow(rustc::untranslatable_diagnostic)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(control_flow_enum)]
#![feature(extend_one)]

View File

@ -386,7 +386,6 @@ fn get_codegen_sysroot(
}
}
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
pub(crate) fn check_attr_crate_type(
sess: &Session,
attrs: &[ast::Attribute],

View File

@ -1,5 +1,5 @@
use hir::{Expr, Pat};
use rustc_hir as hir;
use rustc_hir::{self as hir, LangItem};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::ObligationCause;
use rustc_middle::ty;
@ -126,7 +126,10 @@ fn extract_iterator_next_call<'tcx>(
) -> Option<&'tcx Expr<'tcx>> {
// This won't work for `Iterator::next(iter)`, is this an issue?
if let hir::ExprKind::MethodCall(_, recv, _, _) = expr.kind
&& cx.typeck_results().type_dependent_def_id(expr.hir_id) == cx.tcx.lang_items().next_fn()
&& cx
.typeck_results()
.type_dependent_def_id(expr.hir_id)
.is_some_and(|def_id| cx.tcx.is_lang_item(def_id, LangItem::IteratorNext))
{
Some(recv)
} else {

View File

@ -717,7 +717,6 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
};
}
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn add(&mut self, attrs: &[ast::Attribute], is_crate_node: bool, source_hir_id: Option<HirId>) {
let sess = self.sess;
for (attr_index, attr) in attrs.iter().enumerate() {
@ -1039,7 +1038,6 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS);
// FIXME: make this translatable
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
lint_level(self.sess, lint, level, src, Some(span.into()), |lint| {
lint.primary_message(fluent::lint_unknown_gated_lint);
lint.arg("name", lint_id.lint.name_lower());

View File

@ -114,7 +114,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints {
let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { return };
for (bound, modifier) in &bounds[..] {
let def_id = bound.trait_ref.trait_def_id();
if cx.tcx.lang_items().drop_trait() == def_id
if def_id.is_some_and(|def_id| cx.tcx.is_lang_item(def_id, LangItem::Drop))
&& *modifier != hir::TraitBoundModifier::Maybe
{
let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return };

View File

@ -1022,7 +1022,7 @@ fn ty_is_known_nonnull<'tcx>(
let ty = tcx.try_normalize_erasing_regions(param_env, ty).unwrap_or(ty);
match ty.kind() {
ty::FnPtr(_) => true,
ty::FnPtr(..) => true,
ty::Ref(..) => true,
ty::Adt(def, _) if def.is_box() && matches!(mode, CItemKind::Definition) => true,
ty::Adt(def, args) if def.repr().transparent() && !def.is_union() => {
@ -1473,7 +1473,8 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
ty::Array(inner_ty, _) => self.check_type_for_ffi(cache, inner_ty),
ty::FnPtr(sig) => {
ty::FnPtr(sig_tys, hdr) => {
let sig = sig_tys.with(hdr);
if self.is_internal_abi(sig.abi()) {
return FfiUnsafe {
ty,
@ -1709,8 +1710,8 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
type Result = ControlFlow<Ty<'tcx>>;
fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
if let ty::FnPtr(sig) = ty.kind()
&& !self.visitor.is_internal_abi(sig.abi())
if let ty::FnPtr(_, hdr) = ty.kind()
&& !self.visitor.is_internal_abi(hdr.abi)
{
self.tys.push(ty);
}

View File

@ -397,6 +397,18 @@ LLVMRustCreateAllocSizeAttr(LLVMContextRef C, uint32_t ElementSizeArg) {
std::nullopt));
}
extern "C" LLVMAttributeRef
LLVMRustCreateRangeAttribute(LLVMContextRef C, unsigned NumBits,
const uint64_t LowerWords[],
const uint64_t UpperWords[]) {
#if LLVM_VERSION_GE(19, 0)
return LLVMCreateConstantRangeAttribute(C, Attribute::Range, NumBits,
LowerWords, UpperWords);
#else
report_fatal_error("LLVM 19.0 is required for Range Attribute");
#endif
}
// These values **must** match ffi::AllocKindFlags.
// It _happens_ to match the LLVM values of llvm::AllocFnKind,
// but that's happenstance and we do explicit conversions before

View File

@ -134,12 +134,18 @@ metadata_lib_framework_apple =
metadata_lib_required =
crate `{$crate_name}` required to be available in {$kind} format, but was not found in this form
metadata_link_arg_unstable =
link kind `link-arg` is unstable
metadata_link_cfg_form =
link cfg must be of the form `cfg(/* predicate */)`
metadata_link_cfg_single_predicate =
link cfg must have a single predicate argument
metadata_link_cfg_unstable =
link cfg is unstable
metadata_link_framework_apple =
link kind `framework` is only supported on Apple targets

View File

@ -949,7 +949,6 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
}
}
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn report_unused_deps(&mut self, krate: &ast::Crate) {
// Make a point span rather than covering the whole file
let span = krate.spans.inner_span.shrink_to_lo();

View File

@ -17,7 +17,7 @@ use rustc_span::def_id::{DefId, LOCAL_CRATE};
use rustc_span::symbol::{sym, Symbol};
use rustc_target::spec::abi::Abi;
use crate::errors;
use crate::{errors, fluent_generated};
pub fn find_native_static_library(name: &str, verbatim: bool, sess: &Session) -> PathBuf {
let formats = if verbatim {
@ -87,7 +87,6 @@ struct Collector<'tcx> {
}
impl<'tcx> Collector<'tcx> {
#[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable
fn process_module(&mut self, module: &ForeignModule) {
let ForeignModule { def_id, abi, ref foreign_items } = *module;
let def_id = def_id.expect_local();
@ -161,7 +160,7 @@ impl<'tcx> Collector<'tcx> {
sess,
sym::link_arg_attribute,
span,
"link kind `link-arg` is unstable",
fluent_generated::metadata_link_arg_unstable,
)
.emit();
}
@ -201,8 +200,13 @@ impl<'tcx> Collector<'tcx> {
continue;
};
if !features.link_cfg {
feature_err(sess, sym::link_cfg, item.span(), "link cfg is unstable")
.emit();
feature_err(
sess,
sym::link_cfg,
item.span(),
fluent_generated::metadata_link_cfg_unstable,
)
.emit();
}
cfg = Some(link_cfg.clone());
}
@ -266,6 +270,8 @@ impl<'tcx> Collector<'tcx> {
macro report_unstable_modifier($feature: ident) {
if !features.$feature {
// FIXME: make this translatable
#[expect(rustc::untranslatable_diagnostic)]
feature_err(
sess,
sym::$feature,

View File

@ -13,7 +13,6 @@ use std::num::NonZero;
use std::{fmt, io};
use rustc_ast::LitKind;
use rustc_attr::InlineAttr;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lock;
use rustc_errors::ErrorGuaranteed;
@ -46,7 +45,7 @@ pub use self::pointer::{CtfeProvenance, Pointer, PointerArithmetic, Provenance};
pub use self::value::Scalar;
use crate::mir;
use crate::ty::codec::{TyDecoder, TyEncoder};
use crate::ty::{self, GenericArgKind, Instance, Ty, TyCtxt};
use crate::ty::{self, Instance, Ty, TyCtxt};
/// Uniquely identifies one of the following:
/// - A constant
@ -126,11 +125,10 @@ pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>>(
AllocDiscriminant::Alloc.encode(encoder);
alloc.encode(encoder);
}
GlobalAlloc::Function { instance, unique } => {
GlobalAlloc::Function { instance } => {
trace!("encoding {:?} with {:#?}", alloc_id, instance);
AllocDiscriminant::Fn.encode(encoder);
instance.encode(encoder);
unique.encode(encoder);
}
GlobalAlloc::VTable(ty, poly_trait_ref) => {
trace!("encoding {:?} with {ty:#?}, {poly_trait_ref:#?}", alloc_id);
@ -219,38 +217,32 @@ impl<'s> AllocDecodingSession<'s> {
}
// Now decode the actual data.
let alloc_id = decoder.with_position(pos, |decoder| {
match alloc_kind {
AllocDiscriminant::Alloc => {
trace!("creating memory alloc ID");
let alloc = <ConstAllocation<'tcx> as Decodable<_>>::decode(decoder);
trace!("decoded alloc {:?}", alloc);
decoder.interner().reserve_and_set_memory_alloc(alloc)
}
AllocDiscriminant::Fn => {
trace!("creating fn alloc ID");
let instance = ty::Instance::decode(decoder);
trace!("decoded fn alloc instance: {:?}", instance);
let unique = bool::decode(decoder);
// Here we cannot call `reserve_and_set_fn_alloc` as that would use a query, which
// is not possible in this context. That's why the allocation stores
// whether it is unique or not.
decoder.interner().reserve_and_set_fn_alloc_internal(instance, unique)
}
AllocDiscriminant::VTable => {
trace!("creating vtable alloc ID");
let ty = <Ty<'_> as Decodable<D>>::decode(decoder);
let poly_trait_ref =
<Option<ty::PolyExistentialTraitRef<'_>> as Decodable<D>>::decode(decoder);
trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}");
decoder.interner().reserve_and_set_vtable_alloc(ty, poly_trait_ref)
}
AllocDiscriminant::Static => {
trace!("creating extern static alloc ID");
let did = <DefId as Decodable<D>>::decode(decoder);
trace!("decoded static def-ID: {:?}", did);
decoder.interner().reserve_and_set_static_alloc(did)
}
let alloc_id = decoder.with_position(pos, |decoder| match alloc_kind {
AllocDiscriminant::Alloc => {
trace!("creating memory alloc ID");
let alloc = <ConstAllocation<'tcx> as Decodable<_>>::decode(decoder);
trace!("decoded alloc {:?}", alloc);
decoder.interner().reserve_and_set_memory_alloc(alloc)
}
AllocDiscriminant::Fn => {
trace!("creating fn alloc ID");
let instance = ty::Instance::decode(decoder);
trace!("decoded fn alloc instance: {:?}", instance);
decoder.interner().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT)
}
AllocDiscriminant::VTable => {
trace!("creating vtable alloc ID");
let ty = <Ty<'_> as Decodable<D>>::decode(decoder);
let poly_trait_ref =
<Option<ty::PolyExistentialTraitRef<'_>> as Decodable<D>>::decode(decoder);
trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}");
decoder.interner().reserve_and_set_vtable_alloc(ty, poly_trait_ref, CTFE_ALLOC_SALT)
}
AllocDiscriminant::Static => {
trace!("creating extern static alloc ID");
let did = <DefId as Decodable<D>>::decode(decoder);
trace!("decoded static def-ID: {:?}", did);
decoder.interner().reserve_and_set_static_alloc(did)
}
});
@ -265,12 +257,7 @@ impl<'s> AllocDecodingSession<'s> {
#[derive(Debug, Clone, Eq, PartialEq, Hash, TyDecodable, TyEncodable, HashStable)]
pub enum GlobalAlloc<'tcx> {
/// The alloc ID is used as a function pointer.
Function {
instance: Instance<'tcx>,
/// Stores whether this instance is unique, i.e. all pointers to this function use the same
/// alloc ID.
unique: bool,
},
Function { instance: Instance<'tcx> },
/// This alloc ID points to a symbolic (not-reified) vtable.
VTable(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>),
/// The alloc ID points to a "lazy" static variable that did not get computed (yet).
@ -323,14 +310,17 @@ impl<'tcx> GlobalAlloc<'tcx> {
}
}
pub const CTFE_ALLOC_SALT: usize = 0;
pub(crate) struct AllocMap<'tcx> {
/// Maps `AllocId`s to their corresponding allocations.
alloc_map: FxHashMap<AllocId, GlobalAlloc<'tcx>>,
/// Used to ensure that statics and functions only get one associated `AllocId`.
//
// FIXME: Should we just have two separate dedup maps for statics and functions each?
dedup: FxHashMap<GlobalAlloc<'tcx>, AllocId>,
/// Used to deduplicate global allocations: functions, vtables, string literals, ...
///
/// The `usize` is a "salt" used by Miri to make deduplication imperfect, thus better emulating
/// the actual guarantees.
dedup: FxHashMap<(GlobalAlloc<'tcx>, usize), AllocId>,
/// The `AllocId` to assign to the next requested ID.
/// Always incremented; never gets smaller.
@ -368,74 +358,40 @@ impl<'tcx> TyCtxt<'tcx> {
/// Reserves a new ID *if* this allocation has not been dedup-reserved before.
/// Should not be used for mutable memory.
fn reserve_and_set_dedup(self, alloc: GlobalAlloc<'tcx>) -> AllocId {
fn reserve_and_set_dedup(self, alloc: GlobalAlloc<'tcx>, salt: usize) -> AllocId {
let mut alloc_map = self.alloc_map.lock();
if let GlobalAlloc::Memory(mem) = alloc {
if mem.inner().mutability.is_mut() {
bug!("trying to dedup-reserve mutable memory");
}
}
if let Some(&alloc_id) = alloc_map.dedup.get(&alloc) {
let alloc_salt = (alloc, salt);
if let Some(&alloc_id) = alloc_map.dedup.get(&alloc_salt) {
return alloc_id;
}
let id = alloc_map.reserve();
debug!("creating alloc {alloc:?} with id {id:?}");
alloc_map.alloc_map.insert(id, alloc.clone());
alloc_map.dedup.insert(alloc, id);
debug!("creating alloc {:?} with id {id:?}", alloc_salt.0);
alloc_map.alloc_map.insert(id, alloc_salt.0.clone());
alloc_map.dedup.insert(alloc_salt, id);
id
}
/// Generates an `AllocId` for a memory allocation. If the exact same memory has been
/// allocated before, this will return the same `AllocId`.
pub fn reserve_and_set_memory_dedup(self, mem: ConstAllocation<'tcx>) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::Memory(mem))
pub fn reserve_and_set_memory_dedup(self, mem: ConstAllocation<'tcx>, salt: usize) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::Memory(mem), salt)
}
/// Generates an `AllocId` for a static or return a cached one in case this function has been
/// called on the same static before.
pub fn reserve_and_set_static_alloc(self, static_id: DefId) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::Static(static_id))
let salt = 0; // Statics have a guaranteed unique address, no salt added.
self.reserve_and_set_dedup(GlobalAlloc::Static(static_id), salt)
}
/// Generates an `AllocId` for a function. The caller must already have decided whether this
/// function obtains a unique AllocId or gets de-duplicated via the cache.
fn reserve_and_set_fn_alloc_internal(self, instance: Instance<'tcx>, unique: bool) -> AllocId {
let alloc = GlobalAlloc::Function { instance, unique };
if unique {
// Deduplicate.
self.reserve_and_set_dedup(alloc)
} else {
// Get a fresh ID.
let mut alloc_map = self.alloc_map.lock();
let id = alloc_map.reserve();
alloc_map.alloc_map.insert(id, alloc);
id
}
}
/// Generates an `AllocId` for a function. Depending on the function type,
/// this might get deduplicated or assigned a new ID each time.
pub fn reserve_and_set_fn_alloc(self, instance: Instance<'tcx>) -> AllocId {
// Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
// by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
// duplicated across crates. We thus generate a new `AllocId` for every mention of a
// function. This means that `main as fn() == main as fn()` is false, while `let x = main as
// fn(); x == x` is true. However, as a quality-of-life feature it can be useful to identify
// certain functions uniquely, e.g. for backtraces. So we identify whether codegen will
// actually emit duplicate functions. It does that when they have non-lifetime generics, or
// when they can be inlined. All other functions are given a unique address.
// This is not a stable guarantee! The `inline` attribute is a hint and cannot be relied
// upon for anything. But if we don't do this, backtraces look terrible.
let is_generic = instance
.args
.into_iter()
.any(|kind| !matches!(kind.unpack(), GenericArgKind::Lifetime(_)));
let can_be_inlined = match self.codegen_fn_attrs(instance.def_id()).inline {
InlineAttr::Never => false,
_ => true,
};
let unique = !is_generic && !can_be_inlined;
self.reserve_and_set_fn_alloc_internal(instance, unique)
/// Generates an `AllocId` for a function. Will get deduplicated.
pub fn reserve_and_set_fn_alloc(self, instance: Instance<'tcx>, salt: usize) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::Function { instance }, salt)
}
/// Generates an `AllocId` for a (symbolic, not-reified) vtable. Will get deduplicated.
@ -443,8 +399,9 @@ impl<'tcx> TyCtxt<'tcx> {
self,
ty: Ty<'tcx>,
poly_trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
salt: usize,
) -> AllocId {
self.reserve_and_set_dedup(GlobalAlloc::VTable(ty, poly_trait_ref))
self.reserve_and_set_dedup(GlobalAlloc::VTable(ty, poly_trait_ref), salt)
}
/// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical

View File

@ -1,3 +1,5 @@
use std::assert_matches::assert_matches;
use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
use super::Const;
@ -80,7 +82,7 @@ impl<'tcx> Expr<'tcx> {
}
pub fn binop_args(self) -> (Ty<'tcx>, Ty<'tcx>, Const<'tcx>, Const<'tcx>) {
assert!(matches!(self.kind, ExprKind::Binop(_)));
assert_matches!(self.kind, ExprKind::Binop(_));
match self.args().as_slice() {
[lhs_ty, rhs_ty, lhs_ct, rhs_ct] => (
@ -101,7 +103,7 @@ impl<'tcx> Expr<'tcx> {
}
pub fn unop_args(self) -> (Ty<'tcx>, Const<'tcx>) {
assert!(matches!(self.kind, ExprKind::UnOp(_)));
assert_matches!(self.kind, ExprKind::UnOp(_));
match self.args().as_slice() {
[ty, ct] => (ty.expect_ty(), ct.expect_const()),
@ -125,7 +127,7 @@ impl<'tcx> Expr<'tcx> {
}
pub fn call_args(self) -> (Ty<'tcx>, Const<'tcx>, impl Iterator<Item = Const<'tcx>>) {
assert!(matches!(self.kind, ExprKind::FunctionCall));
assert_matches!(self.kind, ExprKind::FunctionCall);
match self.args().as_slice() {
[func_ty, func, rest @ ..] => (
@ -152,7 +154,7 @@ impl<'tcx> Expr<'tcx> {
}
pub fn cast_args(self) -> (Ty<'tcx>, Const<'tcx>, Ty<'tcx>) {
assert!(matches!(self.kind, ExprKind::Cast(_)));
assert_matches!(self.kind, ExprKind::Cast(_));
match self.args().as_slice() {
[value_ty, value, to_ty] => {

Some files were not shown because too many files have changed in this diff Show More