Rollup merge of #152001 - reddevilmidzy:mgca-i, r=BoxyUwU

mGCA: Validate const literal against expected type

close: rust-lang/rust#151625
close: rust-lang/rust#150983

also fix: https://github.com/rust-lang/rust/issues/133966 (moved crashes test)
This commit is contained in:
Jonathan Brouwer 2026-02-14 18:55:35 +01:00 committed by GitHub
commit 5ae6bb3faf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
40 changed files with 532 additions and 233 deletions

View file

@ -35,11 +35,10 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_infer::traits::DynCompatibilityViolation;
use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::middle::stability::AllowUnstable;
use rustc_middle::mir::interpret::LitToConstInput;
use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
use rustc_middle::ty::{
self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, fold_regions,
self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, Ty, TyCtxt,
TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, const_lit_matches_ty, fold_regions,
};
use rustc_middle::{bug, span_bug};
use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
@ -2809,8 +2808,17 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
span: Span,
) -> Const<'tcx> {
let tcx = self.tcx();
if let LitKind::Err(guar) = *kind {
return ty::Const::new_error(tcx, guar);
}
let input = LitToConstInput { lit: *kind, ty, neg };
tcx.at(span).lit_to_const(input)
match tcx.at(span).lit_to_const(input) {
Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
None => {
let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
ty::Const::new_error(tcx, e)
}
}
}
#[instrument(skip(self), level = "debug")]
@ -2839,11 +2847,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
_ => None,
};
lit_input
// Allow the `ty` to be an alias type, though we cannot handle it here, we just go through
// the more expensive anon const code path.
.filter(|l| !l.ty.has_aliases())
.map(|l| tcx.at(expr.span).lit_to_const(l))
lit_input.and_then(|l| {
if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
tcx.at(expr.span)
.lit_to_const(l)
.map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
} else {
None
}
})
}
fn require_type_const_attribute(