Auto merge of #120080 - cuviper:128-align-packed, r=nikic

Pack u128 in the compiler to mitigate new alignment

This is based on #116672, adding a new `#[repr(packed(8))]` wrapper on `u128` to avoid changing any of the compiler's size assertions. This is needed in two places:

* `SwitchTargets`, otherwise its `SmallVec<[u128; 1]>` gets padded up to 32 bytes.
* `LitKind::Int`, so that entire `enum` can stay 24 bytes.
  * This change definitely has far-reaching effects though, since it's public.
This commit is contained in:
bors 2024-01-22 13:08:19 +00:00
commit 3066253050
43 changed files with 173 additions and 86 deletions

View File

@ -27,6 +27,7 @@
use crate::ptr::P;
use crate::token::{self, CommentKind, Delimiter};
use crate::tokenstream::{DelimSpan, LazyAttrTokenStream, TokenStream};
use rustc_data_structures::packed::Pu128;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::sync::Lrc;
@ -1833,7 +1834,7 @@ pub enum LitKind {
/// A character literal (`'a'`).
Char(char),
/// An integer literal (`1`).
Int(u128, LitIntType),
Int(Pu128, LitIntType),
/// A float literal (`1.0`, `1f64` or `1E10f64`). The pre-suffix part is
/// stored as a symbol rather than `f64` so that `LitKind` can impl `Eq`
/// and `Hash`.
@ -3304,13 +3305,9 @@ mod size_asserts {
static_assert_size!(Impl, 136);
static_assert_size!(Item, 136);
static_assert_size!(ItemKind, 64);
// This can be removed after i128:128 is in the bootstrap compiler's target.
#[cfg(not(bootstrap))]
static_assert_size!(LitKind, 32);
static_assert_size!(LitKind, 24);
static_assert_size!(Local, 72);
// This can be removed after i128:128 is in the bootstrap compiler's target.
#[cfg(not(bootstrap))]
static_assert_size!(MetaItemLit, 48);
static_assert_size!(MetaItemLit, 40);
static_assert_size!(Param, 40);
static_assert_size!(Pat, 72);
static_assert_size!(Path, 24);

View File

@ -366,7 +366,7 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>) -> Result<LitKind, LitErr
};
let s = &s[if base != 10 { 2 } else { 0 }..];
u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| {
u128::from_str_radix(s, base).map(|i| LitKind::Int(i.into(), ty)).map_err(|_| {
// Small bases are lexed as if they were base 10, e.g, the string
// might be `0b10201`. This will cause the conversion above to fail,
// but these kinds of errors are already reported by the lexer.

View File

@ -1899,7 +1899,10 @@ fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> {
let lit = self.arena.alloc(hir::Lit {
span: sp,
node: ast::LitKind::Int(value as u128, ast::LitIntType::Unsigned(ast::UintTy::Usize)),
node: ast::LitKind::Int(
(value as u128).into(),
ast::LitIntType::Unsigned(ast::UintTy::Usize),
),
});
self.expr(sp, hir::ExprKind::Lit(lit))
}
@ -1907,7 +1910,10 @@ pub(super) fn expr_usize(&mut self, sp: Span, value: usize) -> hir::Expr<'hir> {
pub(super) fn expr_u32(&mut self, sp: Span, value: u32) -> hir::Expr<'hir> {
let lit = self.arena.alloc(hir::Lit {
span: sp,
node: ast::LitKind::Int(value.into(), ast::LitIntType::Unsigned(ast::UintTy::U32)),
node: ast::LitKind::Int(
u128::from(value).into(),
ast::LitIntType::Unsigned(ast::UintTy::U32),
),
});
self.expr(sp, hir::ExprKind::Lit(lit))
}

View File

@ -1185,9 +1185,9 @@ fn allow_unstable<'a>(
pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> {
if let ast::LitKind::Int(literal, ast::LitIntType::Unsuffixed) = node {
if literal.is_power_of_two() {
if literal.get().is_power_of_two() {
// rustc_middle::ty::layout::Align restricts align to <= 2^29
if *literal <= 1 << 29 { Ok(*literal as u32) } else { Err("larger than 2^29") }
if *literal <= 1 << 29 { Ok(literal.get() as u32) } else { Err("larger than 2^29") }
} else {
Err("not a power of two")
}

View File

@ -296,7 +296,7 @@ impl<'a> IncorrectReprFormatGenericCause<'a> {
pub fn from_lit_kind(span: Span, kind: &ast::LitKind, name: &'a str) -> Option<Self> {
match kind {
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
Some(Self::Int { span, name, int: *int })
Some(Self::Int { span, name, int: int.get() })
}
ast::LitKind::Str(symbol, _) => Some(Self::Symbol { span, name, symbol: *symbol }),
_ => None,

View File

@ -54,7 +54,7 @@ fn invalid_type_err(
val,
ast::LitIntType::Unsuffixed | ast::LitIntType::Unsigned(ast::UintTy::U8),
)) => {
assert!(val > u8::MAX.into()); // must be an error
assert!(val.get() > u8::MAX.into()); // must be an error
dcx.emit_err(ConcatBytesOob { span });
}
Ok(ast::LitKind::Int(_, _)) => {
@ -86,7 +86,7 @@ fn handle_array_element(
Ok(ast::LitKind::Int(
val,
ast::LitIntType::Unsuffixed | ast::LitIntType::Unsigned(ast::UintTy::U8),
)) if val <= u8::MAX.into() => Some(val as u8),
)) if val.get() <= u8::MAX.into() => Some(val.get() as u8),
Ok(ast::LitKind::Byte(val)) => Some(val),
Ok(ast::LitKind::ByteStr(..)) => {
@ -148,7 +148,7 @@ pub fn expand_concat_bytes(
if let Some(elem) =
handle_array_element(cx, &mut has_errors, &mut missing_literals, expr)
{
for _ in 0..count_val {
for _ in 0..count_val.get() {
accumulator.push(elem);
}
}

View File

@ -658,7 +658,7 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<u16> {
// if the resulting EXE runs, as I haven't yet built the necessary DLL -- see earlier comment
// about LINK.EXE failing.)
if *ordinal <= u16::MAX as u128 {
Some(*ordinal as u16)
Some(ordinal.get() as u16)
} else {
let msg = format!("ordinal value in `link_ordinal` is too large: `{}`", &ordinal);
tcx.dcx()

View File

@ -93,6 +93,7 @@ pub fn outline<F: FnOnce() -> R, R>(f: F) -> R {
pub mod frozen;
mod hashes;
pub mod owned_slice;
pub mod packed;
pub mod sso;
pub mod steal;
pub mod tagged_ptr;

View File

@ -0,0 +1,71 @@
use crate::stable_hasher::{HashStable, StableHasher};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use std::cmp::Ordering;
use std::fmt;
#[repr(packed(8))]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pu128(pub u128);
impl Pu128 {
#[inline]
pub fn get(self) -> u128 {
self.0
}
}
impl From<u128> for Pu128 {
#[inline]
fn from(value: u128) -> Self {
Self(value)
}
}
impl PartialEq<u128> for Pu128 {
#[inline]
fn eq(&self, other: &u128) -> bool {
({ self.0 }) == *other
}
}
impl PartialOrd<u128> for Pu128 {
#[inline]
fn partial_cmp(&self, other: &u128) -> Option<Ordering> {
{ self.0 }.partial_cmp(other)
}
}
impl fmt::Display for Pu128 {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
{ self.0 }.fmt(f)
}
}
impl fmt::UpperHex for Pu128 {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
{ self.0 }.fmt(f)
}
}
impl<CTX> HashStable<CTX> for Pu128 {
#[inline]
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
{ self.0 }.hash_stable(ctx, hasher)
}
}
impl<S: Encoder> Encodable<S> for Pu128 {
#[inline]
fn encode(&self, s: &mut S) {
{ self.0 }.encode(s);
}
}
impl<D: Decoder> Decodable<D> for Pu128 {
#[inline]
fn decode(d: &mut D) -> Self {
Self(u128::decode(d))
}
}

View File

@ -124,7 +124,7 @@ fn parse_depth<'sess>(
};
if let Ok(lit_kind) = LitKind::from_token_lit(*lit)
&& let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind
&& let Ok(n_usize) = usize::try_from(n_u128)
&& let Ok(n_usize) = usize::try_from(n_u128.get())
{
Ok(n_usize)
} else {

View File

@ -2981,10 +2981,11 @@ fn check_expr_index(
// fixed expression:
if let ExprKind::Lit(lit) = idx.kind
&& let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node
&& i < types
.len()
.try_into()
.expect("expected tuple index to be < usize length")
&& i.get()
< types
.len()
.try_into()
.expect("expected tuple index to be < usize length")
{
err.span_suggestion(
brackets_span,

View File

@ -11,6 +11,7 @@
use core::cmp::min;
use core::iter;
use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX};
use rustc_data_structures::packed::Pu128;
use rustc_errors::{Applicability, Diagnostic, MultiSpan};
use rustc_hir as hir;
use rustc_hir::def::Res;
@ -1409,8 +1410,8 @@ pub(crate) fn suggest_floating_point_literal(
}
let (_, suffix) = snippet.split_at(snippet.len() - 3);
let value = match suffix {
"f32" => (lit - 0xf32) / (16 * 16 * 16),
"f64" => (lit - 0xf64) / (16 * 16 * 16),
"f32" => (lit.get() - 0xf32) / (16 * 16 * 16),
"f64" => (lit.get() - 0xf64) / (16 * 16 * 16),
_ => return false,
};
err.span_suggestions(
@ -1440,7 +1441,8 @@ pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg(
};
// Provided expression needs to be a literal `0`.
let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(0, _), span }) = expr.kind else {
let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(Pu128(0), _), span }) = expr.kind
else {
return false;
};

View File

@ -4,6 +4,7 @@
use super::{has_expected_num_generic_args, FnCtxt};
use crate::Expectation;
use rustc_ast as ast;
use rustc_data_structures::packed::Pu128;
use rustc_errors::{struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
@ -834,7 +835,7 @@ pub fn check_user_unop(
hir::Expr {
kind:
hir::ExprKind::Lit(Spanned {
node: ast::LitKind::Int(1, _),
node: ast::LitKind::Int(Pu128(1), _),
..
}),
..

View File

@ -111,7 +111,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
.map(|e| match &e.kind {
ExprKind::Lit(Spanned { node: lit, .. }) => match lit {
LitKind::Byte(b) => Some(*b),
LitKind::Int(b, _) => Some(*b as u8),
LitKind::Int(b, _) => Some(b.get() as u8),
_ => None,
},
_ => None,

View File

@ -492,7 +492,7 @@ fn lint_uint_literal<'tcx>(
let lit_val: u128 = match lit.node {
// _v is u8, within range by definition
ast::LitKind::Byte(_v) => return,
ast::LitKind::Int(v, _) => v,
ast::LitKind::Int(v, _) => v.get(),
_ => bug!(),
};
if lit_val < min || lit_val > max {
@ -555,7 +555,7 @@ fn lint_literal<'tcx>(
ty::Int(t) => {
match lit.node {
ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => {
lint_int_literal(cx, type_limits, e, lit, t, v)
lint_int_literal(cx, type_limits, e, lit, t, v.get())
}
_ => bug!(),
};
@ -842,7 +842,7 @@ fn check_limits(
ast::LitKind::Int(
v,
ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed,
) => v as i128,
) => v.get() as i128,
_ => return true,
},
_ => bug!(),
@ -853,7 +853,7 @@ fn check_limits(
let (min, max): (u128, u128) = uint_ty_range(uint_ty);
let lit_val: u128 = match lit.kind {
hir::ExprKind::Lit(li) => match li.node {
ast::LitKind::Int(v, _) => v,
ast::LitKind::Int(v, _) => v.get(),
_ => return true,
},
_ => bug!(),

View File

@ -1672,19 +1672,13 @@ mod size_asserts {
use super::*;
use rustc_data_structures::static_assert_size;
// tidy-alphabetical-start
// This can be removed after i128:128 is in the bootstrap compiler's target.
#[cfg(not(bootstrap))]
static_assert_size!(BasicBlockData<'_>, 144);
static_assert_size!(BasicBlockData<'_>, 136);
static_assert_size!(LocalDecl<'_>, 40);
static_assert_size!(SourceScopeData<'_>, 72);
static_assert_size!(Statement<'_>, 32);
static_assert_size!(StatementKind<'_>, 16);
// This can be removed after i128:128 is in the bootstrap compiler's target.
#[cfg(not(bootstrap))]
static_assert_size!(Terminator<'_>, 112);
// This can be removed after i128:128 is in the bootstrap compiler's target.
#[cfg(not(bootstrap))]
static_assert_size!(TerminatorKind<'_>, 96);
static_assert_size!(Terminator<'_>, 104);
static_assert_size!(TerminatorKind<'_>, 88);
static_assert_size!(VarDebugInfo<'_>, 88);
// tidy-alphabetical-end
}

View File

@ -13,6 +13,7 @@
use crate::ty::{Region, UserTypeAnnotationIndex};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_data_structures::packed::Pu128;
use rustc_hir::def_id::DefId;
use rustc_hir::{self, CoroutineKind};
use rustc_index::IndexVec;
@ -829,7 +830,7 @@ pub const fn name(&self) -> &'static str {
pub struct SwitchTargets {
/// Possible values. The locations to branch to in each case
/// are found in the corresponding indices from the `targets` vector.
pub(super) values: SmallVec<[u128; 1]>,
pub(super) values: SmallVec<[Pu128; 1]>,
/// Possible branch sites. The last element of this vector is used
/// for the otherwise branch, so targets.len() == values.len() + 1

View File

@ -3,6 +3,7 @@
use smallvec::SmallVec;
use super::TerminatorKind;
use rustc_data_structures::packed::Pu128;
use rustc_macros::HashStable;
use std::slice;
@ -14,7 +15,8 @@ impl SwitchTargets {
/// The iterator may be empty, in which case the `SwitchInt` instruction is equivalent to
/// `goto otherwise;`.
pub fn new(targets: impl Iterator<Item = (u128, BasicBlock)>, otherwise: BasicBlock) -> Self {
let (values, mut targets): (SmallVec<_>, SmallVec<_>) = targets.unzip();
let (values, mut targets): (SmallVec<_>, SmallVec<_>) =
targets.map(|(v, t)| (Pu128(v), t)).unzip();
targets.push(otherwise);
Self { values, targets }
}
@ -22,7 +24,7 @@ pub fn new(targets: impl Iterator<Item = (u128, BasicBlock)>, otherwise: BasicBl
/// Builds a switch targets definition that jumps to `then` if the tested value equals `value`,
/// and to `else_` if not.
pub fn static_if(value: u128, then: BasicBlock, else_: BasicBlock) -> Self {
Self { values: smallvec![value], targets: smallvec![then, else_] }
Self { values: smallvec![Pu128(value)], targets: smallvec![then, else_] }
}
/// Inverse of `SwitchTargets::static_if`.
@ -31,7 +33,7 @@ pub fn as_static_if(&self) -> Option<(u128, BasicBlock, BasicBlock)> {
if let &[value] = &self.values[..]
&& let &[then, else_] = &self.targets[..]
{
Some((value, then, else_))
Some((value.get(), then, else_))
} else {
None
}
@ -75,7 +77,7 @@ pub fn target_for_value(&self, value: u128) -> BasicBlock {
}
pub struct SwitchTargetsIter<'a> {
inner: iter::Zip<slice::Iter<'a, u128>, slice::Iter<'a, BasicBlock>>,
inner: iter::Zip<slice::Iter<'a, Pu128>, slice::Iter<'a, BasicBlock>>,
}
impl<'a> Iterator for SwitchTargetsIter<'a> {
@ -83,7 +85,7 @@ impl<'a> Iterator for SwitchTargetsIter<'a> {
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(val, bb)| (*val, *bb))
self.inner.next().map(|(val, bb)| (val.get(), *bb))
}
#[inline]

View File

@ -745,7 +745,7 @@ pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound<u128>, Bound<u12
],
) = attr.meta_item_list().as_deref()
{
Bound::Included(a)
Bound::Included(a.get())
} else {
self.dcx().span_delayed_bug(
attr.span,

View File

@ -153,7 +153,7 @@ fn lit_to_mir_constant<'tcx>(
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
}
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() })?
}
(ast::LitKind::Float(n, _), ty::Float(fty)) => parse_float_into_constval(*n, *fty, neg)
.ok_or_else(|| {

View File

@ -54,7 +54,7 @@ pub(crate) fn lit_to_const<'tcx>(
}
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
let scalar_int =
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?;
trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() })?;
ty::ValTree::from_scalar_int(scalar_int)
}
(ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int((*b).into()),

View File

@ -2069,7 +2069,7 @@ fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
let mut ret = Vec::new();
for meta in attr.meta_item_list()? {
match meta.lit()?.kind {
LitKind::Int(a, _) => ret.push(a as usize),
LitKind::Int(a, _) => ret.push(a.get() as usize),
_ => panic!("invalid arg index"),
}
}

View File

@ -1049,7 +1049,7 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attrib
func.decl
.inputs
.values
.insert(a as _, Argument { name, type_: *ty, is_const: true });
.insert(a.get() as _, Argument { name, type_: *ty, is_const: true });
} else {
panic!("unexpected non const in position {pos}");
}

View File

@ -107,7 +107,7 @@ pub(super) fn check<'tcx>(
&& let Some(src) = snippet_opt(cx, cast_expr.span)
&& cast_to.is_floating_point()
&& let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node)
&& let from_nbits = 128 - n.leading_zeros()
&& let from_nbits = 128 - n.get().leading_zeros()
&& let to_nbits = fp_ty_mantissa_nbits(cast_to)
&& from_nbits != 0
&& to_nbits != 0

View File

@ -3,6 +3,7 @@
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_context;
use rustc_ast::ast::{LitIntType, LitKind};
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Block, Expr, ExprKind, Stmt, StmtKind};
use rustc_lint::{LateContext, LateLintPass};
@ -69,7 +70,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
&& clippy_utils::SpanlessEq::new(cx).eq_expr(l, target)
&& BinOpKind::Add == op1.node
&& let ExprKind::Lit(lit) = value.kind
&& let LitKind::Int(1, LitIntType::Unsuffixed) = lit.node
&& let LitKind::Int(Pu128(1), LitIntType::Unsuffixed) = lit.node
&& block.expr.is_none()
{
let mut app = Applicability::MachineApplicable;

View File

@ -1,6 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::{higher, is_integer_literal, peel_blocks_with_stmt, SpanlessEq};
use rustc_ast::ast::LitKind;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind, QPath};
use rustc_lint::{LateContext, LateLintPass};
@ -86,7 +87,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
match cond_num_val.kind {
ExprKind::Lit(cond_lit) => {
// Check if the constant is zero
if let LitKind::Int(0, _) = cond_lit.node {
if let LitKind::Int(Pu128(0), _) = cond_lit.node {
if cx.typeck_results().expr_ty(cond_left).is_signed() {
} else {
print_lint_and_sugg(cx, var_name, expr);

View File

@ -461,7 +461,7 @@ fn extract_lit_value(expr: &Expr<'_>) -> Option<u128> {
if let ExprKind::Lit(lit) = expr.kind
&& let ast::LitKind::Int(value, _) = lit.node
{
Some(value)
Some(value.get())
} else {
None
}

View File

@ -209,8 +209,8 @@ fn is_end_eq_array_len<'tcx>(
&& let Some(arr_len) = arr_len_const.try_eval_target_usize(cx.tcx, cx.param_env)
{
return match limits {
ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
ast::RangeLimits::Closed => end_int.get() + 1 >= arr_len.into(),
ast::RangeLimits::HalfOpen => end_int.get() >= arr_len.into(),
};
}

View File

@ -3,6 +3,7 @@
use clippy_utils::get_parent_expr;
use clippy_utils::source::snippet_with_context;
use rustc_ast::ast::LitKind;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind, GenericArg, QPath};
use rustc_lint::{LateContext, LateLintPass, LintContext};
@ -62,7 +63,7 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
&& let Some((real_ty, resolved_ty, other_expr)) = get_one_size_of_ty(cx, left_expr, right_expr)
&& matches!(resolved_ty.kind(), ty::Int(_) | ty::Uint(_))
&& let ExprKind::Lit(lit) = &other_expr.kind
&& let LitKind::Int(8, _) = lit.node
&& let LitKind::Int(Pu128(8), _) = lit.node
{
let mut app = Applicability::MachineApplicable;
let ty_snip = snippet_with_context(cx, real_ty.span, ctxt, "..", &mut app).0;

View File

@ -45,7 +45,7 @@ fn expr_as_i128(expr: &Expr<'_>) -> Option<i128> {
&& let LitKind::Int(num, _) = lit.node
{
// Intentionally not handling numbers greater than i128::MAX (for u128 literals) for now.
num.try_into().ok()
num.get().try_into().ok()
} else {
None
}

View File

@ -161,7 +161,7 @@ fn eq_pattern_length<'tcx>(cx: &LateContext<'tcx>, pattern: &Expr<'_>, expr: &'t
..
}) = expr.kind
{
constant_length(cx, pattern).map_or(false, |length| length == *n)
constant_length(cx, pattern).map_or(false, |length| *n == length)
} else {
len_arg(cx, expr).map_or(false, |arg| eq_expr_value(cx, pattern, arg))
}

View File

@ -293,7 +293,7 @@ fn from_pat(cx: &LateContext<'_>, arena: &'a DroplessArena, pat: &'a Pat<'_>) ->
LitKind::ByteStr(ref bytes, _) | LitKind::CStr(ref bytes, _) => Self::LitBytes(bytes),
LitKind::Byte(val) => Self::LitInt(val.into()),
LitKind::Char(val) => Self::LitInt(val.into()),
LitKind::Int(val, _) => Self::LitInt(val),
LitKind::Int(val, _) => Self::LitInt(val.get()),
LitKind::Bool(val) => Self::LitBool(val),
LitKind::Float(..) | LitKind::Err => Self::Wild,
},
@ -305,7 +305,7 @@ fn from_pat(cx: &LateContext<'_>, arena: &'a DroplessArena, pat: &'a Pat<'_>) ->
None => 0,
Some(e) => match &e.kind {
ExprKind::Lit(lit) => match lit.node {
LitKind::Int(val, _) => val,
LitKind::Int(val, _) => val.get(),
LitKind::Char(val) => val.into(),
LitKind::Byte(val) => val.into(),
_ => return Self::Wild,
@ -317,7 +317,7 @@ fn from_pat(cx: &LateContext<'_>, arena: &'a DroplessArena, pat: &'a Pat<'_>) ->
None => (u128::MAX, RangeEnd::Included),
Some(e) => match &e.kind {
ExprKind::Lit(lit) => match lit.node {
LitKind::Int(val, _) => (val, bounds),
LitKind::Int(val, _) => (val.get(), bounds),
LitKind::Char(val) => (val.into(), bounds),
LitKind::Byte(val) => (val.into(), bounds),
_ => return Self::Wild,

View File

@ -2,6 +2,7 @@
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_ast::LitKind;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_lint::LateContext;
@ -20,7 +21,7 @@ pub(super) fn check<'tcx>(
&& let Some(impl_id) = cx.tcx.impl_of_method(method_id)
&& let identity = cx.tcx.type_of(impl_id).instantiate_identity()
&& let hir::ExprKind::Lit(Spanned {
node: LitKind::Int(0, _),
node: LitKind::Int(Pu128(0), _),
..
}) = arg.kind
{

View File

@ -13,7 +13,7 @@ fn expr_as_u128(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<u128> {
if let ExprKind::Lit(lit) = expr_or_init(cx, e).kind
&& let LitKind::Int(n, _) = lit.node
{
Some(n)
Some(n.get())
} else {
None
}

View File

@ -1,4 +1,5 @@
use rustc_ast::ast::{LitIntType, LitKind};
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
@ -41,7 +42,7 @@ fn arg_is_seek_from_current<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>)
// check if argument of `SeekFrom::Current` is `0`
if args.len() == 1
&& let ExprKind::Lit(lit) = args[0].kind
&& let LitKind::Int(0, LitIntType::Unsuffixed) = lit.node
&& let LitKind::Int(Pu128(0), LitIntType::Unsuffixed) = lit.node
{
return true;
}

View File

@ -2,6 +2,7 @@
use clippy_utils::ty::implements_trait;
use clippy_utils::{is_expr_used_or_unified, match_def_path, paths};
use rustc_ast::ast::{LitIntType, LitKind};
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
@ -31,7 +32,7 @@ pub(super) fn check<'tcx>(
&& match_def_path(cx, def_id, &paths::STD_IO_SEEKFROM_START)
&& args1.len() == 1
&& let ExprKind::Lit(lit) = args1[0].kind
&& let LitKind::Int(0, LitIntType::Unsuffixed) = lit.node
&& let LitKind::Int(Pu128(0), LitIntType::Unsuffixed) = lit.node
{
let method_call_span = expr.span.with_lo(name_span.lo());
span_lint_and_then(

View File

@ -2,6 +2,7 @@
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::{is_trait_method, path_to_local_id, peel_blocks, strip_pat_refs};
use rustc_ast::ast;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::PatKind;
@ -150,7 +151,7 @@ pub(super) fn check(
},
);
},
ast::LitKind::Int(0, _) => check_fold_with_op(
ast::LitKind::Int(Pu128(0), _) => check_fold_with_op(
cx,
expr,
acc,
@ -162,7 +163,7 @@ pub(super) fn check(
method_name: "sum",
},
),
ast::LitKind::Int(1, _) => {
ast::LitKind::Int(Pu128(1), _) => {
check_fold_with_op(
cx,
expr,

View File

@ -1,6 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use rustc_ast::LitKind;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
@ -20,7 +21,7 @@ pub(super) fn check<'tcx>(
&& let Some(impl_id) = cx.tcx.impl_of_method(method_id)
&& is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Vec)
&& let ExprKind::Lit(Spanned {
node: LitKind::Int(0, _),
node: LitKind::Int(Pu128(0), _),
..
}) = count_arg.kind
&& let ExprKind::Lit(Spanned {

View File

@ -7,6 +7,7 @@
use clippy_utils::visitors::for_each_expr;
use clippy_utils::{eq_expr_value, hash_expr, higher};
use rustc_ast::{LitKind, RangeLimits};
use rustc_data_structures::packed::Pu128;
use rustc_data_structures::unhash::UnhashMap;
use rustc_errors::{Applicability, Diagnostic};
use rustc_hir::{BinOp, Block, Body, Expr, ExprKind, UnOp};
@ -102,8 +103,8 @@ fn len_comparison<'hir>(
) -> Option<(LengthComparison, usize, &'hir Expr<'hir>)> {
macro_rules! int_lit_pat {
($id:ident) => {
ExprKind::Lit(Spanned {
node: LitKind::Int($id, _),
ExprKind::Lit(&Spanned {
node: LitKind::Int(Pu128($id), _),
..
})
};
@ -112,13 +113,13 @@ macro_rules! int_lit_pat {
// normalize comparison, `v.len() > 4` becomes `4 < v.len()`
// this simplifies the logic a bit
let (op, left, right) = normalize_comparison(bin_op.node, left, right)?;
match (op, &left.kind, &right.kind) {
(Rel::Lt, int_lit_pat!(left), _) => Some((LengthComparison::IntLessThanLength, *left as usize, right)),
(Rel::Lt, _, int_lit_pat!(right)) => Some((LengthComparison::LengthLessThanInt, *right as usize, left)),
(Rel::Le, int_lit_pat!(left), _) => Some((LengthComparison::IntLessThanOrEqualLength, *left as usize, right)),
(Rel::Le, _, int_lit_pat!(right)) => Some((LengthComparison::LengthLessThanOrEqualInt, *right as usize, left)),
(Rel::Eq, int_lit_pat!(left), _) => Some((LengthComparison::LengthEqualInt, *left as usize, right)),
(Rel::Eq, _, int_lit_pat!(right)) => Some((LengthComparison::LengthEqualInt, *right as usize, left)),
match (op, left.kind, right.kind) {
(Rel::Lt, int_lit_pat!(left), _) => Some((LengthComparison::IntLessThanLength, left as usize, right)),
(Rel::Lt, _, int_lit_pat!(right)) => Some((LengthComparison::LengthLessThanInt, right as usize, left)),
(Rel::Le, int_lit_pat!(left), _) => Some((LengthComparison::IntLessThanOrEqualLength, left as usize, right)),
(Rel::Le, _, int_lit_pat!(right)) => Some((LengthComparison::LengthLessThanOrEqualInt, right as usize, left)),
(Rel::Eq, int_lit_pat!(left), _) => Some((LengthComparison::LengthEqualInt, left as usize, right)),
(Rel::Eq, _, int_lit_pat!(right)) => Some((LengthComparison::LengthEqualInt, right as usize, left)),
_ => None,
}
}
@ -206,14 +207,14 @@ pub fn index_spans(&self) -> Option<&[Span]> {
/// for `..=5` this returns `Some(5)`
fn upper_index_expr(expr: &Expr<'_>) -> Option<usize> {
if let ExprKind::Lit(lit) = &expr.kind
&& let LitKind::Int(index, _) = lit.node
&& let LitKind::Int(Pu128(index), _) = lit.node
{
Some(index as usize)
} else if let Some(higher::Range {
end: Some(end), limits, ..
}) = higher::Range::hir(expr)
&& let ExprKind::Lit(lit) = &end.kind
&& let LitKind::Int(index @ 1.., _) = lit.node
&& let LitKind::Int(Pu128(index @ 1..), _) = lit.node
{
match limits {
RangeLimits::HalfOpen => Some(index as usize - 1),

View File

@ -151,7 +151,7 @@ fn literal_integer(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<u128> {
if let hir::ExprKind::Lit(lit) = actual.kind
&& let ast::LitKind::Int(n, _) = lit.node
{
return Some(n);
return Some(n.get());
}
if let Some(Constant::Int(n)) = constant(cx, cx.typeck_results(), expr) {
return Some(n);

View File

@ -1,6 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::sugg::Sugg;
use rustc_ast::ast::LitKind;
use rustc_data_structures::packed::Pu128;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::LateContext;
@ -19,9 +20,9 @@ pub(super) fn check<'tcx>(
&& let ExprKind::Binary(op1, left1, right1) = &left.kind
&& BinOpKind::BitAnd == op1.node
&& let ExprKind::Lit(lit) = &right1.kind
&& let LitKind::Int(n, _) = lit.node
&& let LitKind::Int(Pu128(n), _) = lit.node
&& let ExprKind::Lit(lit1) = &right.kind
&& let LitKind::Int(0, _) = lit1.node
&& let LitKind::Int(Pu128(0), _) = lit1.node
&& n.leading_zeros() == n.count_zeros()
&& n > u128::from(threshold)
{

View File

@ -275,7 +275,7 @@ pub fn lit_to_mir_constant<'tcx>(lit: &LitKind, ty: Option<Ty<'tcx>>) -> Constan
LitKind::Byte(b) => Constant::Int(u128::from(b)),
LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(Lrc::clone(s)),
LitKind::Char(c) => Constant::Char(c),
LitKind::Int(n, _) => Constant::Int(n),
LitKind::Int(n, _) => Constant::Int(n.get()),
LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
ast::FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
ast::FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),

View File

@ -80,6 +80,7 @@
use itertools::Itertools;
use rustc_ast::ast::{self, LitKind, RangeLimits};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::packed::Pu128;
use rustc_data_structures::unhash::UnhashMap;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, LOCAL_CRATE};
@ -838,7 +839,7 @@ pub fn is_default_equivalent_call(cx: &LateContext<'_>, repl_func: &Expr<'_>) ->
pub fn is_default_equivalent(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
match &e.kind {
ExprKind::Lit(lit) => match lit.node {
LitKind::Bool(false) | LitKind::Int(0, _) => true,
LitKind::Bool(false) | LitKind::Int(Pu128(0), _) => true,
LitKind::Str(s, _) => s.is_empty(),
_ => false,
},