Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experiment] Remove format_args_nl!() #111060

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion compiler/rustc_builtin_macros/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,6 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
template_str,
str_style,
template_snippet,
false,
parse::ParseMode::InlineAsm,
);
parser.curarg = curarg;
Expand Down
39 changes: 4 additions & 35 deletions compiler/rustc_builtin_macros/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,21 +153,13 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
Ok(MacroInput { fmtstr, args, is_direct_literal })
}

fn make_format_args(
ecx: &mut ExtCtxt<'_>,
input: MacroInput,
append_newline: bool,
) -> Result<FormatArgs, ()> {
fn make_format_args(ecx: &mut ExtCtxt<'_>, input: MacroInput) -> Result<FormatArgs, ()> {
let msg = "format argument must be a string literal";
let unexpanded_fmt_span = input.fmtstr.span;

let MacroInput { fmtstr: efmt, mut args, is_direct_literal } = input;

let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
Ok(mut fmt) if append_newline => {
fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
fmt
}
Ok(fmt) => fmt,
Err(err) => {
if let Some((mut err, suggested)) = err {
Expand Down Expand Up @@ -196,13 +188,7 @@ fn make_format_args(

let fmt_str = fmt_str.as_str(); // for the suggestions below
let fmt_snippet = ecx.source_map().span_to_snippet(unexpanded_fmt_span).ok();
let mut parser = parse::Parser::new(
fmt_str,
str_style,
fmt_snippet,
append_newline,
parse::ParseMode::Format,
);
let mut parser = parse::Parser::new(fmt_str, str_style, fmt_snippet, parse::ParseMode::Format);

let mut pieces = Vec::new();
while let Some(piece) = parser.next() {
Expand Down Expand Up @@ -831,16 +817,15 @@ fn report_invalid_references(
e.emit();
}

fn expand_format_args_impl<'cx>(
pub fn expand_format_args<'cx>(
ecx: &'cx mut ExtCtxt<'_>,
mut sp: Span,
tts: TokenStream,
nl: bool,
) -> Box<dyn base::MacResult + 'cx> {
sp = ecx.with_def_site_ctxt(sp);
match parse_args(ecx, sp, tts) {
Ok(input) => {
if let Ok(format_args) = make_format_args(ecx, input, nl) {
if let Ok(format_args) = make_format_args(ecx, input) {
MacEager::expr(ecx.expr(sp, ExprKind::FormatArgs(P(format_args))))
} else {
MacEager::expr(DummyResult::raw_expr(sp, true))
Expand All @@ -852,19 +837,3 @@ fn expand_format_args_impl<'cx>(
}
}
}

pub fn expand_format_args<'cx>(
ecx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> {
expand_format_args_impl(ecx, sp, tts, false)
}

pub fn expand_format_args_nl<'cx>(
ecx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> {
expand_format_args_impl(ecx, sp, tts, true)
}
1 change: 0 additions & 1 deletion compiler/rustc_builtin_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
concat: concat::expand_concat,
env: env::expand_env,
file: source_util::expand_file,
format_args_nl: format::expand_format_args_nl,
format_args: format::expand_format_args,
const_format_args: format::expand_format_args,
global_asm: asm::expand_global_asm,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/non_fmt_panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ fn check_panic_str<'tcx>(
Err(_) => (None, None),
};

let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), ParseMode::Format);
let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();

if n_arguments > 0 && fmt_parser.errors.is_empty() {
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_parse_format/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,6 @@ pub struct Parser<'a> {
width_map: Vec<InnerWidthMapping>,
/// Span of the last opening brace seen, used for error reporting
last_opening_brace: Option<InnerSpan>,
/// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
append_newline: bool,
/// Whether this formatting string was written directly in the source. This controls whether we
/// can use spans to refer into it and give better error messages.
/// N.B: This does _not_ control whether implicit argument captures can be used.
Expand Down Expand Up @@ -322,7 +320,6 @@ impl<'a> Parser<'a> {
s: &'a str,
style: Option<usize>,
snippet: Option<string::String>,
append_newline: bool,
mode: ParseMode,
) -> Parser<'a> {
let input_string_kind = find_width_map_from_snippet(s, snippet, style);
Expand All @@ -341,7 +338,6 @@ impl<'a> Parser<'a> {
arg_places: vec![],
width_map,
last_opening_brace: None,
append_newline,
is_source_literal,
cur_line_start: 0,
line_spans: vec![],
Expand Down Expand Up @@ -485,8 +481,7 @@ impl<'a> Parser<'a> {
} else {
let description = format!("expected `{c:?}` but string was terminated");
// point at closing `"`
let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
let pos = self.to_span_index(pos);
let pos = self.to_span_index(self.input.len());
if c == '}' {
let label = format!("expected `{c:?}`");
let (note, secondary_label) = if c == '}' {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_parse_format/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::*;

#[track_caller]
fn same(fmt: &'static str, p: &[Piece<'static>]) {
let parser = Parser::new(fmt, None, None, false, ParseMode::Format);
let parser = Parser::new(fmt, None, None, ParseMode::Format);
assert_eq!(parser.collect::<Vec<Piece<'static>>>(), p);
}

Expand All @@ -24,7 +24,7 @@ fn fmtdflt() -> FormatSpec<'static> {
}

fn musterr(s: &str) {
let mut p = Parser::new(s, None, None, false, ParseMode::Format);
let mut p = Parser::new(s, None, None, ParseMode::Format);
p.next();
assert!(!p.errors.is_empty());
}
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,6 @@ symbols! {
format_args,
format_args_capture,
format_args_macro,
format_args_nl,
format_argument,
format_arguments,
format_count,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,7 @@ impl<'tcx> OnUnimplementedFormatString {
let trait_name = tcx.item_name(trait_def_id);
let generics = tcx.generics_of(item_def_id);
let s = self.0.as_str();
let parser = Parser::new(s, None, None, false, ParseMode::Format);
let parser = Parser::new(s, None, None, ParseMode::Format);
let mut result = Ok(());
for token in parser {
match token {
Expand Down Expand Up @@ -650,7 +650,7 @@ impl<'tcx> OnUnimplementedFormatString {
let empty_string = String::new();

let s = self.0.as_str();
let parser = Parser::new(s, None, None, false, ParseMode::Format);
let parser = Parser::new(s, None, None, ParseMode::Format);
let item_context = (options.get(&sym::ItemContext)).unwrap_or(&empty_string);
parser
.map(|p| match p {
Expand Down
18 changes: 1 addition & 17 deletions library/core/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,13 +549,12 @@ macro_rules! write {
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "writeln_macro")]
#[allow_internal_unstable(format_args_nl)]
macro_rules! writeln {
($dst:expr $(,)?) => {
$crate::write!($dst, "\n")
};
($dst:expr, $($arg:tt)*) => {
$dst.write_fmt($crate::format_args_nl!($($arg)*))
$dst.write_fmt($crate::format_args!("{}\n", $crate::format_args!($($arg)*)))
};
}

Expand Down Expand Up @@ -893,21 +892,6 @@ pub(crate) mod builtin {
($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
}

/// Same as [`format_args`], but adds a newline in the end.
#[unstable(
feature = "format_args_nl",
issue = "none",
reason = "`format_args_nl` is only for internal \
language use and is subject to change"
)]
#[allow_internal_unstable(fmt_internals)]
#[rustc_builtin_macro]
#[macro_export]
macro_rules! format_args_nl {
($fmt:expr) => {{ /* compiler built-in */ }};
($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
}

/// Inspects an environment variable at compile time.
///
/// This macro will expand to the value of the named environment variable at
Expand Down
5 changes: 2 additions & 3 deletions library/core/src/prelude/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ pub use crate::hash::macros::Hash;
#[allow(deprecated)]
#[doc(no_inline)]
pub use crate::{
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args,
format_args_nl, include, include_bytes, include_str, line, log_syntax, module_path, option_env,
stringify, trace_macros,
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args, include,
include_bytes, include_str, line, log_syntax, module_path, option_env, stringify, trace_macros,
};

#[unstable(
Expand Down
5 changes: 2 additions & 3 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,6 @@
#![feature(core_panic)]
#![feature(custom_test_frameworks)]
#![feature(edition_panic)]
#![feature(format_args_nl)]
#![feature(get_many_mut)]
#![feature(lazy_cell)]
#![feature(log_syntax)]
Expand Down Expand Up @@ -621,8 +620,8 @@ pub use core::{
#[allow(deprecated)]
pub use core::{
assert, assert_matches, cfg, column, compile_error, concat, concat_idents, const_format_args,
env, file, format_args, format_args_nl, include, include_bytes, include_str, line, log_syntax,
module_path, option_env, stringify, trace_macros,
env, file, format_args, include, include_bytes, include_str, line, log_syntax, module_path,
option_env, stringify, trace_macros,
};

#[unstable(
Expand Down
8 changes: 4 additions & 4 deletions library/std/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,13 @@ macro_rules! print {
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
#[allow_internal_unstable(print_internals, format_args_nl)]
#[allow_internal_unstable(print_internals)]
macro_rules! println {
() => {
$crate::print!("\n")
};
($($arg:tt)*) => {{
$crate::io::_print($crate::format_args_nl!($($arg)*));
$crate::io::_print($crate::format_args!("{}\n", $crate::format_args!($($arg)*)));
}};
}

Expand Down Expand Up @@ -200,13 +200,13 @@ macro_rules! eprint {
#[macro_export]
#[stable(feature = "eprint", since = "1.19.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
#[allow_internal_unstable(print_internals, format_args_nl)]
#[allow_internal_unstable(print_internals)]
macro_rules! eprintln {
() => {
$crate::eprint!("\n")
};
($($arg:tt)*) => {{
$crate::io::_eprint($crate::format_args_nl!($($arg)*));
$crate::io::_eprint($crate::format_args!("{}\n", $crate::format_args!($($arg)*)));
}};
}

Expand Down
6 changes: 3 additions & 3 deletions library/std/src/prelude/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ pub use crate::result::Result::{self, Err, Ok};
#[allow(deprecated)]
#[doc(no_inline)]
pub use core::prelude::v1::{
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args,
format_args_nl, include, include_bytes, include_str, line, log_syntax, module_path, option_env,
stringify, trace_macros, Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd,
assert, cfg, column, compile_error, concat, concat_idents, env, file, format_args, include,
include_bytes, include_str, line, log_syntax, module_path, option_env, stringify, trace_macros,
Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd,
};

#[unstable(
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2266,7 +2266,7 @@ impl<T: Termination, E: fmt::Debug> Termination for Result<T, E> {
match self {
Ok(val) => val.report(),
Err(err) => {
io::attempt_print_to_stderr(format_args_nl!("Error: {err:?}"));
io::attempt_print_to_stderr(format_args!("Error: {err:?}\n"));
ExitCode::FAILURE
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_utils/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ pub fn find_format_args(cx: &LateContext<'_>, start: &Expr<'_>, expn_id: ExpnId,
if ctxt.outer_expn().is_descendant_of(expn_id) {
if macro_backtrace(expr.span)
.map(|macro_call| cx.tcx.item_name(macro_call.def_id))
.any(|name| matches!(name, sym::const_format_args | sym::format_args | sym::format_args_nl))
.any(|name| matches!(name, sym::const_format_args | sym::format_args))
{
ControlFlow::Break(expr)
} else {
Expand Down
18 changes: 9 additions & 9 deletions src/tools/clippy/tests/ui/explicit_write.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,22 @@ fn main() {
use std::io::Write;
print!("test");
eprint!("test");
println!("test");
eprintln!("test");
println!("{}\n", $crate::format_args!($($arg)*));
eprintln!("{}\n", $crate::format_args!($($arg)*));
print!("test");
eprint!("test");

// including newlines
println!("test\ntest");
eprintln!("test\ntest");
println!("{}\n", $crate::format_args!($($arg)*));
eprintln!("{}\n", $crate::format_args!($($arg)*));

let value = 1;
eprintln!("with {}", value);
eprintln!("with {} {}", 2, value);
eprintln!("with {value}");
eprintln!("macro arg {}", one!());
eprintln!("{}\n", $crate::format_args!($($arg)*));
eprintln!("{}\n", $crate::format_args!($($arg)*));
eprintln!("{}\n", $crate::format_args!($($arg)*));
eprintln!("{}\n", $crate::format_args!($($arg)*));
let width = 2;
eprintln!("{:w$}", value, w = width);
eprintln!("{}\n", $crate::format_args!($($arg)*));
}
// these should not warn, different destination
{
Expand Down
Loading