Skip to content

Use format args capture #100589

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

Closed
wants to merge 3 commits 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
15 changes: 7 additions & 8 deletions compiler/rustc_parse/src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ impl<'a> StringReader<'a> {
) -> DiagnosticBuilder<'a, !> {
self.sess
.span_diagnostic
.struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
.struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{m}: {}", escaped_char(c)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mixing different types of capture in one format string isn't nice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be fine, since they are all pretty short and in order. But, I can revert those if necessary.

}

fn struct_err_span_char(
Expand All @@ -143,7 +143,7 @@ impl<'a> StringReader<'a> {
) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
self.sess
.span_diagnostic
.struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c)))
.struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{m}: {}", escaped_char(c)))
}

/// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly
Expand Down Expand Up @@ -217,7 +217,7 @@ impl<'a> StringReader<'a> {
self.sess.symbol_gallery.insert(sym, span);
if is_raw_ident {
if !sym.can_be_raw() {
self.err_span(span, &format!("`{}` cannot be a raw identifier", sym));
self.err_span(span, &format!("`{sym}` cannot be a raw identifier"));
}
self.sess.raw_identifier_spans.borrow_mut().push(span);
}
Expand Down Expand Up @@ -481,7 +481,7 @@ impl<'a> StringReader<'a> {

/// As symbol_from, with an explicit endpoint.
fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol {
debug!("taking an ident from {:?} to {:?}", start, end);
debug!("taking an ident from {start:?} to {end:?}");
Symbol::intern(self.str_from_to(start, end))
}

Expand Down Expand Up @@ -607,7 +607,7 @@ impl<'a> StringReader<'a> {
fn report_unknown_prefix(&self, start: BytePos) {
let prefix_span = self.mk_sp(start, self.pos);
let prefix_str = self.str_from_to(start, self.pos);
let msg = format!("prefix `{}` is unknown", prefix_str);
let msg = format!("prefix `{prefix_str}` is unknown");

let expn_data = prefix_span.ctxt().outer_expn_data();

Expand Down Expand Up @@ -650,8 +650,7 @@ impl<'a> StringReader<'a> {
self.pos,
&format!(
"too many `#` symbols: raw strings may be delimited \
by up to 255 `#` symbols, but found {}",
found
by up to 255 `#` symbols, but found {found}"
),
)
}
Expand Down Expand Up @@ -699,7 +698,7 @@ impl<'a> StringReader<'a> {
if c != '_' && c.to_digit(base).is_none() {
let lo = content_start + BytePos(2 + idx);
let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32);
self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base));
self.err_span_(lo, hi, &format!("invalid digit for a base {base} literal"));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/lexer/tokentrees.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ impl<'a> TokenTreesReader<'a> {
// An unexpected closing delimiter (i.e., there is no
// matching opening delimiter).
let token_str = token_to_string(&self.token);
let msg = format!("unexpected closing delimiter: `{}`", token_str);
let msg = format!("unexpected closing delimiter: `{token_str}`");
let mut err =
self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg);

Expand Down
27 changes: 9 additions & 18 deletions compiler/rustc_parse/src/lexer/unescape_error_reporting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ pub(crate) fn emit_unescape_error(
handler.span_suggestion(
span_with_quotes,
msg,
format!("{}\"{}\"", prefix, lit),
format!("{prefix}\"{lit}\""),
Applicability::MachineApplicable,
);
}
Expand All @@ -137,7 +137,7 @@ pub(crate) fn emit_unescape_error(
"character constant must be escaped"
};
handler
.struct_span_err(span, &format!("{}: `{}`", msg, escaped_char(c)))
.struct_span_err(span, &format!("{msg}: `{}`", escaped_char(c)))
.span_suggestion(
char_span,
"escape the character",
Expand Down Expand Up @@ -173,7 +173,7 @@ pub(crate) fn emit_unescape_error(
let label =
if mode.is_bytes() { "unknown byte escape" } else { "unknown character escape" };
let ec = escaped_char(c);
let mut diag = handler.struct_span_err(span, &format!("{}: `{}`", label, ec));
let mut diag = handler.struct_span_err(span, &format!("{label}: `{ec}`"));
diag.span_label(span, label);
if c == '{' || c == '}' && !mode.is_bytes() {
diag.help(
Expand Down Expand Up @@ -214,10 +214,7 @@ pub(crate) fn emit_unescape_error(
};
let c = escaped_char(c);

handler
.struct_span_err(span, &format!("{}: `{}`", msg, c))
.span_label(span, msg)
.emit();
handler.struct_span_err(span, &format!("{msg}: `{c}`")).span_label(span, msg).emit();
}
EscapeError::NonAsciiCharInByte => {
assert!(mode.is_bytes());
Expand All @@ -228,7 +225,7 @@ pub(crate) fn emit_unescape_error(
} else {
String::new()
};
err.span_label(span, &format!("byte constant must be ASCII{}", postfix));
err.span_label(span, &format!("byte constant must be ASCII{postfix}"));
if (c as u32) <= 0xFF {
err.span_suggestion(
span,
Expand All @@ -246,10 +243,7 @@ pub(crate) fn emit_unescape_error(
utf8.push(c);
err.span_suggestion(
span,
&format!(
"if you meant to use the UTF-8 encoding of {:?}, use \\xHH escapes",
c
),
&format!("if you meant to use the UTF-8 encoding of {c:?}, use \\xHH escapes"),
utf8.as_bytes()
.iter()
.map(|b: &u8| format!("\\x{:X}", *b))
Expand All @@ -263,13 +257,13 @@ pub(crate) fn emit_unescape_error(
assert!(mode.is_bytes());
let (c, span) = last_char();
let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 {
format!(" but is {:?}", c)
format!(" but is {c:?}")
} else {
String::new()
};
handler
.struct_span_err(span, "raw byte string must be ASCII")
.span_label(span, &format!("must be ASCII{}", postfix))
.span_label(span, &format!("must be ASCII{postfix}"))
.emit();
}
EscapeError::OutOfRangeHexEscape => {
Expand All @@ -281,10 +275,7 @@ pub(crate) fn emit_unescape_error(
EscapeError::LeadingUnderscoreUnicodeEscape => {
let (c, span) = last_char();
let msg = "invalid start of unicode escape";
handler
.struct_span_err(span, &format!("{}: `{}`", msg, c))
.span_label(span, msg)
.emit();
handler.struct_span_err(span, &format!("{msg}: `{c}`")).span_label(span, msg).emit();
}
EscapeError::OverlongUnicodeEscape => {
handler
Expand Down
8 changes: 3 additions & 5 deletions compiler/rustc_parse/src/lexer/unicode_chars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ pub(super) fn check_for_substitution<'a>(
let span = Span::with_root_ctxt(pos, pos + Pos::from_usize(ch.len_utf8()));

let Some((_ascii_char, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(c, _, _)| c == ascii_char) else {
let msg = format!("substitution character not found for '{}'", ch);
let msg = format!("substitution character not found for '{ch}'");
reader.sess.span_diagnostic.span_bug_no_panic(span, &msg);
return None;
};
Expand All @@ -352,8 +352,7 @@ pub(super) fn check_for_substitution<'a>(
if let Some(s) = peek_delimited(&reader.src[reader.src_index(pos)..], '“', '”') {
let msg = format!(
"Unicode characters '“' (Left Double Quotation Mark) and \
'”' (Right Double Quotation Mark) look like '{}' ({}), but are not",
ascii_char, ascii_name
'”' (Right Double Quotation Mark) look like '{ascii_char}' ({ascii_name}), but are not"
);
err.span_suggestion(
Span::with_root_ctxt(
Expand All @@ -366,8 +365,7 @@ pub(super) fn check_for_substitution<'a>(
);
} else {
let msg = format!(
"Unicode character '{}' ({}) looks like '{}' ({}), but it is not",
ch, u_name, ascii_char, ascii_name
"Unicode character '{ch}' ({u_name}) looks like '{ascii_char}' ({ascii_name}), but it is not"
);
err.span_suggestion(span, &msg, ascii_char, Applicability::MaybeIncorrect);
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_parse/src/parser/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ impl<'a> Parser<'a> {
inner_parse_policy: InnerAttrPolicy<'_>,
) -> PResult<'a, ast::Attribute> {
debug!(
"parse_attribute: inner_parse_policy={:?} self.token={:?}",
inner_parse_policy, self.token
"parse_attribute: inner_parse_policy={inner_parse_policy:?} self.token={:?}",
self.token
);
let lo = self.token.span;
// Attributes can't have attributes of their own [Editor's note: not with that attitude]
Expand Down Expand Up @@ -191,7 +191,7 @@ impl<'a> Parser<'a> {
};
err.span_label(
item.span,
&format!("the inner {} doesn't annotate this {}", attr_name, item.kind.descr()),
&format!("the inner {attr_name} doesn't annotate this {}", item.kind.descr()),
);
err.span_suggestion_verbose(
replacement_span,
Expand Down Expand Up @@ -323,7 +323,7 @@ impl<'a> Parser<'a> {

pub(crate) fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
let lit = self.parse_lit()?;
debug!("checking if {:?} is unusuffixed", lit);
debug!("checking if {lit:?} is unusuffixed");

if !lit.kind.is_unsuffixed() {
self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
Expand Down
19 changes: 7 additions & 12 deletions compiler/rustc_parse/src/parser/attr_wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,11 @@ impl CreateTokenStream for LazyTokenStreamImpl {
// another replace range will capture the *replaced* tokens for the inner
// range, not the original tokens.
for (range, new_tokens) in replace_ranges.iter().rev() {
assert!(!range.is_empty(), "Cannot replace an empty range: {:?}", range);
assert!(!range.is_empty(), "Cannot replace an empty range: {range:?}");
// Replace ranges are only allowed to decrease the number of tokens.
assert!(
range.len() >= new_tokens.len(),
"Range {:?} has greater len than {:?}",
range,
new_tokens
"Range {range:?} has greater len than {new_tokens:?}"
);

// Replace any removed tokens with `FlatToken::Empty`.
Expand Down Expand Up @@ -408,22 +406,19 @@ fn make_token_stream(
FlatToken::Token(Token { kind: TokenKind::CloseDelim(delim), span }) => {
let frame_data = stack
.pop()
.unwrap_or_else(|| panic!("Token stack was empty for token: {:?}", token));
.unwrap_or_else(|| panic!("Token stack was empty for token: {token:?}"));

let (open_delim, open_sp) = frame_data.open_delim_sp.unwrap();
assert_eq!(
open_delim, delim,
"Mismatched open/close delims: open={:?} close={:?}",
open_delim, span
"Mismatched open/close delims: open={open_delim:?} close={span:?}"
);
let dspan = DelimSpan::from_pair(open_sp, span);
let stream = AttrAnnotatedTokenStream::new(frame_data.inner);
let delimited = AttrAnnotatedTokenTree::Delimited(dspan, delim, stream);
stack
.last_mut()
.unwrap_or_else(|| {
panic!("Bottom token frame is missing for token: {:?}", token)
})
.unwrap_or_else(|| panic!("Bottom token frame is missing for token: {token:?}"))
.inner
.push((delimited, Spacing::Alone));
}
Expand Down Expand Up @@ -456,9 +451,9 @@ fn make_token_stream(
spacing,
));
} else {
panic!("Unexpected last token {:?}", last_token)
panic!("Unexpected last token {last_token:?}")
}
}
assert!(stack.is_empty(), "Stack should be empty: final_buf={:?} stack={:?}", final_buf, stack);
assert!(stack.is_empty(), "Stack should be empty: final_buf={final_buf:?} stack={stack:?}");
AttrAnnotatedTokenStream::new(final_buf.inner)
}
4 changes: 2 additions & 2 deletions compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1077,7 +1077,7 @@ impl<'a> Parser<'a> {
}
components.push(Punct(c));
} else {
panic!("unexpected character in a float token: {:?}", c)
panic!("unexpected character in a float token: {c:?}")
}
}
if !ident_like.is_empty() {
Expand Down Expand Up @@ -1149,7 +1149,7 @@ impl<'a> Parser<'a> {
self.error_unexpected_after_dot();
base
}
_ => panic!("unexpected components in a float token: {:?}", components),
_ => panic!("unexpected components in a float token: {components:?}"),
}
}

Expand Down