Skip to content

Commit 975bc18

Browse files
committed
Make Arguments constructors unsafe
1 parent 73d96b0 commit 975bc18

File tree

8 files changed

+114
-41
lines changed

8 files changed

+114
-41
lines changed

compiler/rustc_builtin_macros/src/format.rs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use Position::*;
33

44
use rustc_ast as ast;
55
use rustc_ast::ptr::P;
6-
use rustc_ast::token;
76
use rustc_ast::tokenstream::TokenStream;
7+
use rustc_ast::{token, BlockCheckMode, UnsafeSource};
88
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
99
use rustc_errors::{pluralize, Applicability, DiagnosticBuilder};
1010
use rustc_expand::base::{self, *};
@@ -838,12 +838,15 @@ impl<'a, 'b> Context<'a, 'b> {
838838
//
839839
// But the nested match expression is proved to perform not as well
840840
// as series of let's; the first approach does.
841-
let pat = self.ecx.pat_tuple(self.macsp, pats);
842-
let arm = self.ecx.arm(self.macsp, pat, args_array);
843-
let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
844-
let result = self.ecx.expr_match(self.macsp, head, vec![arm]);
841+
let args_match = {
842+
let pat = self.ecx.pat_tuple(self.macsp, pats);
843+
let arm = self.ecx.arm(self.macsp, pat, args_array);
844+
let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
845+
self.ecx.expr_match(self.macsp, head, vec![arm])
846+
};
845847

846-
let args_slice = self.ecx.expr_addr_of(self.macsp, result);
848+
let ident = Ident::from_str_and_span("args", self.macsp);
849+
let args_slice = self.ecx.expr_ident(self.macsp, ident);
847850

848851
// Now create the fmt::Arguments struct with all our locals we created.
849852
let (fn_name, fn_args) = if self.all_pieces_simple {
@@ -857,7 +860,20 @@ impl<'a, 'b> Context<'a, 'b> {
857860
};
858861

859862
let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
860-
self.ecx.expr_call_global(self.macsp, path, fn_args)
863+
let arguments = self.ecx.expr_call_global(self.macsp, path, fn_args);
864+
let body = self.ecx.expr_block(P(ast::Block {
865+
stmts: vec![self.ecx.stmt_expr(arguments)],
866+
id: ast::DUMMY_NODE_ID,
867+
rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
868+
span: self.macsp,
869+
tokens: None,
870+
}));
871+
872+
let ident = Ident::from_str_and_span("args", self.macsp);
873+
let binding_mode = ast::BindingMode::ByRef(ast::Mutability::Not);
874+
let pat = self.ecx.pat_ident_binding_mode(self.macsp, ident, binding_mode);
875+
let arm = self.ecx.arm(self.macsp, pat, body);
876+
self.ecx.expr_match(self.macsp, args_match, vec![arm])
861877
}
862878

863879
fn format_arg(

library/core/src/fmt/mod.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,11 +334,29 @@ enum FlagV1 {
334334
impl<'a> Arguments<'a> {
335335
/// When using the format_args!() macro, this function is used to generate the
336336
/// Arguments structure.
337+
#[cfg(not(bootstrap))]
338+
#[doc(hidden)]
339+
#[inline]
340+
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
341+
#[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
342+
pub const unsafe fn new_v1(
343+
pieces: &'a [&'static str],
344+
args: &'a [ArgumentV1<'a>],
345+
) -> Arguments<'a> {
346+
if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
347+
panic!("invalid args");
348+
}
349+
Arguments { pieces, fmt: None, args }
350+
}
351+
#[cfg(bootstrap)]
337352
#[doc(hidden)]
338353
#[inline]
339354
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
340355
#[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
341356
pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> {
357+
if pieces.len() < args.len() || pieces.len() > args.len() + 1 {
358+
panic!("invalid args");
359+
}
342360
Arguments { pieces, fmt: None, args }
343361
}
344362

@@ -348,6 +366,19 @@ impl<'a> Arguments<'a> {
348366
/// `CountIsParam` or `CountIsNextParam` has to point to an argument
349367
/// created with `argumentusize`. However, failing to do so doesn't cause
350368
/// unsafety, but will ignore invalid .
369+
#[cfg(not(bootstrap))]
370+
#[doc(hidden)]
371+
#[inline]
372+
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]
373+
#[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")]
374+
pub const unsafe fn new_v1_formatted(
375+
pieces: &'a [&'static str],
376+
args: &'a [ArgumentV1<'a>],
377+
fmt: &'a [rt::v1::Argument],
378+
) -> Arguments<'a> {
379+
Arguments { pieces, fmt: Some(fmt), args }
380+
}
381+
#[cfg(bootstrap)]
351382
#[doc(hidden)]
352383
#[inline]
353384
#[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")]

library/core/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@
110110
//
111111
// Language features:
112112
#![feature(abi_unadjusted)]
113+
#![feature(allow_internal_unsafe)]
113114
#![feature(allow_internal_unstable)]
114115
#![feature(asm)]
115116
#![feature(associated_type_bounds)]

library/core/src/macros/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,7 @@ pub(crate) mod builtin {
828828
/// assert_eq!(s, format!("hello {}", "world"));
829829
/// ```
830830
#[stable(feature = "rust1", since = "1.0.0")]
831+
#[allow_internal_unsafe]
831832
#[allow_internal_unstable(fmt_internals)]
832833
#[rustc_builtin_macro]
833834
#[macro_export]

library/core/src/panicking.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,15 @@ pub fn panic(expr: &'static str) -> ! {
4747
// truncation and padding (even though none is used here). Using
4848
// Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
4949
// output binary, saving up to a few kilobytes.
50-
panic_fmt(fmt::Arguments::new_v1(&[expr], &[]));
50+
panic_fmt(
51+
#[cfg(bootstrap)]
52+
fmt::Arguments::new_v1(&[expr], &[]),
53+
#[cfg(not(bootstrap))]
54+
// SAFETY: Arguments::new_v1 is safe with exactly one str and zero args
55+
unsafe {
56+
fmt::Arguments::new_v1(&[expr], &[])
57+
},
58+
);
5159
}
5260

5361
#[inline]

src/test/pretty/dollar-crate.pp

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010

1111
fn main() {
1212
{
13-
::std::io::_print(::core::fmt::Arguments::new_v1(&["rust\n"],
14-
&match () {
15-
() => [],
16-
}));
13+
::std::io::_print(match match () { () => [], } {
14+
ref args => unsafe {
15+
::core::fmt::Arguments::new_v1(&["rust\n"],
16+
args)
17+
}
18+
});
1719
};
1820
}

src/test/pretty/issue-4264.pp

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,29 +32,39 @@
3232
({
3333
let res =
3434
((::alloc::fmt::format as
35-
for<'r> fn(Arguments<'r>) -> String {format})(((::core::fmt::Arguments::new_v1
36-
as
37-
fn(&[&'static str], &[ArgumentV1]) -> Arguments {Arguments::new_v1})((&([("test"
38-
as
39-
&str)]
40-
as
41-
[&str; 1])
42-
as
43-
&[&str; 1]),
44-
(&(match (()
45-
as
46-
())
47-
{
48-
()
49-
=>
50-
([]
51-
as
52-
[ArgumentV1; 0]),
53-
}
54-
as
55-
[ArgumentV1; 0])
56-
as
57-
&[ArgumentV1; 0]))
35+
for<'r> fn(Arguments<'r>) -> String {format})((match (match (()
36+
as
37+
())
38+
{
39+
()
40+
=>
41+
([]
42+
as
43+
[ArgumentV1; 0]),
44+
}
45+
as
46+
[ArgumentV1; 0])
47+
{
48+
ref args
49+
=>
50+
unsafe
51+
{
52+
((::core::fmt::Arguments::new_v1
53+
as
54+
unsafe fn(&[&'static str], &[ArgumentV1]) -> Arguments {Arguments::new_v1})((&([("test"
55+
as
56+
&str)]
57+
as
58+
[&str; 1])
59+
as
60+
&[&str; 1]),
61+
(args
62+
as
63+
&[ArgumentV1; 0]))
64+
as
65+
Arguments)
66+
}
67+
}
5868
as
5969
Arguments))
6070
as String);

src/test/ui/attributes/key-value-expansion.stderr

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,16 @@ LL | bug!();
1717

1818
error: unexpected token: `{
1919
let res =
20-
::alloc::fmt::format(::core::fmt::Arguments::new_v1(&[""],
21-
&match (&"u8",) {
22-
(arg0,) =>
23-
[::core::fmt::ArgumentV1::new(arg0,
24-
::core::fmt::Display::fmt)],
25-
}));
20+
::alloc::fmt::format(match match (&"u8",) {
21+
(arg0,) =>
22+
[::core::fmt::ArgumentV1::new(arg0,
23+
::core::fmt::Display::fmt)],
24+
} {
25+
ref args => unsafe {
26+
::core::fmt::Arguments::new_v1(&[""],
27+
args)
28+
}
29+
});
2630
res
2731
}.as_str()`
2832
--> $DIR/key-value-expansion.rs:48:23

0 commit comments

Comments
 (0)