Skip to content

Commit 3cc8a08

Browse files
committed
Use an enum for the sign instead of a bool
1 parent f73da1c commit 3cc8a08

File tree

27 files changed

+116
-85
lines changed

27 files changed

+116
-85
lines changed

compiler/rustc_ast/src/ast.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1869,18 +1869,31 @@ impl StrLit {
18691869
}
18701870
}
18711871

1872+
#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
1873+
#[derive(HashStable_Generic)]
1874+
pub enum Sign {
1875+
/// A `-` in front of a literal.
1876+
Neg,
1877+
/// No sign. There are no leading `+` in front of literals.
1878+
None,
1879+
}
1880+
1881+
impl Sign {
1882+
pub fn is_neg(&self) -> bool {
1883+
matches!(self, Self::Neg)
1884+
}
1885+
}
1886+
18721887
/// Type of the integer literal based on provided suffix.
18731888
#[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)]
18741889
#[derive(HashStable_Generic)]
18751890
pub enum LitIntType {
18761891
/// e.g. `42_i32`.
1877-
/// The bool signals whether the literal is negated
1878-
Signed(IntTy, bool),
1892+
Signed(IntTy, Sign),
18791893
/// e.g. `42_u32`.
18801894
Unsigned(UintTy),
18811895
/// e.g. `42`.
1882-
/// The bool signals whether the literal is negated
1883-
Unsuffixed(bool),
1896+
Unsuffixed(Sign),
18841897
}
18851898

18861899
/// Type of the float literal based on provided suffix.
@@ -1975,8 +1988,8 @@ impl LitKind {
19751988

19761989
pub fn is_negative(&self) -> bool {
19771990
match self {
1978-
LitKind::Int(_, LitIntType::Signed(_, negative) | LitIntType::Unsuffixed(negative)) => {
1979-
*negative
1991+
LitKind::Int(_, LitIntType::Signed(_, sign) | LitIntType::Unsuffixed(sign)) => {
1992+
sign.is_neg()
19801993
}
19811994
LitKind::Float(f, _) => f.as_str().starts_with('-'),
19821995
_ => false,

compiler/rustc_ast/src/util/literal.rs

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rustc_lexer::unescape::{
88
use rustc_span::{Span, Symbol, kw, sym};
99
use tracing::debug;
1010

11+
use crate::Sign;
1112
use crate::ast::{self, LitKind, MetaItemLit, StrStyle};
1213
use crate::token::{self, Token};
1314

@@ -44,24 +45,21 @@ pub enum LitError {
4445
impl LitKind {
4546
/// Converts literal token into a semantic literal.
4647
pub fn from_token_lit(lit: token::Lit) -> Result<LitKind, LitError> {
47-
Self::from_token_lit_maybe_negated(lit, false)
48+
Self::from_token_lit_maybe_negated(lit, Sign::None)
4849
}
4950

5051
/// Converts literal token into a semantic literal.
5152
/// May optionally include a sign, and will error if a literal
5253
/// other than integer or float literals is negated.
53-
pub fn from_token_lit_maybe_negated(
54-
lit: token::Lit,
55-
negated: bool,
56-
) -> Result<LitKind, LitError> {
54+
pub fn from_token_lit_maybe_negated(lit: token::Lit, sign: Sign) -> Result<LitKind, LitError> {
5755
let token::Lit { kind, symbol, suffix } = lit;
5856
if let Some(suffix) = suffix
5957
&& !kind.may_have_suffix()
6058
{
6159
return Err(LitError::InvalidSuffix(suffix));
6260
}
6361

64-
if negated && !matches!(kind, token::Integer | token::Float) {
62+
if sign.is_neg() && !matches!(kind, token::Integer | token::Float) {
6563
return Err(LitError::InvalidNegation(kind));
6664
}
6765

@@ -86,8 +84,8 @@ impl LitKind {
8684

8785
// There are some valid suffixes for integer and float literals,
8886
// so all the handling is done internally.
89-
token::Integer => return integer_lit(symbol, suffix, negated),
90-
token::Float => return float_lit(symbol, suffix, negated),
87+
token::Integer => return integer_lit(symbol, suffix, sign),
88+
token::Float => return float_lit(symbol, suffix, sign),
9189

9290
token::Str => {
9391
// If there are no characters requiring special treatment we can
@@ -206,14 +204,14 @@ impl fmt::Display for LitKind {
206204
}
207205
LitKind::Int(n, ty) => match ty {
208206
ast::LitIntType::Unsigned(ty) => write!(f, "{n}{}", ty.name())?,
209-
ast::LitIntType::Signed(ty, negated) => {
210-
if negated {
207+
ast::LitIntType::Signed(ty, sign) => {
208+
if sign.is_neg() {
211209
write!(f, "-")?;
212210
}
213211
write!(f, "{n}{}", ty.name())?
214212
}
215-
ast::LitIntType::Unsuffixed(negated) => {
216-
if negated {
213+
ast::LitIntType::Unsuffixed(sign) => {
214+
if sign.is_neg() {
217215
write!(f, "-")?;
218216
}
219217
write!(f, "{n}")?;
@@ -291,13 +289,14 @@ fn filtered_float_lit(
291289
symbol: Symbol,
292290
suffix: Option<Symbol>,
293291
base: u32,
294-
negated: bool,
292+
sign: Sign,
295293
) -> Result<LitKind, LitError> {
296-
debug!(?symbol, ?suffix, ?base, ?negated);
294+
debug!(?symbol, ?suffix, ?base, ?sign);
297295
if base != 10 {
298296
return Err(LitError::NonDecimalFloat(base));
299297
}
300-
let symbol = if negated { Symbol::intern(&format!("-{}", symbol.as_str())) } else { symbol };
298+
let symbol =
299+
if sign.is_neg() { Symbol::intern(&format!("-{}", symbol.as_str())) } else { symbol };
301300
Ok(match suffix {
302301
Some(suffix) => LitKind::Float(
303302
symbol,
@@ -313,12 +312,12 @@ fn filtered_float_lit(
313312
})
314313
}
315314

316-
fn float_lit(symbol: Symbol, suffix: Option<Symbol>, negated: bool) -> Result<LitKind, LitError> {
315+
fn float_lit(symbol: Symbol, suffix: Option<Symbol>, sign: Sign) -> Result<LitKind, LitError> {
317316
debug!("float_lit: {:?}, {:?}", symbol, suffix);
318-
filtered_float_lit(strip_underscores(symbol), suffix, 10, negated)
317+
filtered_float_lit(strip_underscores(symbol), suffix, 10, sign)
319318
}
320319

321-
fn integer_lit(symbol: Symbol, suffix: Option<Symbol>, negated: bool) -> Result<LitKind, LitError> {
320+
fn integer_lit(symbol: Symbol, suffix: Option<Symbol>, sign: Sign) -> Result<LitKind, LitError> {
322321
debug!("integer_lit: {:?}, {:?}", symbol, suffix);
323322
let symbol = strip_underscores(symbol);
324323
let s = symbol.as_str();
@@ -332,12 +331,12 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>, negated: bool) -> Result<
332331

333332
let ty = match suffix {
334333
Some(suf) => match suf {
335-
sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize, negated),
336-
sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8, negated),
337-
sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16, negated),
338-
sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32, negated),
339-
sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64, negated),
340-
sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128, negated),
334+
sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize, sign),
335+
sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8, sign),
336+
sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16, sign),
337+
sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32, sign),
338+
sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64, sign),
339+
sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128, sign),
341340
sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize),
342341
sym::u8 => ast::LitIntType::Unsigned(ast::UintTy::U8),
343342
sym::u16 => ast::LitIntType::Unsigned(ast::UintTy::U16),
@@ -347,14 +346,14 @@ fn integer_lit(symbol: Symbol, suffix: Option<Symbol>, negated: bool) -> Result<
347346
// `1f64` and `2f32` etc. are valid float literals, and
348347
// `fxxx` looks more like an invalid float literal than invalid integer literal.
349348
_ if suf.as_str().starts_with('f') => {
350-
return filtered_float_lit(symbol, suffix, base, negated);
349+
return filtered_float_lit(symbol, suffix, base, sign);
351350
}
352351
_ => return Err(LitError::InvalidIntSuffix(suf)),
353352
},
354-
_ => ast::LitIntType::Unsuffixed(negated),
353+
_ => ast::LitIntType::Unsuffixed(sign),
355354
};
356355
if let ast::LitIntType::Unsigned(_) = ty
357-
&& negated
356+
&& sign.is_neg()
358357
{
359358
return Err(LitError::InvalidNegation(token::Integer));
360359
}

compiler/rustc_ast_lowering/src/expr.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
142142
if let ExprKind::Lit(token_lit) = &ohs.kind {
143143
return hir::Expr {
144144
hir_id: expr_hir_id,
145-
kind: hir::ExprKind::Lit(self.lower_lit(token_lit, e.span, true)),
145+
kind: hir::ExprKind::Lit(self.lower_lit(
146+
token_lit,
147+
e.span,
148+
Sign::Neg,
149+
)),
146150
span: self.lower_span(e.span),
147151
};
148152
}
@@ -152,7 +156,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
152156
hir::ExprKind::Unary(op, ohs)
153157
}
154158
ExprKind::Lit(token_lit) => {
155-
hir::ExprKind::Lit(self.lower_lit(token_lit, e.span, false))
159+
hir::ExprKind::Lit(self.lower_lit(token_lit, e.span, Sign::None))
156160
}
157161
ExprKind::IncludedBytes(bytes) => {
158162
let lit = self.arena.alloc(respan(
@@ -430,9 +434,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
430434
&mut self,
431435
token_lit: &token::Lit,
432436
span: Span,
433-
negated: bool,
437+
sign: Sign,
434438
) -> &'hir Spanned<LitKind> {
435-
let lit_kind = match LitKind::from_token_lit_maybe_negated(*token_lit, negated) {
439+
let lit_kind = match LitKind::from_token_lit_maybe_negated(*token_lit, sign) {
436440
Ok(lit_kind) => lit_kind,
437441
Err(err) => {
438442
let guar = report_lit_error(&self.tcx.sess.psess, err, *token_lit, span);

compiler/rustc_ast_lowering/src/format.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
3030
Ok(LitKind::Int(n, ty)) => {
3131
match ty {
3232
// unsuffixed integer literals are assumed to be i32's
33-
LitIntType::Unsuffixed(negated) => (!negated && n <= i32::MAX as u128)
33+
LitIntType::Unsuffixed(sign) => (matches!(sign, Sign::None)
34+
&& n <= i32::MAX as u128)
3435
.then_some(Symbol::intern(&n.to_string())),
35-
LitIntType::Signed(int_ty, negated) => {
36+
LitIntType::Signed(int_ty, sign) => {
3637
let max_literal = self.int_ty_max(int_ty);
37-
(!negated && n <= max_literal).then_some(Symbol::intern(&n.to_string()))
38+
(matches!(sign, Sign::None) && n <= max_literal)
39+
.then_some(Symbol::intern(&n.to_string()))
3840
}
3941
LitIntType::Unsigned(uint_ty) => {
4042
let max_literal = self.uint_ty_max(uint_ty);

compiler/rustc_ast_lowering/src/pat.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
393393
lit: self.arena.alloc(respan(span, LitKind::Err(guar))),
394394
};
395395
let kind = match &expr.kind {
396-
ExprKind::Lit(lit) => hir::PatExprKind::Lit { lit: self.lower_lit(lit, span, false) },
396+
ExprKind::Lit(lit) => {
397+
hir::PatExprKind::Lit { lit: self.lower_lit(lit, span, Sign::None) }
398+
}
397399
ExprKind::ConstBlock(c) => hir::PatExprKind::ConstBlock(self.lower_const_block(c)),
398400
ExprKind::IncludedBytes(bytes) => hir::PatExprKind::Lit {
399401
lit: self
@@ -412,7 +414,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
412414
None,
413415
)),
414416
ExprKind::Unary(UnOp::Neg, inner) if let ExprKind::Lit(lit) = &inner.kind => {
415-
hir::PatExprKind::Lit { lit: self.lower_lit(lit, span, true) }
417+
hir::PatExprKind::Lit { lit: self.lower_lit(lit, span, Sign::Neg) }
416418
}
417419
_ => {
418420
let pattern_from_macro = expr.is_approximately_pattern();

compiler/rustc_attr_parsing/src/attributes/repr.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use rustc_abi::Align;
2-
use rustc_ast::{IntTy, LitIntType, LitKind, UintTy};
2+
use rustc_ast::{IntTy, LitIntType, LitKind, Sign, UintTy};
33
use rustc_attr_data_structures::{AttributeKind, IntType, ReprAttr};
44
use rustc_span::{Span, Symbol, sym};
55

@@ -225,7 +225,7 @@ fn parse_repr_align(
225225
}
226226

227227
fn parse_alignment(node: &LitKind) -> Result<Align, &'static str> {
228-
if let LitKind::Int(literal, LitIntType::Unsuffixed(false)) = node {
228+
if let LitKind::Int(literal, LitIntType::Unsuffixed(Sign::None)) = node {
229229
// `Align::from_bytes` accepts 0 as an input, check is_power_of_two() first
230230
if literal.get().is_power_of_two() {
231231
// Only possible error is larger than 2^29

compiler/rustc_attr_parsing/src/session_diagnostics.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -343,10 +343,10 @@ pub(crate) enum IncorrectReprFormatGenericCause<'a> {
343343
impl<'a> IncorrectReprFormatGenericCause<'a> {
344344
pub(crate) fn from_lit_kind(span: Span, kind: &ast::LitKind, name: &'a str) -> Option<Self> {
345345
match *kind {
346-
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed(negated)) => Some(Self::Int {
346+
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed(sign)) => Some(Self::Int {
347347
span,
348348
name,
349-
int: if negated { format!("-{}", int.get()) } else { int.get().to_string() },
349+
int: if sign.is_neg() { format!("-{}", int.get()) } else { int.get().to_string() },
350350
}),
351351
ast::LitKind::Str(symbol, _) => Some(Self::Symbol { span, name, symbol }),
352352
_ => None,

compiler/rustc_builtin_macros/src/concat_bytes.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rustc_ast::ptr::P;
22
use rustc_ast::tokenstream::TokenStream;
3-
use rustc_ast::{ExprKind, LitIntType, LitKind, UintTy, token};
3+
use rustc_ast::{ExprKind, LitIntType, LitKind, Sign, UintTy, token};
44
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
55
use rustc_session::errors::report_lit_error;
66
use rustc_span::{ErrorGuaranteed, Span};
@@ -51,7 +51,10 @@ fn invalid_type_err(
5151
snippet.map(|snippet| ConcatBytesInvalidSuggestion::IntLit { span, snippet });
5252
dcx.emit_err(ConcatBytesInvalid { span, lit_kind: "numeric", sugg })
5353
}
54-
Ok(LitKind::Int(val, LitIntType::Unsuffixed(false) | LitIntType::Unsigned(UintTy::U8))) => {
54+
Ok(LitKind::Int(
55+
val,
56+
LitIntType::Unsuffixed(Sign::None) | LitIntType::Unsigned(UintTy::U8),
57+
)) => {
5558
assert!(val.get() > u8::MAX.into()); // must be an error
5659
dcx.emit_err(ConcatBytesOob { span })
5760
}
@@ -79,7 +82,7 @@ fn handle_array_element(
7982
match LitKind::from_token_lit(token_lit) {
8083
Ok(LitKind::Int(
8184
val,
82-
LitIntType::Unsuffixed(false) | LitIntType::Unsigned(UintTy::U8),
85+
LitIntType::Unsuffixed(Sign::None) | LitIntType::Unsigned(UintTy::U8),
8386
)) if let Ok(val) = u8::try_from(val.get()) => {
8487
return Some(val);
8588
}

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_abi::ExternAbi;
44
use rustc_ast::expand::autodiff_attrs::{
55
AutoDiffAttrs, DiffActivity, DiffMode, valid_input_activity, valid_ret_activity,
66
};
7-
use rustc_ast::{MetaItem, MetaItemInner, attr};
7+
use rustc_ast::{MetaItem, MetaItemInner, Sign, attr};
88
use rustc_attr_parsing::ReprAttr::ReprAlign;
99
use rustc_attr_parsing::{AttributeKind, InlineAttr, InstructionSetAttr, OptimizeAttr};
1010
use rustc_data_structures::fx::FxHashMap;
@@ -751,7 +751,8 @@ fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &hir::Attribute) -> Option<u16> {
751751
return None;
752752
};
753753
if let Some(MetaItemLit {
754-
kind: LitKind::Int(ordinal, LitIntType::Unsuffixed(false)), ..
754+
kind: LitKind::Int(ordinal, LitIntType::Unsuffixed(Sign::None)),
755+
..
755756
}) = sole_meta_list.lit()
756757
{
757758
// According to the table at

compiler/rustc_expand/src/mbe/metavar_expr.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, Token, TokenKind};
22
use rustc_ast::tokenstream::{TokenStream, TokenStreamIter, TokenTree};
3-
use rustc_ast::{LitIntType, LitKind};
3+
use rustc_ast::{LitIntType, LitKind, Sign};
44
use rustc_ast_pretty::pprust;
55
use rustc_errors::{Applicability, PResult};
66
use rustc_macros::{Decodable, Encodable};
@@ -191,7 +191,7 @@ fn parse_depth<'psess>(
191191
.struct_span_err(span, "meta-variable expression depth must be a literal"));
192192
};
193193
if let Ok(lit_kind) = LitKind::from_token_lit(*lit)
194-
&& let LitKind::Int(n_u128, LitIntType::Unsuffixed(false)) = lit_kind
194+
&& let LitKind::Int(n_u128, LitIntType::Unsuffixed(Sign::None)) = lit_kind
195195
&& let Ok(n_usize) = usize::try_from(n_u128.get())
196196
{
197197
Ok(n_usize)

0 commit comments

Comments
 (0)