Skip to content

Commit fb9ce02

Browse files
committed
Limit formatting width and precision to 16 bits.
1 parent 2c6a12e commit fb9ce02

File tree

10 files changed

+69
-46
lines changed

10 files changed

+69
-46
lines changed

compiler/rustc_ast/src/format.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ pub enum FormatAlignment {
266266
#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq)]
267267
pub enum FormatCount {
268268
/// `{:5}` or `{:.5}`
269-
Literal(usize),
269+
Literal(u16),
270270
/// `{:.*}`, `{:.5$}`, or `{:a$}`, etc.
271271
Argument(FormatArgPosition),
272272
}

compiler/rustc_ast_lowering/src/expr.rs

+11
Original file line numberDiff line numberDiff line change
@@ -2152,6 +2152,17 @@ impl<'hir> LoweringContext<'_, 'hir> {
21522152
self.expr(sp, hir::ExprKind::Lit(lit))
21532153
}
21542154

2155+
pub(super) fn expr_u16(&mut self, sp: Span, value: u16) -> hir::Expr<'hir> {
2156+
let lit = self.arena.alloc(hir::Lit {
2157+
span: sp,
2158+
node: ast::LitKind::Int(
2159+
u128::from(value).into(),
2160+
ast::LitIntType::Unsigned(ast::UintTy::U16),
2161+
),
2162+
});
2163+
self.expr(sp, hir::ExprKind::Lit(lit))
2164+
}
2165+
21552166
pub(super) fn expr_char(&mut self, sp: Span, value: char) -> hir::Expr<'hir> {
21562167
let lit = self.arena.alloc(hir::Lit { span: sp, node: ast::LitKind::Char(value) });
21572168
self.expr(sp, hir::ExprKind::Lit(lit))

compiler/rustc_ast_lowering/src/format.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ fn make_count<'hir>(
292292
hir::LangItem::FormatCount,
293293
sym::Is,
294294
));
295-
let value = ctx.arena.alloc_from_iter([ctx.expr_usize(sp, *n)]);
295+
let value = ctx.arena.alloc_from_iter([ctx.expr_u16(sp, *n)]);
296296
ctx.expr_call_mut(sp, count_is, value)
297297
}
298298
Some(FormatCount::Argument(arg)) => {

compiler/rustc_parse_format/src/lib.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ pub enum DebugHex {
189189
#[derive(Copy, Clone, Debug, PartialEq)]
190190
pub enum Count<'a> {
191191
/// The count is specified explicitly.
192-
CountIs(usize),
192+
CountIs(u16),
193193
/// The count is specified by the argument with the given name.
194194
CountIsName(&'a str, InnerSpan),
195195
/// The count is specified by the argument at the given index.
@@ -564,7 +564,7 @@ impl<'a> Parser<'a> {
564564
/// consuming a macro argument, `None` if it's the case.
565565
fn position(&mut self) -> Option<Position<'a>> {
566566
if let Some(i) = self.integer() {
567-
Some(ArgumentIs(i))
567+
Some(ArgumentIs(i.into()))
568568
} else {
569569
match self.cur.peek() {
570570
Some(&(lo, c)) if rustc_lexer::is_id_start(c) => {
@@ -770,7 +770,7 @@ impl<'a> Parser<'a> {
770770
/// width.
771771
fn count(&mut self, start: usize) -> Count<'a> {
772772
if let Some(i) = self.integer() {
773-
if self.consume('$') { CountIsParam(i) } else { CountIs(i) }
773+
if self.consume('$') { CountIsParam(i.into()) } else { CountIs(i) }
774774
} else {
775775
let tmp = self.cur.clone();
776776
let word = self.word();
@@ -821,15 +821,15 @@ impl<'a> Parser<'a> {
821821
word
822822
}
823823

824-
fn integer(&mut self) -> Option<usize> {
825-
let mut cur: usize = 0;
824+
fn integer(&mut self) -> Option<u16> {
825+
let mut cur: u16 = 0;
826826
let mut found = false;
827827
let mut overflow = false;
828828
let start = self.current_pos();
829829
while let Some(&(_, c)) = self.cur.peek() {
830830
if let Some(i) = c.to_digit(10) {
831831
let (tmp, mul_overflow) = cur.overflowing_mul(10);
832-
let (tmp, add_overflow) = tmp.overflowing_add(i as usize);
832+
let (tmp, add_overflow) = tmp.overflowing_add(i as u16);
833833
if mul_overflow || add_overflow {
834834
overflow = true;
835835
}
@@ -846,11 +846,11 @@ impl<'a> Parser<'a> {
846846
let overflowed_int = &self.input[start..end];
847847
self.err(
848848
format!(
849-
"integer `{}` does not fit into the type `usize` whose range is `0..={}`",
849+
"integer `{}` does not fit into the type `u16` whose range is `0..={}`",
850850
overflowed_int,
851-
usize::MAX
851+
u16::MAX
852852
),
853-
"integer out of range for `usize`",
853+
"integer out of range for `u16`",
854854
self.span(start, end),
855855
);
856856
}

compiler/rustc_span/src/symbol.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,7 @@ symbols! {
10161016
from_residual,
10171017
from_size_align_unchecked,
10181018
from_str_method,
1019+
from_u16,
10191020
from_usize,
10201021
from_yeet,
10211022
fs_create_dir,

library/core/src/fmt/float.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ fn float_to_decimal_common_exact<T>(
2929
fmt: &mut Formatter<'_>,
3030
num: &T,
3131
sign: flt2dec::Sign,
32-
precision: usize,
32+
precision: u16,
3333
) -> Result
3434
where
3535
T: flt2dec::DecodableFloat,
@@ -40,7 +40,7 @@ where
4040
flt2dec::strategy::grisu::format_exact,
4141
*num,
4242
sign,
43-
precision,
43+
precision.into(),
4444
&mut buf,
4545
&mut parts,
4646
);
@@ -55,7 +55,7 @@ fn float_to_decimal_common_shortest<T>(
5555
fmt: &mut Formatter<'_>,
5656
num: &T,
5757
sign: flt2dec::Sign,
58-
precision: usize,
58+
precision: u16,
5959
) -> Result
6060
where
6161
T: flt2dec::DecodableFloat,
@@ -68,7 +68,7 @@ where
6868
flt2dec::strategy::grisu::format_shortest,
6969
*num,
7070
sign,
71-
precision,
71+
precision.into(),
7272
&mut buf,
7373
&mut parts,
7474
);
@@ -101,7 +101,7 @@ fn float_to_exponential_common_exact<T>(
101101
fmt: &mut Formatter<'_>,
102102
num: &T,
103103
sign: flt2dec::Sign,
104-
precision: usize,
104+
precision: u16,
105105
upper: bool,
106106
) -> Result
107107
where
@@ -113,7 +113,7 @@ where
113113
flt2dec::strategy::grisu::format_exact,
114114
*num,
115115
sign,
116-
precision,
116+
precision.into(),
117117
upper,
118118
&mut buf,
119119
&mut parts,

library/core/src/fmt/mod.rs

+27-24
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,8 @@ pub struct FormattingOptions {
294294
flags: u32,
295295
fill: char,
296296
align: Option<Alignment>,
297-
width: Option<usize>,
298-
precision: Option<usize>,
297+
width: Option<u16>,
298+
precision: Option<u16>,
299299
}
300300

301301
impl FormattingOptions {
@@ -389,7 +389,7 @@ impl FormattingOptions {
389389
/// the padding specified by [`FormattingOptions::fill`]/[`FormattingOptions::align`]
390390
/// will be used to take up the required space.
391391
#[unstable(feature = "formatting_options", issue = "118117")]
392-
pub fn width(&mut self, width: Option<usize>) -> &mut Self {
392+
pub fn width(&mut self, width: Option<u16>) -> &mut Self {
393393
self.width = width;
394394
self
395395
}
@@ -403,7 +403,7 @@ impl FormattingOptions {
403403
/// - For floating-point types, this indicates how many digits after the
404404
/// decimal point should be printed.
405405
#[unstable(feature = "formatting_options", issue = "118117")]
406-
pub fn precision(&mut self, precision: Option<usize>) -> &mut Self {
406+
pub fn precision(&mut self, precision: Option<u16>) -> &mut Self {
407407
self.precision = precision;
408408
self
409409
}
@@ -455,12 +455,12 @@ impl FormattingOptions {
455455
}
456456
/// Returns the current width.
457457
#[unstable(feature = "formatting_options", issue = "118117")]
458-
pub const fn get_width(&self) -> Option<usize> {
458+
pub const fn get_width(&self) -> Option<u16> {
459459
self.width
460460
}
461461
/// Returns the current precision.
462462
#[unstable(feature = "formatting_options", issue = "118117")]
463-
pub const fn get_precision(&self) -> Option<usize> {
463+
pub const fn get_precision(&self) -> Option<u16> {
464464
self.precision
465465
}
466466
/// Returns the current precision.
@@ -1499,15 +1499,18 @@ unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::Placeholder, args: &[rt::Argume
14991499
unsafe { value.fmt(fmt) }
15001500
}
15011501

1502-
unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<usize> {
1502+
unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<u16> {
15031503
match *cnt {
1504+
#[cfg(bootstrap)]
1505+
rt::Count::Is(n) => Some(n as u16),
1506+
#[cfg(not(bootstrap))]
15041507
rt::Count::Is(n) => Some(n),
15051508
rt::Count::Implied => None,
15061509
rt::Count::Param(i) => {
15071510
debug_assert!(i < args.len());
15081511
// SAFETY: cnt and args come from the same Arguments,
15091512
// which guarantees this index is always within bounds.
1510-
unsafe { args.get_unchecked(i).as_usize() }
1513+
unsafe { args.get_unchecked(i).as_u16() }
15111514
}
15121515
}
15131516
}
@@ -1516,11 +1519,11 @@ unsafe fn getcount(args: &[rt::Argument<'_>], cnt: &rt::Count) -> Option<usize>
15161519
#[must_use = "don't forget to write the post padding"]
15171520
pub(crate) struct PostPadding {
15181521
fill: char,
1519-
padding: usize,
1522+
padding: u16,
15201523
}
15211524

15221525
impl PostPadding {
1523-
fn new(fill: char, padding: usize) -> PostPadding {
1526+
fn new(fill: char, padding: u16) -> PostPadding {
15241527
PostPadding { fill, padding }
15251528
}
15261529

@@ -1634,7 +1637,7 @@ impl<'a> Formatter<'a> {
16341637
}
16351638
// Check if we're over the minimum width, if so then we can also
16361639
// just write the bytes.
1637-
Some(min) if width >= min => {
1640+
Some(min) if width >= usize::from(min) => {
16381641
write_prefix(self, sign, prefix)?;
16391642
self.buf.write_str(buf)
16401643
}
@@ -1645,7 +1648,7 @@ impl<'a> Formatter<'a> {
16451648
let old_align =
16461649
crate::mem::replace(&mut self.options.align, Some(Alignment::Right));
16471650
write_prefix(self, sign, prefix)?;
1648-
let post_padding = self.padding(min - width, Alignment::Right)?;
1651+
let post_padding = self.padding(min - width as u16, Alignment::Right)?;
16491652
self.buf.write_str(buf)?;
16501653
post_padding.write(self)?;
16511654
self.options.fill = old_fill;
@@ -1654,7 +1657,7 @@ impl<'a> Formatter<'a> {
16541657
}
16551658
// Otherwise, the sign and prefix goes after the padding
16561659
Some(min) => {
1657-
let post_padding = self.padding(min - width, Alignment::Right)?;
1660+
let post_padding = self.padding(min - width as u16, Alignment::Right)?;
16581661
write_prefix(self, sign, prefix)?;
16591662
self.buf.write_str(buf)?;
16601663
post_padding.write(self)
@@ -1702,26 +1705,26 @@ impl<'a> Formatter<'a> {
17021705
// string being formatted.
17031706
let (s, char_count) = if let Some(max_char_count) = self.options.precision {
17041707
let mut iter = s.char_indices();
1705-
let remaining = match iter.advance_by(max_char_count) {
1708+
let remaining = match iter.advance_by(usize::from(max_char_count)) {
17061709
Ok(()) => 0,
17071710
Err(remaining) => remaining.get(),
17081711
};
17091712
// SAFETY: The offset of `.char_indices()` is guaranteed to be
17101713
// in-bounds and between character boundaries.
17111714
let truncated = unsafe { s.get_unchecked(..iter.offset()) };
1712-
(truncated, max_char_count - remaining)
1715+
(truncated, usize::from(max_char_count) - remaining)
17131716
} else {
17141717
// Use the optimized char counting algorithm for the full string.
17151718
(s, s.chars().count())
17161719
};
17171720

17181721
// The `width` field is more of a minimum width parameter at this point.
17191722
if let Some(width) = self.options.width
1720-
&& char_count < width
1723+
&& char_count < usize::from(width)
17211724
{
17221725
// If we're under the minimum width, then fill up the minimum width
17231726
// with the specified string + some alignment.
1724-
let post_padding = self.padding(width - char_count, Alignment::Left)?;
1727+
let post_padding = self.padding(width - char_count as u16, Alignment::Left)?;
17251728
self.buf.write_str(s)?;
17261729
post_padding.write(self)
17271730
} else {
@@ -1737,7 +1740,7 @@ impl<'a> Formatter<'a> {
17371740
/// thing that is being padded.
17381741
pub(crate) fn padding(
17391742
&mut self,
1740-
padding: usize,
1743+
padding: u16,
17411744
default: Alignment,
17421745
) -> result::Result<PostPadding, Error> {
17431746
let align = self.align().unwrap_or(default);
@@ -1777,19 +1780,19 @@ impl<'a> Formatter<'a> {
17771780

17781781
// remove the sign from the formatted parts
17791782
formatted.sign = "";
1780-
width = width.saturating_sub(sign.len());
1783+
width = width.saturating_sub(sign.len() as u16);
17811784
self.options.fill = '0';
17821785
self.options.align = Some(Alignment::Right);
17831786
}
17841787

17851788
// remaining parts go through the ordinary padding process.
17861789
let len = formatted.len();
1787-
let ret = if width <= len {
1790+
let ret = if usize::from(width) <= len {
17881791
// no padding
17891792
// SAFETY: Per the precondition.
17901793
unsafe { self.write_formatted_parts(&formatted) }
17911794
} else {
1792-
let post_padding = self.padding(width - len, Alignment::Right)?;
1795+
let post_padding = self.padding(width - len as u16, Alignment::Right)?;
17931796
// SAFETY: Per the precondition.
17941797
unsafe {
17951798
self.write_formatted_parts(&formatted)?;
@@ -2021,7 +2024,7 @@ impl<'a> Formatter<'a> {
20212024
#[must_use]
20222025
#[stable(feature = "fmt_flags", since = "1.5.0")]
20232026
pub fn width(&self) -> Option<usize> {
2024-
self.options.width
2027+
self.options.width.map(|x| x as usize)
20252028
}
20262029

20272030
/// Returns the optionally specified precision for numeric types.
@@ -2052,7 +2055,7 @@ impl<'a> Formatter<'a> {
20522055
#[must_use]
20532056
#[stable(feature = "fmt_flags", since = "1.5.0")]
20542057
pub fn precision(&self) -> Option<usize> {
2055-
self.options.precision
2058+
self.options.precision.map(|x| x as usize)
20562059
}
20572060

20582061
/// Determines if the `+` flag was specified.
@@ -2792,7 +2795,7 @@ pub(crate) fn pointer_fmt_inner(ptr_addr: usize, f: &mut Formatter<'_>) -> Resul
27922795
f.options.flags |= 1 << (rt::Flag::SignAwareZeroPad as u32);
27932796

27942797
if f.options.width.is_none() {
2795-
f.options.width = Some((usize::BITS / 4) as usize + 2);
2798+
f.options.width = Some((usize::BITS / 4) as u16 + 2);
27962799
}
27972800
}
27982801
f.options.flags |= 1 << (rt::Flag::Alternate as u32);

library/core/src/fmt/rt.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,11 @@ pub enum Alignment {
4747
#[derive(Copy, Clone)]
4848
pub enum Count {
4949
/// Specified with a literal number, stores the value
50+
#[cfg(bootstrap)]
5051
Is(usize),
52+
/// Specified with a literal number, stores the value
53+
#[cfg(not(bootstrap))]
54+
Is(u16),
5155
/// Specified using `$` and `*` syntaxes, stores the index into `args`
5256
Param(usize),
5357
/// Not specified
@@ -74,7 +78,7 @@ enum ArgumentType<'a> {
7478
formatter: unsafe fn(NonNull<()>, &mut Formatter<'_>) -> Result,
7579
_lifetime: PhantomData<&'a ()>,
7680
},
77-
Count(usize),
81+
Count(u16),
7882
}
7983

8084
/// This struct represents a generic "argument" which is taken by format_args!().
@@ -151,7 +155,10 @@ impl Argument<'_> {
151155
}
152156
#[inline]
153157
pub const fn from_usize(x: &usize) -> Argument<'_> {
154-
Argument { ty: ArgumentType::Count(*x) }
158+
if *x > u16::MAX as usize {
159+
panic!("Formatting argument out of range");
160+
};
161+
Argument { ty: ArgumentType::Count(*x as u16) }
155162
}
156163

157164
/// Format this placeholder argument.
@@ -181,7 +188,7 @@ impl Argument<'_> {
181188
}
182189

183190
#[inline]
184-
pub(super) const fn as_usize(&self) -> Option<usize> {
191+
pub(super) const fn as_u16(&self) -> Option<u16> {
185192
match self.ty {
186193
ArgumentType::Count(count) => Some(count),
187194
ArgumentType::Placeholder { .. } => None,

0 commit comments

Comments
 (0)