Auto merge of #94824 - Dylan-DPC:rollup-iamc09j, r=Dylan-DPC

Rollup of 7 pull requests

Successful merges:

 - #93950 (Use modern formatting for format! macros)
 - #94274 (Treat unstable lints as unknown)
 - #94368 ([1/2] Implement macro meta-variable expressions)
 - #94719 (Statically compile libstdc++ everywhere if asked)
 - #94728 (Only emit pointer-like metadata for `Box<T, A>` when `A` is ZST)
 - #94790 (enable portable-simd doctests in Miri)
 - #94811 (Update browser-ui-test version)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2022-03-10 23:10:59 +00:00
commit 352e621368
220 changed files with 2048 additions and 915 deletions

View File

@ -23,7 +23,7 @@ pub enum LitError {
impl LitKind {
/// Converts literal token into a semantic literal.
fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
pub fn from_lit_token(lit: token::Lit) -> Result<LitKind, LitError> {
let token::Lit { kind, symbol, suffix } = lit;
if suffix.is_some() && !kind.may_have_suffix() {
return Err(LitError::InvalidSuffix);

View File

@ -617,7 +617,9 @@ pub fn type_metadata<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll
ty::RawPtr(ty::TypeAndMut { ty: pointee_type, .. }) | ty::Ref(_, pointee_type, _) => {
pointer_or_reference_metadata(cx, t, pointee_type, unique_type_id)
}
ty::Adt(def, _) if def.is_box() => {
// Box<T, A> may have a non-ZST allocator A. In that case, we
// cannot treat Box<T, A> as just an owned alias of `*mut T`.
ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => {
pointer_or_reference_metadata(cx, t, t.boxed_ty(), unique_type_id)
}
ty::FnDef(..) | ty::FnPtr(_) => subroutine_type_metadata(cx, unique_type_id),

View File

@ -1087,12 +1087,12 @@ impl HandlerInner {
let warnings = match self.deduplicated_warn_count {
0 => String::new(),
1 => "1 warning emitted".to_string(),
count => format!("{} warnings emitted", count),
count => format!("{count} warnings emitted"),
};
let errors = match self.deduplicated_err_count {
0 => String::new(),
1 => "aborting due to previous error".to_string(),
count => format!("aborting due to {} previous errors", count),
count => format!("aborting due to {count} previous errors"),
};
if self.treat_err_as_bug() {
return;

View File

@ -3,6 +3,7 @@
#![feature(crate_visibility_modifier)]
#![feature(decl_macro)]
#![feature(if_let_guard)]
#![feature(let_chains)]
#![feature(let_else)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_internals)]

View File

@ -6,17 +6,17 @@
crate mod macro_check;
crate mod macro_parser;
crate mod macro_rules;
crate mod metavar_expr;
crate mod quoted;
crate mod transcribe;
use metavar_expr::MetaVarExpr;
use rustc_ast::token::{self, NonterminalKind, Token, TokenKind};
use rustc_ast::tokenstream::DelimSpan;
use rustc_data_structures::sync::Lrc;
use rustc_span::symbol::Ident;
use rustc_span::Span;
use rustc_data_structures::sync::Lrc;
/// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
/// that the delimiter itself might be `NoDelim`.
#[derive(Clone, PartialEq, Encodable, Decodable, Debug)]
@ -73,8 +73,8 @@ enum KleeneOp {
ZeroOrOne,
}
/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
/// are "first-class" token trees. Useful for parsing macros.
/// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, `$(...)`,
/// and `${...}` are "first-class" token trees. Useful for parsing macros.
#[derive(Debug, Clone, PartialEq, Encodable, Decodable)]
enum TokenTree {
Token(Token),
@ -85,6 +85,8 @@ enum TokenTree {
MetaVar(Span, Ident),
/// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
MetaVarDecl(Span, Ident /* name to bind */, Option<NonterminalKind>),
/// A meta-variable expression inside `${...}`
MetaVarExpr(DelimSpan, MetaVarExpr),
}
impl TokenTree {
@ -139,7 +141,9 @@ impl TokenTree {
TokenTree::Token(Token { span, .. })
| TokenTree::MetaVar(span, _)
| TokenTree::MetaVarDecl(span, _, _) => span,
TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(),
TokenTree::Delimited(span, _)
| TokenTree::MetaVarExpr(span, _)
| TokenTree::Sequence(span, _) => span.entire(),
}
}

View File

@ -278,6 +278,8 @@ fn check_binders(
binders.insert(name, BinderInfo { span, ops: ops.into() });
}
}
// `MetaVarExpr` can not appear in the LHS of a macro arm
TokenTree::MetaVarExpr(..) => {}
TokenTree::Delimited(_, ref del) => {
for tt in &del.tts {
check_binders(sess, node_id, tt, macros, binders, ops, valid);
@ -335,6 +337,8 @@ fn check_occurrences(
let name = MacroRulesNormalizedIdent::new(name);
check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name);
}
// FIXME(c410-f3r) Check token (https://github.com/rust-lang/rust/issues/93902)
TokenTree::MetaVarExpr(..) => {}
TokenTree::Delimited(_, ref del) => {
check_nested_occurrences(sess, node_id, &del.tts, macros, binders, ops, valid);
}

View File

@ -200,7 +200,7 @@ struct MatcherPos<'root, 'tt> {
// This type is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
rustc_data_structures::static_assert_size!(MatcherPos<'_, '_>, 192);
rustc_data_structures::static_assert_size!(MatcherPos<'_, '_>, 240);
impl<'root, 'tt> MatcherPos<'root, 'tt> {
/// Generates the top-level matcher position in which the "dot" is before the first token of
@ -321,10 +321,13 @@ pub(super) fn count_names(ms: &[TokenTree]) -> usize {
ms.iter().fold(0, |count, elt| {
count
+ match *elt {
TokenTree::Sequence(_, ref seq) => seq.num_captures,
TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
TokenTree::MetaVar(..) => 0,
TokenTree::MetaVarDecl(..) => 1,
// FIXME(c410-f3r) MetaVarExpr should be handled instead of being ignored
// https://github.com/rust-lang/rust/issues/9390
TokenTree::MetaVarExpr(..) => 0,
TokenTree::Sequence(_, ref seq) => seq.num_captures,
TokenTree::Token(..) => 0,
}
})
@ -436,7 +439,9 @@ fn nameize<I: Iterator<Item = NamedMatch>>(
}
Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))),
},
TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
// FIXME(c410-f3r) MetaVar and MetaVarExpr should be handled instead of being ignored
// https://github.com/rust-lang/rust/issues/9390
TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) | TokenTree::Token(..) => {}
}
Ok(())
@ -650,7 +655,7 @@ fn inner_parse_loop<'root, 'tt>(
// rules. NOTE that this is not necessarily an error unless _all_ items in
// `cur_items` end up doing this. There may still be some other matchers that do
// end up working out.
TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarExpr(..) => {}
}
}
}

View File

@ -580,7 +580,10 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
use mbe::TokenTree;
for tt in tts {
match *tt {
TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
TokenTree::Token(..)
| TokenTree::MetaVar(..)
| TokenTree::MetaVarDecl(..)
| TokenTree::MetaVarExpr(..) => (),
TokenTree::Delimited(_, ref del) => {
if !check_lhs_no_empty_seq(sess, &del.tts) {
return false;
@ -669,7 +672,10 @@ impl FirstSets {
let mut first = TokenSet::empty();
for tt in tts.iter().rev() {
match *tt {
TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
TokenTree::Token(..)
| TokenTree::MetaVar(..)
| TokenTree::MetaVarDecl(..)
| TokenTree::MetaVarExpr(..) => {
first.replace_with(tt.clone());
}
TokenTree::Delimited(span, ref delimited) => {
@ -731,7 +737,10 @@ impl FirstSets {
for tt in tts.iter() {
assert!(first.maybe_empty);
match *tt {
TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
TokenTree::Token(..)
| TokenTree::MetaVar(..)
| TokenTree::MetaVarDecl(..)
| TokenTree::MetaVarExpr(..) => {
first.add_one(tt.clone());
return first;
}
@ -907,7 +916,10 @@ fn check_matcher_core(
// First, update `last` so that it corresponds to the set
// of NT tokens that might end the sequence `... token`.
match *token {
TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
TokenTree::Token(..)
| TokenTree::MetaVar(..)
| TokenTree::MetaVarDecl(..)
| TokenTree::MetaVarExpr(..) => {
if token_can_be_followed_by_any(token) {
// don't need to track tokens that work with any,
last.replace_with_irrelevant();

View File

@ -0,0 +1,157 @@
use rustc_ast::token;
use rustc_ast::tokenstream::{Cursor, TokenStream, TokenTree};
use rustc_ast::{LitIntType, LitKind};
use rustc_ast_pretty::pprust;
use rustc_errors::{Applicability, PResult};
use rustc_session::parse::ParseSess;
use rustc_span::symbol::Ident;
use rustc_span::Span;
/// A meta-variable expression, for expansions based on properties of meta-variables.
#[derive(Debug, Clone, PartialEq, Encodable, Decodable)]
crate enum MetaVarExpr {
/// The number of repetitions of an identifier, optionally limited to a number
/// of outer-most repetition depths. If the depth limit is `None` then the depth is unlimited.
Count(Ident, Option<usize>),
/// Ignore a meta-variable for repetition without expansion.
Ignore(Ident),
/// The index of the repetition at a particular depth, where 0 is the inner-most
/// repetition. The `usize` is the depth.
Index(usize),
/// The length of the repetition at a particular depth, where 0 is the inner-most
/// repetition. The `usize` is the depth.
Length(usize),
}
impl MetaVarExpr {
/// Attempt to parse a meta-variable expression from a token stream.
crate fn parse<'sess>(
input: &TokenStream,
outer_span: Span,
sess: &'sess ParseSess,
) -> PResult<'sess, MetaVarExpr> {
let mut tts = input.trees();
let ident = parse_ident(&mut tts, sess, outer_span)?;
let Some(TokenTree::Delimited(_, token::Paren, args)) = tts.next() else {
let msg = "meta-variable expression parameter must be wrapped in parentheses";
return Err(sess.span_diagnostic.struct_span_err(ident.span, msg));
};
check_trailing_token(&mut tts, sess)?;
let mut iter = args.trees();
let rslt = match &*ident.as_str() {
"count" => parse_count(&mut iter, sess, ident.span)?,
"ignore" => MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?),
"index" => MetaVarExpr::Index(parse_depth(&mut iter, sess, ident.span)?),
"length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?),
_ => {
let err_msg = "unrecognized meta-variable expression";
let mut err = sess.span_diagnostic.struct_span_err(ident.span, err_msg);
err.span_suggestion(
ident.span,
"supported expressions are count, ignore, index and length",
String::new(),
Applicability::MachineApplicable,
);
return Err(err);
}
};
check_trailing_token(&mut iter, sess)?;
Ok(rslt)
}
crate fn ident(&self) -> Option<&Ident> {
match self {
MetaVarExpr::Count(ident, _) | MetaVarExpr::Ignore(ident) => Some(&ident),
MetaVarExpr::Index(..) | MetaVarExpr::Length(..) => None,
}
}
}
// Checks if there are any remaining tokens. For example, `${ignore(ident ... a b c ...)}`
fn check_trailing_token<'sess>(iter: &mut Cursor, sess: &'sess ParseSess) -> PResult<'sess, ()> {
if let Some(tt) = iter.next() {
let mut diag = sess.span_diagnostic.struct_span_err(
tt.span(),
&format!("unexpected token: {}", pprust::tt_to_string(&tt)),
);
diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
Err(diag)
} else {
Ok(())
}
}
/// Parse a meta-variable `count` expression: `count(ident[, depth])`
fn parse_count<'sess>(
iter: &mut Cursor,
sess: &'sess ParseSess,
span: Span,
) -> PResult<'sess, MetaVarExpr> {
let ident = parse_ident(iter, sess, span)?;
let depth = if try_eat_comma(iter) { Some(parse_depth(iter, sess, span)?) } else { None };
Ok(MetaVarExpr::Count(ident, depth))
}
/// Parses the depth used by index(depth) and length(depth).
fn parse_depth<'sess>(
iter: &mut Cursor,
sess: &'sess ParseSess,
span: Span,
) -> PResult<'sess, usize> {
let Some(tt) = iter.next() else { return Ok(0) };
let TokenTree::Token(token::Token {
kind: token::TokenKind::Literal(lit), ..
}) = tt else {
return Err(sess.span_diagnostic.struct_span_err(
span,
"meta-variable expression depth must be a literal"
));
};
if let Ok(lit_kind) = LitKind::from_lit_token(lit)
&& let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind
&& let Ok(n_usize) = usize::try_from(n_u128)
{
Ok(n_usize)
}
else {
let msg = "only unsuffixes integer literals are supported in meta-variable expressions";
Err(sess.span_diagnostic.struct_span_err(span, msg))
}
}
/// Parses an generic ident
fn parse_ident<'sess>(
iter: &mut Cursor,
sess: &'sess ParseSess,
span: Span,
) -> PResult<'sess, Ident> {
let err_fn = |msg| sess.span_diagnostic.struct_span_err(span, msg);
if let Some(tt) = iter.next() && let TokenTree::Token(token) = tt {
if let Some((elem, false)) = token.ident() {
return Ok(elem);
}
let token_str = pprust::token_to_string(&token);
let mut err = err_fn(&format!("expected identifier, found `{}`", &token_str));
err.span_suggestion(
token.span,
&format!("try removing `{}`", &token_str),
String::new(),
Applicability::MaybeIncorrect,
);
return Err(err);
}
Err(err_fn("expected identifier"))
}
/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the
/// iterator is not modified and the result is `false`.
fn try_eat_comma(iter: &mut Cursor) -> bool {
if let Some(TokenTree::Token(token::Token { kind: token::Comma, .. })) = iter.look_ahead(0) {
let _ = iter.next();
return true;
}
false
}

View File

@ -1,13 +1,13 @@
use crate::mbe::macro_parser;
use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree};
use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree};
use rustc_ast::token::{self, Token};
use rustc_ast::tokenstream;
use rustc_ast::{NodeId, DUMMY_NODE_ID};
use rustc_ast_pretty::pprust;
use rustc_feature::Features;
use rustc_session::parse::ParseSess;
use rustc_span::symbol::{kw, Ident};
use rustc_session::parse::{feature_err, ParseSess};
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::edition::Edition;
use rustc_span::{Span, SyntaxContext};
@ -25,22 +25,22 @@ const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
/// # Parameters
///
/// - `input`: a token stream to read from, the contents of which we are parsing.
/// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
/// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
/// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
/// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
/// pattern, so we pass a parameter to indicate whether to expect them or not.
/// - `parsing_patterns`: `parse` can be used to parse either the "patterns" or the "body" of a
/// macro. Both take roughly the same form _except_ that:
/// - In a pattern, metavars are declared with their "matcher" type. For example `$var:expr` or
/// `$id:ident`. In this example, `expr` and `ident` are "matchers". They are not present in the
/// body of a macro rule -- just in the pattern.
/// - Metavariable expressions are only valid in the "body", not the "pattern".
/// - `sess`: the parsing session. Any errors will be emitted to this session.
/// - `node_id`: the NodeId of the macro we are parsing.
/// - `features`: language features so we can do feature gating.
/// - `edition`: the edition of the crate defining the macro
///
/// # Returns
///
/// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
pub(super) fn parse(
input: tokenstream::TokenStream,
expect_matchers: bool,
parsing_patterns: bool,
sess: &ParseSess,
node_id: NodeId,
features: &Features,
@ -55,9 +55,9 @@ pub(super) fn parse(
while let Some(tree) = trees.next() {
// Given the parsed tree, if there is a metavar and we are expecting matchers, actually
// parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition);
let tree = parse_tree(tree, &mut trees, parsing_patterns, sess, node_id, features, edition);
match tree {
TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
TokenTree::MetaVar(start_sp, ident) if parsing_patterns => {
let span = match trees.next() {
Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => {
match trees.next() {
@ -118,6 +118,14 @@ pub(super) fn parse(
result
}
/// Asks for the `macro_metavar_expr` feature if it is not already declared
fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &ParseSess, span: Span) {
if !features.macro_metavar_expr {
let msg = "meta-variable expressions are unstable";
feature_err(&sess, sym::macro_metavar_expr, span, msg).emit();
}
}
/// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
/// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
/// for use in parsing a macro.
@ -129,14 +137,13 @@ pub(super) fn parse(
/// - `tree`: the tree we wish to convert.
/// - `outer_trees`: an iterator over trees. We may need to read more tokens from it in order to finish
/// converting `tree`
/// - `expect_matchers`: same as for `parse` (see above).
/// - `parsing_patterns`: same as [parse].
/// - `sess`: the parsing session. Any errors will be emitted to this session.
/// - `features`: language features so we can do feature gating.
/// - `edition` - the edition of the crate defining the macro
fn parse_tree(
tree: tokenstream::TokenTree,
outer_trees: &mut impl Iterator<Item = tokenstream::TokenTree>,
expect_matchers: bool,
parsing_patterns: bool,
sess: &ParseSess,
node_id: NodeId,
features: &Features,
@ -158,24 +165,57 @@ fn parse_tree(
}
match next {
// `tree` is followed by a delimited set of token trees. This indicates the beginning
// of a repetition sequence in the macro (e.g. `$(pat)*`).
Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
// Must have `(` not `{` or `[`
if delim != token::Paren {
let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
let msg = format!("expected `(`, found `{}`", tok);
sess.span_diagnostic.span_err(span.entire(), &msg);
// `tree` is followed by a delimited set of token trees.
Some(tokenstream::TokenTree::Delimited(delim_span, delim, tts)) => {
if parsing_patterns {
if delim != token::Paren {
span_dollar_dollar_or_metavar_in_the_lhs_err(
sess,
&Token { kind: token::OpenDelim(delim), span: delim_span.entire() },
);
}
} else {
match delim {
token::Brace => {
// The delimiter is `{`. This indicates the beginning
// of a meta-variable expression (e.g. `${count(ident)}`).
// Try to parse the meta-variable expression.
match MetaVarExpr::parse(&tts, delim_span.entire(), sess) {
Err(mut err) => {
err.emit();
// Returns early the same read `$` to avoid spanning
// unrelated diagnostics that could be performed afterwards
return TokenTree::token(token::Dollar, span);
}
Ok(elem) => {
maybe_emit_macro_metavar_expr_feature(
features,
sess,
delim_span.entire(),
);
return TokenTree::MetaVarExpr(delim_span, elem);
}
}
}
token::Paren => {}
_ => {
let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
let msg = format!("expected `(` or `{{`, found `{}`", tok);
sess.span_diagnostic.span_err(delim_span.entire(), &msg);
}
}
}
// Parse the contents of the sequence itself
let sequence = parse(tts, expect_matchers, sess, node_id, features, edition);
// If we didn't find a metavar expression above, then we must have a
// repetition sequence in the macro (e.g. `$(pat)*`). Parse the
// contents of the sequence itself
let sequence = parse(tts, parsing_patterns, sess, node_id, features, edition);
// Get the Kleene operator and optional separator
let (separator, kleene) =
parse_sep_and_kleene_op(&mut trees, span.entire(), sess);
parse_sep_and_kleene_op(&mut trees, delim_span.entire(), sess);
// Count the number of captured "names" (i.e., named metavars)
let name_captures = macro_parser::count_names(&sequence);
TokenTree::Sequence(
span,
delim_span,
Lrc::new(SequenceRepetition {
tts: sequence,
separator,
@ -197,7 +237,20 @@ fn parse_tree(
}
}
// `tree` is followed by a random token. This is an error.
// `tree` is followed by another `$`. This is an escaped `$`.
Some(tokenstream::TokenTree::Token(Token { kind: token::Dollar, span })) => {
if parsing_patterns {
span_dollar_dollar_or_metavar_in_the_lhs_err(
sess,
&Token { kind: token::Dollar, span },
);
} else {
maybe_emit_macro_metavar_expr_feature(features, sess, span);
}
TokenTree::token(token::Dollar, span)
}
// `tree` is followed by some other token. This is an error.
Some(tokenstream::TokenTree::Token(token)) => {
let msg = format!(
"expected identifier, found `{}`",
@ -221,7 +274,7 @@ fn parse_tree(
span,
Lrc::new(Delimited {
delim,
tts: parse(tts, expect_matchers, sess, node_id, features, edition),
tts: parse(tts, parsing_patterns, sess, node_id, features, edition),
}),
),
}
@ -309,3 +362,15 @@ fn parse_sep_and_kleene_op(
// Return a dummy
(None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
}
// `$$` or a meta-variable is the lhs of a macro but shouldn't.
//
// For example, `macro_rules! foo { ( ${length()} ) => {} }`
fn span_dollar_dollar_or_metavar_in_the_lhs_err<'sess>(sess: &'sess ParseSess, token: &Token) {
sess.span_diagnostic
.span_err(token.span, &format!("unexpected token: {}", pprust::token_to_string(token)));
sess.span_diagnostic.span_note_without_error(
token.span,
"`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
);
}

View File

@ -255,6 +255,11 @@ pub(super) fn transcribe<'a>(
}
}
// Replace meta-variable expressions with the result of their expansion.
mbe::TokenTree::MetaVarExpr(sp, expr) => {
transcribe_metavar_expr(cx, expr, interp, &repeats, &mut result, &sp)?;
}
// If we are entering a new delimiter, we push its contents to the `stack` to be
// processed, and we push all of the currently produced results to the `result_stack`.
// We will produce all of the results of the inside of the `Delimited` and then we will
@ -391,6 +396,28 @@ fn lockstep_iter_size(
_ => LockstepIterSize::Unconstrained,
}
}
TokenTree::MetaVarExpr(_, ref expr) => {
let default_rslt = LockstepIterSize::Unconstrained;
let Some(ident) = expr.ident() else { return default_rslt; };
let name = MacroRulesNormalizedIdent::new(ident.clone());
match lookup_cur_matched(name, interpolations, repeats) {
Some(MatchedSeq(ref ads)) => {
default_rslt.with(LockstepIterSize::Constraint(ads.len(), name))
}
_ => default_rslt,
}
}
TokenTree::Token(..) => LockstepIterSize::Unconstrained,
}
}
fn transcribe_metavar_expr<'a>(
_cx: &ExtCtxt<'a>,
_expr: mbe::MetaVarExpr,
_interp: &FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
_repeats: &[(usize, usize)],
_result: &mut Vec<TreeAndSpacing>,
_sp: &DelimSpan,
) -> PResult<'a, ()> {
Ok(())
}

View File

@ -169,6 +169,8 @@ declare_features! (
(active, staged_api, "1.0.0", None, None),
/// Added for testing E0705; perma-unstable.
(active, test_2018_feature, "1.31.0", None, Some(Edition::Edition2018)),
/// Added for testing unstable lints; perma-unstable.
(active, test_unstable_lint, "1.60.0", None, None),
/// Allows non-`unsafe` —and thus, unsound— access to `Pin` constructions.
/// Marked `incomplete` since perma-unstable and unsound.
(incomplete, unsafe_pin_internals, "1.60.0", None, None),
@ -428,6 +430,8 @@ declare_features! (
(active, link_cfg, "1.14.0", Some(37406), None),
/// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check.
(active, lint_reasons, "1.31.0", Some(54503), None),
/// Give access to additional metadata about declarative macro meta-variables.
(active, macro_metavar_expr, "1.61.0", Some(83527), None),
/// Allows `#[marker]` on certain traits allowing overlapping implementations.
(active, marker_trait_attr, "1.30.0", Some(29864), None),
/// A minimal, sound subset of specialization intended to be used by the

View File

@ -17,7 +17,7 @@ use rustc_session::lint::{
builtin::{self, FORBIDDEN_LINT_GROUPS},
Level, Lint, LintExpectationId, LintId,
};
use rustc_session::parse::feature_err;
use rustc_session::parse::{add_feature_diagnostics, feature_err};
use rustc_session::Session;
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP};
@ -93,10 +93,19 @@ impl<'s> LintLevelsBuilder<'s> {
self.store
}
fn current_specs(&self) -> &FxHashMap<LintId, LevelAndSource> {
&self.sets.list[self.cur].specs
}
fn current_specs_mut(&mut self) -> &mut FxHashMap<LintId, LevelAndSource> {
&mut self.sets.list[self.cur].specs
}
fn process_command_line(&mut self, sess: &Session, store: &LintStore) {
let mut specs = FxHashMap::default();
self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid);
self.cur =
self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: COMMAND_LINE });
for &(ref lint_name, level) in &sess.opts.lint_opts {
store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools);
let orig_level = level;
@ -108,30 +117,24 @@ impl<'s> LintLevelsBuilder<'s> {
};
for id in ids {
// ForceWarn and Forbid cannot be overriden
if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) {
if let Some((Level::ForceWarn | Level::Forbid, _)) = self.current_specs().get(&id) {
continue;
}
self.check_gated_lint(id, DUMMY_SP);
let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
specs.insert(id, (level, src));
if self.check_gated_lint(id, DUMMY_SP) {
let src = LintLevelSource::CommandLine(lint_flag_val, orig_level);
self.current_specs_mut().insert(id, (level, src));
}
}
}
self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE });
}
/// Attempts to insert the `id` to `level_src` map entry. If unsuccessful
/// (e.g. if a forbid was already inserted on the same scope), then emits a
/// diagnostic with no change to `specs`.
fn insert_spec(
&mut self,
specs: &mut FxHashMap<LintId, LevelAndSource>,
id: LintId,
(level, src): LevelAndSource,
) {
fn insert_spec(&mut self, id: LintId, (level, src): LevelAndSource) {
let (old_level, old_src) =
self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess);
self.sets.get_lint_level(id.lint, self.cur, Some(self.current_specs()), &self.sess);
// Setting to a non-forbid level is an error if the lint previously had
// a forbid level. Note that this is not necessarily true even with a
// `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`.
@ -154,7 +157,10 @@ impl<'s> LintLevelsBuilder<'s> {
};
debug!(
"fcw_warning={:?}, specs.get(&id) = {:?}, old_src={:?}, id_name={:?}",
fcw_warning, specs, old_src, id_name
fcw_warning,
self.current_specs(),
old_src,
id_name
);
let decorate_diag = |diag: &mut Diagnostic| {
@ -213,9 +219,9 @@ impl<'s> LintLevelsBuilder<'s> {
}
}
if let Level::ForceWarn = old_level {
specs.insert(id, (old_level, old_src));
self.current_specs_mut().insert(id, (old_level, old_src));
} else {
specs.insert(id, (level, src));
self.current_specs_mut().insert(id, (level, src));
}
}
@ -239,7 +245,9 @@ impl<'s> LintLevelsBuilder<'s> {
is_crate_node: bool,
source_hir_id: Option<HirId>,
) -> BuilderPush {
let mut specs = FxHashMap::default();
let prev = self.cur;
self.cur = self.sets.list.push(LintSet { specs: FxHashMap::default(), parent: prev });
let sess = self.sess;
let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input");
for (attr_index, attr) in attrs.iter().enumerate() {
@ -348,8 +356,9 @@ impl<'s> LintLevelsBuilder<'s> {
reason,
);
for &id in *ids {
self.check_gated_lint(id, attr.span);
self.insert_spec(&mut specs, id, (level, src));
if self.check_gated_lint(id, attr.span) {
self.insert_spec(id, (level, src));
}
}
if let Level::Expect(expect_id) = level {
self.lint_expectations
@ -368,7 +377,7 @@ impl<'s> LintLevelsBuilder<'s> {
reason,
);
for id in ids {
self.insert_spec(&mut specs, *id, (level, src));
self.insert_spec(*id, (level, src));
}
if let Level::Expect(expect_id) = level {
self.lint_expectations
@ -377,8 +386,12 @@ impl<'s> LintLevelsBuilder<'s> {
}
Err((Some(ids), ref new_lint_name)) => {
let lint = builtin::RENAMED_AND_REMOVED_LINTS;
let (lvl, src) =
self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
let (lvl, src) = self.sets.get_lint_level(
lint,
self.cur,
Some(self.current_specs()),
&sess,
);
struct_lint_level(
self.sess,
lint,
@ -408,7 +421,7 @@ impl<'s> LintLevelsBuilder<'s> {
reason,
);
for id in ids {
self.insert_spec(&mut specs, *id, (level, src));
self.insert_spec(*id, (level, src));
}
if let Level::Expect(expect_id) = level {
self.lint_expectations
@ -448,8 +461,12 @@ impl<'s> LintLevelsBuilder<'s> {
CheckLintNameResult::Warning(msg, renamed) => {
let lint = builtin::RENAMED_AND_REMOVED_LINTS;
let (renamed_lint_level, src) =
self.sets.get_lint_level(lint, self.cur, Some(&specs), &sess);
let (renamed_lint_level, src) = self.sets.get_lint_level(
lint,
self.cur,
Some(self.current_specs()),
&sess,
);
struct_lint_level(
self.sess,
lint,
@ -472,8 +489,12 @@ impl<'s> LintLevelsBuilder<'s> {
}
CheckLintNameResult::NoLint(suggestion) => {
let lint = builtin::UNKNOWN_LINTS;
let (level, src) =
self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
let (level, src) = self.sets.get_lint_level(
lint,
self.cur,
Some(self.current_specs()),
self.sess,
);
struct_lint_level(self.sess, lint, level, src, Some(sp.into()), |lint| {
let name = if let Some(tool_ident) = tool_ident {
format!("{}::{}", tool_ident.name, name)
@ -504,8 +525,9 @@ impl<'s> LintLevelsBuilder<'s> {
{
let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason);
for &id in ids {
self.check_gated_lint(id, attr.span);
self.insert_spec(&mut specs, id, (level, src));
if self.check_gated_lint(id, attr.span) {
self.insert_spec(id, (level, src));
}
}
if let Level::Expect(expect_id) = level {
self.lint_expectations
@ -519,7 +541,7 @@ impl<'s> LintLevelsBuilder<'s> {
}
if !is_crate_node {
for (id, &(level, ref src)) in specs.iter() {
for (id, &(level, ref src)) in self.current_specs().iter() {
if !id.lint.crate_level_only {
continue;
}
@ -530,7 +552,7 @@ impl<'s> LintLevelsBuilder<'s> {
let lint = builtin::UNUSED_ATTRIBUTES;
let (lint_level, lint_src) =
self.sets.get_lint_level(lint, self.cur, Some(&specs), self.sess);
self.sets.get_lint_level(lint, self.cur, Some(self.current_specs()), self.sess);
struct_lint_level(
self.sess,
lint,
@ -551,9 +573,9 @@ impl<'s> LintLevelsBuilder<'s> {
}
}
let prev = self.cur;
if !specs.is_empty() {
self.cur = self.sets.list.push(LintSet { specs, parent: prev });
if self.current_specs().is_empty() {
self.sets.list.pop();
self.cur = prev;
}
BuilderPush { prev, changed: prev != self.cur }
@ -574,18 +596,24 @@ impl<'s> LintLevelsBuilder<'s> {
}
/// Checks if the lint is gated on a feature that is not enabled.
fn check_gated_lint(&self, lint_id: LintId, span: Span) {
///
/// Returns `true` if the lint's feature is enabled.
fn check_gated_lint(&self, lint_id: LintId, span: Span) -> bool {
if let Some(feature) = lint_id.lint.feature_gate {
if !self.sess.features_untracked().enabled(feature) {
feature_err(
&self.sess.parse_sess,
feature,
span,
&format!("the `{}` lint is unstable", lint_id.lint.name_lower()),
)
.emit();
let lint = builtin::UNKNOWN_LINTS;
let (level, src) = self.lint_level(builtin::UNKNOWN_LINTS);
struct_lint_level(self.sess, lint, level, src, Some(span.into()), |lint_db| {
let mut db =
lint_db.build(&format!("unknown lint: `{}`", lint_id.lint.name_lower()));
db.note(&format!("the `{}` lint is unstable", lint_id.lint.name_lower(),));
add_feature_diagnostics(&mut db, &self.sess.parse_sess, feature);
db.emit();
});
return false;
}
}
true
}
/// Called after `push` when the scope of a set of attributes are exited.

View File

@ -3128,6 +3128,7 @@ declare_lint_pass! {
SUSPICIOUS_AUTO_TRAIT_IMPLS,
UNEXPECTED_CFGS,
DEPRECATED_WHERE_CLAUSE_LOCATION,
TEST_UNSTABLE_LINT,
]
}
@ -3399,7 +3400,7 @@ declare_lint! {
/// // ^^^^^^^^
/// // This call to try_into matches both Foo:try_into and TryInto::try_into as
/// // `TryInto` has been added to the Rust prelude in 2021 edition.
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
///
@ -3771,3 +3772,25 @@ declare_lint! {
Warn,
"deprecated where clause location"
}
declare_lint! {
/// The `test_unstable_lint` lint tests unstable lints and is perma-unstable.
///
/// ### Example
///
/// ```
/// #![allow(test_unstable_lint)]
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// In order to test the behavior of unstable lints, a permanently-unstable
/// lint is required. This lint can be used to trigger warnings and errors
/// from the compiler related to unstable lints.
pub TEST_UNSTABLE_LINT,
Deny,
"this unstable lint is only for testing",
@feature_gate = sym::test_unstable_lint;
}

View File

@ -281,7 +281,7 @@ pub struct CaptureInfo {
/// let mut t = (0,1);
///
/// let c = || {
/// println!("{}",t); // L1
/// println!("{t}"); // L1
/// t.1 = 4; // L2
/// };
/// ```

View File

@ -98,7 +98,26 @@ pub fn feature_err_issue<'a>(
explain: &str,
) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
let mut err = sess.span_diagnostic.struct_span_err_with_code(span, explain, error_code!(E0658));
add_feature_diagnostics_for_issue(&mut err, sess, feature, issue);
err
}
/// Adds the diagnostics for a feature to an existing error.
pub fn add_feature_diagnostics<'a>(err: &mut Diagnostic, sess: &'a ParseSess, feature: Symbol) {
add_feature_diagnostics_for_issue(err, sess, feature, GateIssue::Language);
}
/// Adds the diagnostics for a feature to an existing error.
///
/// This variant allows you to control whether it is a library or language feature.
/// Almost always, you want to use this for a language feature. If so, prefer
/// `add_feature_diagnostics`.
pub fn add_feature_diagnostics_for_issue<'a>(
err: &mut Diagnostic,
sess: &'a ParseSess,
feature: Symbol,
issue: GateIssue,
) {
if let Some(n) = find_feature_issue(feature, issue) {
err.note(&format!(
"see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information",
@ -110,8 +129,6 @@ pub fn feature_err_issue<'a>(
if sess.unstable_features.is_nightly_build() {
err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
}
err
}
/// Info about a parsing session.

View File

@ -846,6 +846,7 @@ symbols! {
macro_export,
macro_lifetime_matcher,
macro_literal_matcher,
macro_metavar_expr,
macro_reexport,
macro_use,
macro_vis_matcher,
@ -1385,6 +1386,7 @@ symbols! {
test_case,
test_removed_feature,
test_runner,
test_unstable_lint,
then_with,
thread,
thread_local,

View File

@ -458,10 +458,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// let s: String; // hir_id_s
/// let mut p: Point; // his_id_p
/// let c = || {
/// println!("{}", s); // L1
/// println!("{s}"); // L1
/// p.x += 10; // L2
/// println!("{}" , p.y) // L3
/// println!("{}", p) // L4
/// println!("{}" , p.y); // L3
/// println!("{p}"); // L4
/// drop(s); // L5
/// };
/// ```

View File

@ -397,7 +397,7 @@ pub mod __alloc_error_handler {
// if there is no `#[alloc_error_handler]`
#[rustc_std_internal_symbol]
pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! {
panic!("memory allocation of {} bytes failed", size)
panic!("memory allocation of {size} bytes failed")
}
// if there is an `#[alloc_error_handler]`

View File

@ -161,7 +161,7 @@ where
/// let readonly = [1, 2];
/// let borrowed = Items::new((&readonly[..]).into());
/// match borrowed {
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
/// _ => panic!("expect borrowed value"),
/// }
///

View File

@ -31,7 +31,7 @@
//! }
//!
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list);
//! println!("{list:?}");
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
@ -1407,7 +1407,7 @@ impl<T: Copy> From<&[T]> for Box<[T]> {
/// let slice: &[u8] = &[104, 101, 108, 108, 111];
/// let boxed_slice: Box<[u8]> = Box::from(slice);
///
/// println!("{:?}", boxed_slice);
/// println!("{boxed_slice:?}");
/// ```
fn from(slice: &[T]) -> Box<[T]> {
let len = slice.len();
@ -1449,7 +1449,7 @@ impl From<&str> for Box<str> {
///
/// ```rust
/// let boxed: Box<str> = Box::from("hello");
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
#[inline]
fn from(s: &str) -> Box<str> {
@ -1474,14 +1474,14 @@ impl From<Cow<'_, str>> for Box<str> {
///
/// let unboxed = Cow::Borrowed("hello");
/// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
///
/// ```rust
/// # use std::borrow::Cow;
/// let unboxed = Cow::Owned("hello".to_string());
/// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
#[inline]
fn from(cow: Cow<'_, str>) -> Box<str> {
@ -1528,7 +1528,7 @@ impl<T, const N: usize> From<[T; N]> for Box<[T]> {
///
/// ```rust
/// let boxed: Box<[u8]> = Box::from([4, 2]);
/// println!("{:?}", boxed);
/// println!("{boxed:?}");
/// ```
fn from(array: [T; N]) -> Box<[T]> {
box array

View File

@ -194,7 +194,7 @@ use super::SpecExtend;
/// // We can iterate over the items in the heap, although they are returned in
/// // a random order.
/// for x in &heap {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // If we instead pop these scores, they should come back in order.
@ -830,7 +830,7 @@ impl<T> BinaryHeap<T> {
///
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.iter() {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -1110,7 +1110,7 @@ impl<T> BinaryHeap<T> {
///
/// // Will print in some order
/// for x in vec {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
@ -1179,7 +1179,7 @@ impl<T> BinaryHeap<T> {
/// assert!(!heap.is_empty());
///
/// for x in heap.drain() {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// assert!(heap.is_empty());
@ -1624,7 +1624,7 @@ impl<T> IntoIterator for BinaryHeap<T> {
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.into_iter() {
/// // x has type i32, not &i32
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
fn into_iter(self) -> IntoIter<T> {

View File

@ -104,8 +104,8 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
/// let to_find = ["Up!", "Office Space"];
/// for movie in &to_find {
/// match movie_reviews.get(movie) {
/// Some(review) => println!("{}: {}", movie, review),
/// None => println!("{} is unreviewed.", movie)
/// Some(review) => println!("{movie}: {review}"),
/// None => println!("{movie} is unreviewed.")
/// }
/// }
///
@ -114,7 +114,7 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
///
/// // iterate over everything.
/// for (movie, review) in &movie_reviews {
/// println!("{}: \"{}\"", movie, review);
/// println!("{movie}: \"{review}\"");
/// }
/// ```
///
@ -1061,7 +1061,7 @@ impl<K, V> BTreeMap<K, V> {
/// map.insert(5, "b");
/// map.insert(8, "c");
/// for (&key, &value) in map.range((Included(&4), Included(&8))) {
/// println!("{}: {}", key, value);
/// println!("{key}: {value}");
/// }
/// assert_eq!(Some((&5, &"b")), map.range(4..).next());
/// ```
@ -1104,7 +1104,7 @@ impl<K, V> BTreeMap<K, V> {
/// *balance += 100;
/// }
/// for (name, balance) in &map {
/// println!("{} => {}", name, balance);
/// println!("{name} => {balance}");
/// }
/// ```
#[stable(feature = "btree_range", since = "1.17.0")]
@ -2088,7 +2088,7 @@ impl<K, V> BTreeMap<K, V> {
/// map.insert(1, "a");
///
/// for (key, value) in map.iter() {
/// println!("{}: {}", key, value);
/// println!("{key}: {value}");
/// }
///
/// let (first_key, first_value) = map.iter().next().unwrap();

View File

@ -1758,7 +1758,7 @@ fn test_ord_absence() {
}
fn map_debug<K: Debug>(mut map: BTreeMap<K, ()>) {
format!("{:?}", map);
format!("{map:?}");
format!("{:?}", map.iter());
format!("{:?}", map.iter_mut());
format!("{:?}", map.keys());

View File

@ -60,7 +60,7 @@ use super::Recover;
///
/// // Iterate over everything.
/// for book in &books {
/// println!("{}", book);
/// println!("{book}");
/// }
/// ```
///
@ -284,7 +284,7 @@ impl<T> BTreeSet<T> {
/// set.insert(5);
/// set.insert(8);
/// for &elem in set.range((Included(&4), Included(&8))) {
/// println!("{}", elem);
/// println!("{elem}");
/// }
/// assert_eq!(Some(&5), set.range(4..).next());
/// ```

View File

@ -431,10 +431,10 @@ fn test_show() {
set.insert(1);
set.insert(2);
let set_str = format!("{:?}", set);
let set_str = format!("{set:?}");
assert_eq!(set_str, "{1, 2}");
assert_eq!(format!("{:?}", empty), "{}");
assert_eq!(format!("{empty:?}"), "{}");
}
#[test]
@ -649,7 +649,7 @@ fn test_ord_absence() {
}
fn set_debug<K: Debug>(set: BTreeSet<K>) {
format!("{:?}", set);
format!("{set:?}");
format!("{:?}", set.iter());
format!("{:?}", set.into_iter());
}

View File

@ -416,9 +416,9 @@
//! fn main() {
//! let myvector = Vector2D { x: 3, y: 4 };
//!
//! println!("{}", myvector); // => "(3, 4)"
//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}"
//! println!("{:10.3b}", myvector); // => " 5.000"
//! println!("{myvector}"); // => "(3, 4)"
//! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}"
//! println!("{myvector:10.3b}"); // => " 5.000"
//! }
//! ```
//!

View File

@ -309,7 +309,7 @@ fn test_cowrc_clone_weak() {
#[test]
fn test_show() {
let foo = Rc::new(75);
assert_eq!(format!("{:?}", foo), "75");
assert_eq!(format!("{foo:?}"), "75");
}
#[test]
@ -324,7 +324,7 @@ fn test_maybe_thin_unsized() {
use std::ffi::{CStr, CString};
let x: Rc<CStr> = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
assert_eq!(format!("{:?}", x), "\"swordfish\"");
assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Rc::downgrade(&x);
drop(x);
@ -451,7 +451,7 @@ fn test_from_box_trait_zero_sized() {
let b: Box<dyn Debug> = box ();
let r: Rc<dyn Debug> = Rc::from(b);
assert_eq!(format!("{:?}", r), "()");
assert_eq!(format!("{r:?}"), "()");
}
#[test]

View File

@ -48,7 +48,7 @@
//! ```
//! let numbers = &[0, 1, 2];
//! for n in numbers {
//! println!("{} is a number!", n);
//! println!("{n} is a number!");
//! }
//! ```
//!

View File

@ -2718,7 +2718,7 @@ impl From<String> for Vec<u8> {
/// let v1 = Vec::from(s1);
///
/// for b in v1 {
/// println!("{}", b);
/// println!("{b}");
/// }
/// ```
fn from(string: String) -> Vec<u8> {

View File

@ -200,7 +200,7 @@ macro_rules! acquire {
/// let five = Arc::clone(&five);
///
/// thread::spawn(move || {
/// println!("{:?}", five);
/// println!("{five:?}");
/// });
/// }
/// ```
@ -221,7 +221,7 @@ macro_rules! acquire {
///
/// thread::spawn(move || {
/// let v = val.fetch_add(1, Ordering::SeqCst);
/// println!("{:?}", v);
/// println!("{v:?}");
/// });
/// }
/// ```

View File

@ -335,7 +335,7 @@ fn test_weak_count() {
#[test]
fn show_arc() {
let a = Arc::new(5);
assert_eq!(format!("{:?}", a), "5");
assert_eq!(format!("{a:?}"), "5");
}
// Make sure deriving works with Arc<T>
@ -347,7 +347,7 @@ struct Foo {
#[test]
fn test_unsized() {
let x: Arc<[i32]> = Arc::new([1, 2, 3]);
assert_eq!(format!("{:?}", x), "[1, 2, 3]");
assert_eq!(format!("{x:?}"), "[1, 2, 3]");
let y = Arc::downgrade(&x.clone());
drop(x);
assert!(y.upgrade().is_none());
@ -359,7 +359,7 @@ fn test_maybe_thin_unsized() {
use std::ffi::{CStr, CString};
let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
assert_eq!(format!("{:?}", x), "\"swordfish\"");
assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Arc::downgrade(&x);
drop(x);
@ -509,7 +509,7 @@ fn test_from_box_trait_zero_sized() {
let b: Box<dyn Debug> = box ();
let r: Arc<dyn Debug> = Arc::from(b);
assert_eq!(format!("{:?}", r), "()");
assert_eq!(format!("{r:?}"), "()");
}
#[test]

View File

@ -47,8 +47,8 @@ fn any_move() {
fn test_show() {
let a = Box::new(8) as Box<dyn Any>;
let b = Box::new(Test) as Box<dyn Any>;
let a_str = format!("{:?}", a);
let b_str = format!("{:?}", b);
let a_str = format!("{a:?}");
let b_str = format!("{b:?}");
assert_eq!(a_str, "Any { .. }");
assert_eq!(b_str, "Any { .. }");
@ -56,9 +56,9 @@ fn test_show() {
static TEST: Test = Test;
let a = &EIGHT as &dyn Any;
let b = &TEST as &dyn Any;
let s = format!("{:?}", a);
let s = format!("{a:?}");
assert_eq!(s, "Any { .. }");
let s = format!("{:?}", b);
let s = format!("{b:?}");
assert_eq!(s, "Any { .. }");
}

View File

@ -169,7 +169,7 @@ mod spec_extend;
/// vec.extend([1, 2, 3].iter().copied());
///
/// for x in &vec {
/// println!("{}", x);
/// println!("{x}");
/// }
/// assert_eq!(vec, [7, 1, 2, 3]);
/// ```
@ -211,7 +211,7 @@ mod spec_extend;
///
/// while let Some(top) = stack.pop() {
/// // Prints 3, 2, 1
/// println!("{}", top);
/// println!("{top}");
/// }
/// ```
///
@ -1297,7 +1297,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
fn assert_failed(index: usize, len: usize) -> ! {
panic!("swap_remove index (is {}) should be < len (is {})", index, len);
panic!("swap_remove index (is {index}) should be < len (is {len})");
}
let len = self.len();
@ -1338,7 +1338,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
fn assert_failed(index: usize, len: usize) -> ! {
panic!("insertion index (is {}) should be <= len (is {})", index, len);
panic!("insertion index (is {index}) should be <= len (is {len})");
}
let len = self.len();
@ -1397,7 +1397,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[inline(never)]
#[track_caller]
fn assert_failed(index: usize, len: usize) -> ! {
panic!("removal index (is {}) should be < len (is {})", index, len);
panic!("removal index (is {index}) should be < len (is {len})");
}
let len = self.len();
@ -1942,7 +1942,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
fn assert_failed(at: usize, len: usize) -> ! {
panic!("`at` split index (is {}) should be <= len (is {})", at, len);
panic!("`at` split index (is {at}) should be <= len (is {len})");
}
if at > self.len() {
@ -2568,7 +2568,7 @@ impl<T, A: Allocator> IntoIterator for Vec<T, A> {
/// let v = vec!["a".to_string(), "b".to_string()];
/// for s in v.into_iter() {
/// // s has type String, not &String
/// println!("{}", s);
/// println!("{s}");
/// }
/// ```
#[inline]

View File

@ -84,8 +84,8 @@ fn test_format_macro_interface() {
}
t!(format!("{:p}", 0x1234 as *const isize), "0x1234");
t!(format!("{:p}", 0x1234 as *mut isize), "0x1234");
t!(format!("{:x}", A), "aloha");
t!(format!("{:X}", B), "adios");
t!(format!("{A:x}"), "aloha");
t!(format!("{B:X}"), "adios");
t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃");
t!(format!("{1} {0}", 0, 1), "1 0");
t!(format!("{foo} {bar}", foo = 0, bar = 1), "0 1");
@ -94,11 +94,11 @@ fn test_format_macro_interface() {
t!(format!("{_foo}", _foo = 6usize), "6");
t!(format!("{foo_bar}", foo_bar = 1), "1");
t!(format!("{}", 5 + 5), "10");
t!(format!("{:#4}", C), "☃123");
t!(format!("{:b}", D), "aa☃bb");
t!(format!("{C:#4}"), "☃123");
t!(format!("{D:b}"), "aa☃bb");
let a: &dyn fmt::Debug = &1;
t!(format!("{:?}", a), "1");
t!(format!("{a:?}"), "1");
// Formatting strings and their arguments
t!(format!("{}", "a"), "a");
@ -206,7 +206,7 @@ fn test_format_macro_interface() {
// Test that pointers don't get truncated.
{
let val = usize::MAX;
let exp = format!("{:#x}", val);
let exp = format!("{val:#x}");
t!(format!("{:p}", val as *const isize), exp);
}
@ -216,14 +216,14 @@ fn test_format_macro_interface() {
// make sure that format! doesn't move out of local variables
let a = Box::new(3);
format!("{}", a);
format!("{}", a);
format!("{a}");
format!("{a}");
// make sure that format! doesn't cause spurious unused-unsafe warnings when
// it's inside of an outer unsafe block
unsafe {
let a: isize = ::std::mem::transmute(3_usize);
format!("{}", a);
format!("{a}");
}
// test that trailing commas are acceptable
@ -315,9 +315,9 @@ fn test_once() {
#[test]
fn test_refcell() {
let refcell = RefCell::new(5);
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }");
assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }");
let borrow = refcell.borrow_mut();
assert_eq!(format!("{:?}", refcell), "RefCell { value: <borrowed> }");
assert_eq!(format!("{refcell:?}"), "RefCell { value: <borrowed> }");
drop(borrow);
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }");
assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }");
}

View File

@ -302,10 +302,10 @@ fn test_ord_nan() {
#[test]
fn test_show() {
let list: LinkedList<_> = (0..10).collect();
assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
assert_eq!(format!("{list:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let list: LinkedList<_> = ["just", "one", "test", "more"].into_iter().collect();
assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]");
assert_eq!(format!("{list:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
}
#[test]

View File

@ -1045,10 +1045,10 @@ fn test_split_iterators_size_hint() {
a(v.rsplit_mut(p), b, "rsplit_mut");
for n in 0..=3 {
a(v.splitn(n, p), b, f!("splitn, n = {}", n));
a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {}", n));
a(v.rsplitn(n, p), b, f!("rsplitn, n = {}", n));
a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {}", n));
a(v.splitn(n, p), b, f!("splitn, n = {n}"));
a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {n}"));
a(v.rsplitn(n, p), b, f!("rsplitn, n = {n}"));
a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {n}"));
}
}
}
@ -1184,8 +1184,8 @@ fn test_show() {
macro_rules! test_show_vec {
($x:expr, $x_str:expr) => {{
let (x, x_str) = ($x, $x_str);
assert_eq!(format!("{:?}", x), x_str);
assert_eq!(format!("{:?}", x), x_str);
assert_eq!(format!("{x:?}"), x_str);
assert_eq!(format!("{x:?}"), x_str);
}};
}
let empty = Vec::<i32>::new();

View File

@ -1259,7 +1259,7 @@ fn test_chars_debug() {
let s = "ศไทย中华Việt Nam";
let c = s.chars();
assert_eq!(
format!("{:?}", c),
format!("{c:?}"),
r#"Chars(['ศ', 'ไ', 'ท', 'ย', '中', '华', 'V', 'i', 'ệ', 't', ' ', 'N', 'a', 'm'])"#
);
}
@ -1870,7 +1870,7 @@ mod pattern {
}
if let Some(err) = err {
panic!("Input skipped range at {}", err);
panic!("Input skipped range at {err}");
}
if first_index != haystack.len() {
@ -2187,10 +2187,10 @@ fn utf8() {
fn check_str_eq(a: String, b: String) {
let mut i: isize = 0;
for ab in a.bytes() {
println!("{}", i);
println!("{}", ab);
println!("{i}");
println!("{ab}");
let bb: u8 = b.as_bytes()[i as usize];
println!("{}", bb);
println!("{bb}");
assert_eq!(ab, bb);
i += 1;
}

View File

@ -470,7 +470,7 @@ fn test_simple_types() {
#[test]
fn test_vectors() {
let x: Vec<i32> = vec![];
assert_eq!(format!("{:?}", x), "[]");
assert_eq!(format!("{x:?}"), "[]");
assert_eq!(format!("{:?}", vec![1]), "[1]");
assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]");
@ -871,6 +871,6 @@ fn test_from_char() {
fn test_str_concat() {
let a: String = "hello".to_string();
let b: String = "world".to_string();
let s: String = format!("{}{}", a, b);
let s: String = format!("{a}{b}");
assert_eq!(s.as_bytes()[9], 'd' as u8);
}

View File

@ -100,7 +100,7 @@ fn test_debug_fmt() {
assert_eq!("[0, 1]", format!("{:?}", vec2));
let slice: &[isize] = &[4, 5];
assert_eq!("[4, 5]", format!("{:?}", slice));
assert_eq!("[4, 5]", format!("{slice:?}"));
}
#[test]
@ -918,7 +918,7 @@ fn test_into_iter_as_mut_slice() {
fn test_into_iter_debug() {
let vec = vec!['a', 'b', 'c'];
let into_iter = vec.into_iter();
let debug = format!("{:?}", into_iter);
let debug = format!("{into_iter:?}");
assert_eq!(debug, "IntoIter(['a', 'b', 'c'])");
}
@ -2336,7 +2336,7 @@ fn test_vec_dedup_panicking() {
let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index);
if !ok {
panic!("expected: {:?}\ngot: {:?}\n", expected, vec);
panic!("expected: {expected:?}\ngot: {vec:?}\n");
}
}

View File

@ -647,10 +647,10 @@ fn test_ord() {
#[test]
fn test_show() {
let ringbuf: VecDeque<_> = (0..10).collect();
assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
assert_eq!(format!("{ringbuf:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]");
assert_eq!(format!("{ringbuf:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
}
#[test]

View File

@ -12,7 +12,7 @@ use test::Bencher;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded),
full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
}
}

View File

@ -6,7 +6,7 @@ use test::Bencher;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded),
full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
}
}

View File

@ -62,7 +62,7 @@
//! println!("String ({}): {}", as_string.len(), as_string);
//! }
//! None => {
//! println!("{:?}", value);
//! println!("{value:?}");
//! }
//! }
//! }

View File

@ -85,7 +85,7 @@
//! // of scope then the subsequent borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`.
//! let total: i32 = shared_map.borrow().values().sum();
//! println!("{}", total);
//! println!("{total}");
//! }
//! ```
//!

View File

@ -370,7 +370,7 @@ impl char {
///
/// ```
/// for c in '❤'.escape_unicode() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -448,7 +448,7 @@ impl char {
///
/// ```
/// for c in '\n'.escape_debug() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -504,7 +504,7 @@ impl char {
///
/// ```
/// for c in '"'.escape_default() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -949,7 +949,7 @@ impl char {
///
/// ```
/// for c in 'İ'.to_lowercase() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -1016,7 +1016,7 @@ impl char {
///
/// ```
/// for c in 'ß'.to_uppercase() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```

View File

@ -64,7 +64,7 @@ pub mod rt {
///
/// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
///
/// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)");
/// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub type Result = result::Result<(), Error>;
@ -174,7 +174,7 @@ pub trait Write {
/// use std::fmt::{Error, Write};
///
/// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
/// f.write_fmt(format_args!("{}", s))
/// f.write_fmt(format_args!("{s}"))
/// }
///
/// let mut buf = String::new();
@ -562,7 +562,7 @@ impl Display for Arguments<'_> {
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
/// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
/// ```
///
/// Manually implementing:
@ -586,7 +586,7 @@ impl Display for Arguments<'_> {
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }");
/// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
/// ```
///
/// There are a number of helper methods on the [`Formatter`] struct to help you with manual
@ -627,7 +627,7 @@ impl Display for Arguments<'_> {
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {:#?}", origin),
/// assert_eq!(format!("The origin is: {origin:#?}"),
/// "The origin is: Point {
/// x: 0,
/// y: 0,
@ -670,9 +670,9 @@ pub trait Debug {
/// }
///
/// let position = Position { longitude: 1.987, latitude: 2.983 };
/// assert_eq!(format!("{:?}", position), "(1.987, 2.983)");
/// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
///
/// assert_eq!(format!("{:#?}", position), "(
/// assert_eq!(format!("{position:#?}"), "(
/// 1.987,
/// 2.983,
/// )");
@ -724,7 +724,7 @@ pub use macros::Debug;
///
/// let origin = Point { x: 0, y: 0 };
///
/// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)");
/// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
/// ```
#[rustc_on_unimplemented(
on(
@ -786,8 +786,8 @@ pub trait Display {
/// ```
/// let x = 42; // 42 is '52' in octal
///
/// assert_eq!(format!("{:o}", x), "52");
/// assert_eq!(format!("{:#o}", x), "0o52");
/// assert_eq!(format!("{x:o}"), "52");
/// assert_eq!(format!("{x:#o}"), "0o52");
///
/// assert_eq!(format!("{:o}", -16), "37777777760");
/// ```
@ -809,9 +809,9 @@ pub trait Display {
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11");
/// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
///
/// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011");
/// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Octal {
@ -840,8 +840,8 @@ pub trait Octal {
/// ```
/// let x = 42; // 42 is '101010' in binary
///
/// assert_eq!(format!("{:b}", x), "101010");
/// assert_eq!(format!("{:#b}", x), "0b101010");
/// assert_eq!(format!("{x:b}"), "101010");
/// assert_eq!(format!("{x:#b}"), "0b101010");
///
/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
/// ```
@ -863,10 +863,10 @@ pub trait Octal {
///
/// let l = Length(107);
///
/// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011");
/// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
///
/// assert_eq!(
/// format!("l as binary is: {:#032b}", l),
/// format!("l as binary is: {l:#032b}"),
/// "l as binary is: 0b000000000000000000000001101011"
/// );
/// ```
@ -898,8 +898,8 @@ pub trait Binary {
/// ```
/// let x = 42; // 42 is '2a' in hex
///
/// assert_eq!(format!("{:x}", x), "2a");
/// assert_eq!(format!("{:#x}", x), "0x2a");
/// assert_eq!(format!("{x:x}"), "2a");
/// assert_eq!(format!("{x:#x}"), "0x2a");
///
/// assert_eq!(format!("{:x}", -16), "fffffff0");
/// ```
@ -921,9 +921,9 @@ pub trait Binary {
///
/// let l = Length(9);
///
/// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9");
/// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
///
/// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009");
/// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerHex {
@ -953,8 +953,8 @@ pub trait LowerHex {
/// ```
/// let x = 42; // 42 is '2A' in hex
///
/// assert_eq!(format!("{:X}", x), "2A");
/// assert_eq!(format!("{:#X}", x), "0x2A");
/// assert_eq!(format!("{x:X}"), "2A");
/// assert_eq!(format!("{x:#X}"), "0x2A");
///
/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
/// ```
@ -976,9 +976,9 @@ pub trait LowerHex {
///
/// let l = Length(i32::MAX);
///
/// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF");
/// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
///
/// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF");
/// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperHex {
@ -1003,7 +1003,7 @@ pub trait UpperHex {
/// ```
/// let x = &42;
///
/// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0'
/// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
/// ```
///
/// Implementing `Pointer` on a type:
@ -1024,9 +1024,9 @@ pub trait UpperHex {
///
/// let l = Length(42);
///
/// println!("l is in memory here: {:p}", l);
/// println!("l is in memory here: {l:p}");
///
/// let l_ptr = format!("{:018p}", l);
/// let l_ptr = format!("{l:018p}");
/// assert_eq!(l_ptr.len(), 18);
/// assert_eq!(&l_ptr[..2], "0x");
/// ```
@ -1054,7 +1054,7 @@ pub trait Pointer {
/// ```
/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
///
/// assert_eq!(format!("{:e}", x), "4.2e1");
/// assert_eq!(format!("{x:e}"), "4.2e1");
/// ```
///
/// Implementing `LowerExp` on a type:
@ -1074,12 +1074,12 @@ pub trait Pointer {
/// let l = Length(100);
///
/// assert_eq!(
/// format!("l in scientific notation is: {:e}", l),
/// format!("l in scientific notation is: {l:e}"),
/// "l in scientific notation is: 1e2"
/// );
///
/// assert_eq!(
/// format!("l in scientific notation is: {:05e}", l),
/// format!("l in scientific notation is: {l:05e}"),
/// "l in scientific notation is: 001e2"
/// );
/// ```
@ -1105,7 +1105,7 @@ pub trait LowerExp {
/// ```
/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
///
/// assert_eq!(format!("{:E}", x), "4.2E1");
/// assert_eq!(format!("{x:E}"), "4.2E1");
/// ```
///
/// Implementing `UpperExp` on a type:
@ -1125,12 +1125,12 @@ pub trait LowerExp {
/// let l = Length(100);
///
/// assert_eq!(
/// format!("l in scientific notation is: {:E}", l),
/// format!("l in scientific notation is: {l:E}"),
/// "l in scientific notation is: 1E2"
/// );
///
/// assert_eq!(
/// format!("l in scientific notation is: {:05E}", l),
/// format!("l in scientific notation is: {l:05E}"),
/// "l in scientific notation is: 001E2"
/// );
/// ```
@ -1429,8 +1429,8 @@ impl<'a> Formatter<'a> {
/// }
/// }
///
/// assert_eq!(&format!("{:<4}", Foo), "Foo ");
/// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
/// assert_eq!(&format!("{Foo:<4}"), "Foo ");
/// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pad(&mut self, s: &str) -> Result {
@ -1613,8 +1613,8 @@ impl<'a> Formatter<'a> {
/// }
/// }
///
/// assert_eq!(&format!("{}", Foo), "Foo");
/// assert_eq!(&format!("{:0>8}", Foo), "Foo");
/// assert_eq!(&format!("{Foo}"), "Foo");
/// assert_eq!(&format!("{Foo:0>8}"), "Foo");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write_str(&mut self, data: &str) -> Result {
@ -1670,18 +1670,18 @@ impl<'a> Formatter<'a> {
/// let c = formatter.fill();
/// if let Some(width) = formatter.width() {
/// for _ in 0..width {
/// write!(formatter, "{}", c)?;
/// write!(formatter, "{c}")?;
/// }
/// Ok(())
/// } else {
/// write!(formatter, "{}", c)
/// write!(formatter, "{c}")
/// }
/// }
/// }
///
/// // We set alignment to the right with ">".
/// assert_eq!(&format!("{:G>3}", Foo), "GGG");
/// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
/// assert_eq!(&format!("{Foo:G>3}"), "GGG");
/// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
/// ```
#[must_use]
#[stable(feature = "fmt_flags", since = "1.5.0")]
@ -1711,14 +1711,14 @@ impl<'a> Formatter<'a> {
/// } else {
/// "into the void"
/// };
/// write!(formatter, "{}", s)
/// write!(formatter, "{s}")
/// }
/// }
///
/// assert_eq!(&format!("{:<}", Foo), "left");
/// assert_eq!(&format!("{:>}", Foo), "right");
/// assert_eq!(&format!("{:^}", Foo), "center");
/// assert_eq!(&format!("{}", Foo), "into the void");
/// assert_eq!(&format!("{Foo:<}"), "left");
/// assert_eq!(&format!("{Foo:>}"), "right");
/// assert_eq!(&format!("{Foo:^}"), "center");
/// assert_eq!(&format!("{Foo}"), "into the void");
/// ```
#[must_use]
#[stable(feature = "fmt_flags_align", since = "1.28.0")]

View File

@ -34,7 +34,7 @@ use crate::ops::Try;
///
/// for pair in ['a', 'b', 'c'].into_iter()
/// .map(|letter| { c += 1; (letter, c) }) {
/// println!("{:?}", pair);
/// println!("{pair:?}");
/// }
/// ```
///
@ -52,7 +52,7 @@ use crate::ops::Try;
/// for pair in ['a', 'b', 'c'].into_iter()
/// .map(|letter| { c += 1; (letter, c) })
/// .rev() {
/// println!("{:?}", pair);
/// println!("{pair:?}");
/// }
/// ```
#[must_use = "iterators are lazy and do nothing unless consumed"]

View File

@ -144,7 +144,7 @@
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -164,7 +164,7 @@
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -181,7 +181,7 @@
//! None => break,
//! };
//! let x = next;
//! let () = { println!("{}", x); };
//! let () = { println!("{x}"); };
//! },
//! };
//! result
@ -280,7 +280,7 @@
//! ```
//! # #![allow(unused_must_use)]
//! let v = vec![1, 2, 3, 4, 5];
//! v.iter().map(|x| println!("{}", x));
//! v.iter().map(|x| println!("{x}"));
//! ```
//!
//! This will not print any values, as we only created an iterator, rather than
@ -297,10 +297,10 @@
//! ```
//! let v = vec![1, 2, 3, 4, 5];
//!
//! v.iter().for_each(|x| println!("{}", x));
//! v.iter().for_each(|x| println!("{x}"));
//! // or
//! for x in &v {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -329,7 +329,7 @@
//! let five_numbers = numbers.take(5);
//!
//! for number in five_numbers {
//! println!("{}", number);
//! println!("{number}");
//! }
//! ```
//!
@ -345,7 +345,7 @@
//! let ones = std::iter::repeat(1);
//! let least = ones.min().unwrap(); // Oh no! An infinite loop!
//! // `ones.min()` causes an infinite loop, so we won't reach this point!
//! println!("The smallest number one is {}.", least);
//! println!("The smallest number one is {least}.");
//! ```
//!
//! [`take`]: Iterator::take

View File

@ -48,7 +48,7 @@ use crate::iter::{FusedIterator, TrustedLen};
///
/// // this will give us all of the files in .foo as well as .foorc
/// for f in files {
/// println!("{:?}", f);
/// println!("{f:?}");
/// }
/// ```
#[stable(feature = "iter_once", since = "1.2.0")]

View File

@ -52,7 +52,7 @@ use crate::iter::{FusedIterator, TrustedLen};
///
/// // this will give us all of the files in .foo as well as .foorc
/// for f in files {
/// println!("{:?}", f);
/// println!("{f:?}");
/// }
/// ```
#[inline]

View File

@ -227,7 +227,7 @@ pub trait FromIterator<A>: Sized {
/// {
/// collection
/// .into_iter()
/// .map(|item| format!("{:?}", item))
/// .map(|item| format!("{item:?}"))
/// .collect()
/// }
/// ```
@ -345,7 +345,7 @@ impl<I: Iterator> IntoIterator for I {
/// c.extend(vec![1, 2, 3]);
///
/// // we've added these elements onto the end
/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c));
/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Extend<A> {

View File

@ -281,7 +281,7 @@ pub trait DoubleEndedIterator: Iterator {
/// let zero = "0".to_string();
///
/// let result = numbers.iter().rfold(zero, |acc, &x| {
/// format!("({} + {})", x, acc)
/// format!("({x} + {acc})")
/// });
///
/// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");

View File

@ -709,13 +709,13 @@ pub trait Iterator {
/// ```
/// # #![allow(unused_must_use)]
/// // don't do this:
/// (0..5).map(|x| println!("{}", x));
/// (0..5).map(|x| println!("{x}"));
///
/// // it won't even execute, as it is lazy. Rust will warn you about this.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]
@ -761,7 +761,7 @@ pub trait Iterator {
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// .for_each(|(i, x)| println!("{i}:{x}"));
/// ```
#[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")]
@ -1575,17 +1575,17 @@ pub trait Iterator {
/// .filter(|x| x % 2 == 0)
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// println!("{sum}");
///
/// // let's add some inspect() calls to investigate what's happening
/// let sum = a.iter()
/// .cloned()
/// .inspect(|x| println!("about to filter: {}", x))
/// .inspect(|x| println!("about to filter: {x}"))
/// .filter(|x| x % 2 == 0)
/// .inspect(|x| println!("made it through filter: {}", x))
/// .inspect(|x| println!("made it through filter: {x}"))
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// println!("{sum}");
/// ```
///
/// This will print:
@ -1611,13 +1611,13 @@ pub trait Iterator {
/// .map(|line| line.parse::<i32>())
/// .inspect(|num| {
/// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e);
/// println!("Parsing error: {e}");
/// }
/// })
/// .filter_map(Result::ok)
/// .sum();
///
/// println!("Sum: {}", sum);
/// println!("Sum: {sum}");
/// ```
///
/// This will print:
@ -2205,7 +2205,7 @@ pub trait Iterator {
///
/// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
///
/// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
/// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
/// assert!(res.is_ok());
///
/// let mut it = data.iter().cloned();
@ -2319,7 +2319,7 @@ pub trait Iterator {
/// let zero = "0".to_string();
///
/// let result = numbers.iter().fold(zero, |acc, &x| {
/// format!("({} + {})", acc, x)
/// format!("({acc} + {x})")
/// });
///
/// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");

View File

@ -412,12 +412,10 @@ pub mod arch {
#[allow(missing_debug_implementations, dead_code, unsafe_op_in_unsafe_fn, unused_unsafe)]
#[allow(rustdoc::bare_urls)]
#[unstable(feature = "portable_simd", issue = "86656")]
#[cfg(not(all(miri, doctest)))] // Skip SIMD doctests in Miri
mod core_simd;
#[doc = include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")]
#[unstable(feature = "portable_simd", issue = "86656")]
#[cfg(not(all(miri, doctest)))] // Skip SIMD doctests in Miri
pub mod simd {
#[unstable(feature = "portable_simd", issue = "86656")]
pub use crate::core_simd::simd::*;

View File

@ -895,7 +895,7 @@ pub(crate) mod builtin {
///
/// ```
/// let path: &'static str = env!("PATH");
/// println!("the $PATH variable at the time of compiling was: {}", path);
/// println!("the $PATH variable at the time of compiling was: {path}");
/// ```
///
/// You can customize the error message by passing a string as the second
@ -935,7 +935,7 @@ pub(crate) mod builtin {
///
/// ```
/// let key: Option<&'static str> = option_env!("SECRET_KEY");
/// println!("the secret key might be: {:?}", key);
/// println!("the secret key might be: {key:?}");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro]
@ -1046,7 +1046,7 @@ pub(crate) mod builtin {
///
/// ```
/// let current_line = line!();
/// println!("defined on line: {}", current_line);
/// println!("defined on line: {current_line}");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro]
@ -1074,7 +1074,7 @@ pub(crate) mod builtin {
///
/// ```
/// let current_col = column!();
/// println!("defined on column: {}", current_col);
/// println!("defined on column: {current_col}");
/// ```
///
/// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
@ -1112,7 +1112,7 @@ pub(crate) mod builtin {
///
/// ```
/// let this_file = file!();
/// println!("defined in file: {}", this_file);
/// println!("defined in file: {this_file}");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro]
@ -1176,7 +1176,7 @@ pub(crate) mod builtin {
/// fn main() {
/// let my_str = include_str!("spanish.in");
/// assert_eq!(my_str, "adiós\n");
/// print!("{}", my_str);
/// print!("{my_str}");
/// }
/// ```
///
@ -1325,7 +1325,7 @@ pub(crate) mod builtin {
/// fn main() {
/// let my_string = include!("monkeys.in");
/// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
/// println!("{}", my_string);
/// println!("{my_string}");
/// }
/// ```
///

View File

@ -219,7 +219,7 @@ pub trait StructuralEq {
///
/// // `x` has moved into `y`, and so cannot be used
///
/// // println!("{:?}", x); // error: use of moved value
/// // println!("{x:?}"); // error: use of moved value
/// ```
///
/// However, if a type implements `Copy`, it instead has 'copy semantics':
@ -236,7 +236,7 @@ pub trait StructuralEq {
///
/// // `y` is a copy of `x`
///
/// println!("{:?}", x); // A-OK!
/// println!("{x:?}"); // A-OK!
/// ```
///
/// It's important to note that in these two examples, the only difference is whether you

View File

@ -163,7 +163,7 @@ from_str_float_impl!(f64);
/// use std::str::FromStr;
///
/// if let Err(e) = f64::from_str("a.12") {
/// println!("Failed conversion to f64: {}", e);
/// println!("Failed conversion to f64: {e}");
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]

View File

@ -61,7 +61,7 @@ impl const From<!> for TryFromIntError {
///
/// ```
/// if let Err(e) = i32::from_str_radix("a12", 10) {
/// println!("Failed conversion to i32: {}", e);
/// println!("Failed conversion to i32: {e}");
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]

View File

@ -106,7 +106,7 @@ pub trait Index<Idx: ?Sized> {
/// type Output = Weight;
///
/// fn index(&self, index: Side) -> &Self::Output {
/// println!("Accessing {:?}-side of balance immutably", index);
/// println!("Accessing {index:?}-side of balance immutably");
/// match index {
/// Side::Left => &self.left,
/// Side::Right => &self.right,
@ -116,7 +116,7 @@ pub trait Index<Idx: ?Sized> {
///
/// impl IndexMut<Side> for Balance {
/// fn index_mut(&mut self, index: Side) -> &mut Self::Output {
/// println!("Accessing {:?}-side of balance mutably", index);
/// println!("Accessing {index:?}-side of balance mutably");
/// match index {
/// Side::Left => &mut self.left,
/// Side::Right => &mut self.right,

View File

@ -653,7 +653,7 @@ impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
/// map.insert(8, "c");
///
/// for (key, value) in map.range((Excluded(3), Included(8))) {
/// println!("{}: {}", key, value);
/// println!("{key}: {value}");
/// }
///
/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());

View File

@ -34,7 +34,7 @@
//! // Pattern match to retrieve the value
//! match result {
//! // The division was valid
//! Some(x) => println!("Result: {}", x),
//! Some(x) => println!("Result: {x}"),
//! // The division was invalid
//! None => println!("Cannot divide by 0"),
//! }
@ -66,7 +66,7 @@
//!
//! fn check_optional(optional: Option<Box<i32>>) {
//! match optional {
//! Some(p) => println!("has value {}", p),
//! Some(p) => println!("has value {p}"),
//! None => println!("has no value"),
//! }
//! }
@ -493,7 +493,7 @@
//! }
//!
//! match name_of_biggest_animal {
//! Some(name) => println!("the biggest animal is {}", name),
//! Some(name) => println!("the biggest animal is {name}"),
//! None => println!("there are no animals :("),
//! }
//! ```
@ -615,7 +615,7 @@ impl<T> Option<T> {
/// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
/// // then consume *that* with `map`, leaving `text` on the stack.
/// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
/// println!("still can print text: {:?}", text);
/// println!("still can print text: {text:?}");
/// ```
#[inline]
#[rustc_const_stable(feature = "const_option", since = "1.48.0")]
@ -918,10 +918,10 @@ impl<T> Option<T> {
/// let v = vec![1, 2, 3, 4, 5];
///
/// // prints "got: 4"
/// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x));
/// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
///
/// // prints nothing
/// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x));
/// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
/// ```
#[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")]
@ -1976,7 +1976,7 @@ impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
/// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
/// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
///
/// println!("Can still print s: {:?}", s);
/// println!("Can still print s: {s:?}");
///
/// assert_eq!(o, Some(18));
/// ```

View File

@ -16,7 +16,7 @@ use crate::panic::Location;
///
/// panic::set_hook(Box::new(|panic_info| {
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {:?}", s);
/// println!("panic occurred: {s:?}");
/// } else {
/// println!("panic occurred");
/// }
@ -75,7 +75,7 @@ impl<'a> PanicInfo<'a> {
///
/// panic::set_hook(Box::new(|panic_info| {
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {:?}", s);
/// println!("panic occurred: {s:?}");
/// } else {
/// println!("panic occurred");
/// }

View File

@ -39,7 +39,7 @@ use crate::panic::{Location, PanicInfo};
#[rustc_const_unstable(feature = "core_panic", issue = "none")]
#[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
pub const fn panic(expr: &'static str) -> ! {
// Use Arguments::new_v1 instead of format_args!("{}", expr) to potentially
// Use Arguments::new_v1 instead of format_args!("{expr}") to potentially
// reduce size overhead. The format_args! macro uses str's Display trait to
// write expr, which calls Formatter::pad, which must accommodate string
// truncation and padding (even though none is used here). Using
@ -81,7 +81,7 @@ fn panic_bounds_check(index: usize, len: usize) -> ! {
super::intrinsics::abort()
}
panic!("index out of bounds: the len is {} but the index is {}", len, index)
panic!("index out of bounds: the len is {len} but the index is {index}")
}
// This function is called directly by the codegen backend, and must not have

View File

@ -607,7 +607,7 @@ mod prim_pointer {}
///
/// // This loop prints: 0 1 2
/// for x in array {
/// print!("{} ", x);
/// print!("{x} ");
/// }
/// ```
///
@ -646,19 +646,19 @@ mod prim_pointer {}
/// // This creates a slice iterator, producing references to each value.
/// for item in array.into_iter().enumerate() {
/// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
///
/// // The `array_into_iter` lint suggests this change for future compatibility:
/// for item in array.iter().enumerate() {
/// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
///
/// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
/// for item in IntoIterator::into_iter(array).enumerate() {
/// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
/// ```
///
@ -673,13 +673,13 @@ mod prim_pointer {}
/// // This iterates by reference:
/// for item in array.iter().enumerate() {
/// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
///
/// // This iterates by value:
/// for item in array.into_iter().enumerate() {
/// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
/// ```
///
@ -702,26 +702,26 @@ mod prim_pointer {}
/// // This iterates by reference:
/// for item in array.iter() {
/// let x: &i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // This iterates by value:
/// for item in IntoIterator::into_iter(array) {
/// let x: i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // This iterates by value:
/// for item in array {
/// let x: i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // IntoIter can also start a chain.
/// // This iterates by value:
/// for item in IntoIterator::into_iter(array).enumerate() {
/// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
/// ```
///

View File

@ -153,7 +153,7 @@ impl<T: ?Sized> *const T {
///
/// unsafe {
/// if let Some(val_back) = ptr.as_ref() {
/// println!("We got back the value: {}!", val_back);
/// println!("We got back the value: {val_back}!");
/// }
/// }
/// ```
@ -169,7 +169,7 @@ impl<T: ?Sized> *const T {
///
/// unsafe {
/// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back);
/// println!("We got back the value: {val_back}!");
/// }
/// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")]

View File

@ -160,7 +160,7 @@ impl<T: ?Sized> *mut T {
///
/// unsafe {
/// if let Some(val_back) = ptr.as_ref() {
/// println!("We got back the value: {}!", val_back);
/// println!("We got back the value: {val_back}!");
/// }
/// }
/// ```
@ -176,7 +176,7 @@ impl<T: ?Sized> *mut T {
///
/// unsafe {
/// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back);
/// println!("We got back the value: {val_back}!");
/// }
/// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
@ -409,7 +409,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { ptr.as_mut().unwrap() };
/// *first_value = 4;
/// # assert_eq!(s, [4, 2, 3]);
/// println!("{:?}", s); // It'll print: "[4, 2, 3]".
/// println!("{s:?}"); // It'll print: "[4, 2, 3]".
/// ```
///
/// # Null-unchecked version
@ -424,7 +424,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { &mut *ptr };
/// *first_value = 4;
/// # assert_eq!(s, [4, 2, 3]);
/// println!("{:?}", s); // It'll print: "[4, 2, 3]".
/// println!("{s:?}"); // It'll print: "[4, 2, 3]".
/// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]

View File

@ -314,7 +314,7 @@ impl<T: ?Sized> NonNull<T> {
/// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
///
/// let ref_x = unsafe { ptr.as_ref() };
/// println!("{}", ref_x);
/// println!("{ref_x}");
/// ```
///
/// [the module documentation]: crate::ptr#safety

View File

@ -35,8 +35,8 @@
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//! Ok(v) => println!("working with version: {:?}", v),
//! Err(e) => println!("error parsing header: {:?}", e),
//! Ok(v) => println!("working with version: {v:?}"),
//! Err(e) => println!("error parsing header: {e:?}"),
//! }
//! ```
//!
@ -447,9 +447,9 @@
//! .collect();
//! assert_eq!(errs.len(), 3);
//! assert_eq!(nums, [17, 99]);
//! println!("results {:?}", results);
//! println!("errs {:?}", errs);
//! println!("nums {:?}", nums);
//! println!("results {results:?}");
//! println!("errs {errs:?}");
//! println!("nums {nums:?}");
//! ```
//!
//! ## Collecting into `Result`
@ -756,7 +756,7 @@ impl<T, E> Result<T, E> {
///
/// for num in line.lines() {
/// match num.parse::<i32>().map(|i| i * 2) {
/// Ok(n) => println!("{}", n),
/// Ok(n) => println!("{n}"),
/// Err(..) => {}
/// }
/// }
@ -838,7 +838,7 @@ impl<T, E> Result<T, E> {
/// Basic usage:
///
/// ```
/// fn stringify(x: u32) -> String { format!("error code: {}", x) }
/// fn stringify(x: u32) -> String { format!("error code: {x}") }
///
/// let x: Result<u32, u32> = Ok(2);
/// assert_eq!(x.map_err(stringify), Ok(2));
@ -864,7 +864,7 @@ impl<T, E> Result<T, E> {
///
/// let x: u8 = "4"
/// .parse::<u8>()
/// .inspect(|x| println!("original: {}", x))
/// .inspect(|x| println!("original: {x}"))
/// .map(|x| x.pow(3))
/// .expect("failed to parse number");
/// ```
@ -889,7 +889,7 @@ impl<T, E> Result<T, E> {
///
/// fn read() -> io::Result<String> {
/// fs::read_to_string("address.txt")
/// .inspect_err(|e| eprintln!("failed to read file: {}", e))
/// .inspect_err(|e| eprintln!("failed to read file: {e}"))
/// }
/// ```
#[inline]
@ -1198,7 +1198,7 @@ impl<T, E> Result<T, E> {
/// }
///
/// let s: String = only_good_news().into_ok();
/// println!("{}", s);
/// println!("{s}");
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
@ -1235,7 +1235,7 @@ impl<T, E> Result<T, E> {
/// }
///
/// let error: String = only_bad_news().into_err();
/// println!("{}", error);
/// println!("{error}");
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
@ -1781,7 +1781,7 @@ impl<T> Result<T, T> {
#[cold]
#[track_caller]
fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
panic!("{}: {:?}", msg, error)
panic!("{msg}: {error:?}")
}
// This is a separate function to avoid constructing a `dyn Debug`

View File

@ -48,7 +48,7 @@ const fn slice_start_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack
fn slice_start_index_len_fail_rt(index: usize, len: usize) -> ! {
panic!("range start index {} out of range for slice of length {}", index, len);
panic!("range start index {index} out of range for slice of length {len}");
}
const fn slice_start_index_len_fail_ct(_: usize, _: usize) -> ! {
@ -69,7 +69,7 @@ const fn slice_end_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack
fn slice_end_index_len_fail_rt(index: usize, len: usize) -> ! {
panic!("range end index {} out of range for slice of length {}", index, len);
panic!("range end index {index} out of range for slice of length {len}");
}
const fn slice_end_index_len_fail_ct(_: usize, _: usize) -> ! {
@ -88,7 +88,7 @@ const fn slice_index_order_fail(index: usize, end: usize) -> ! {
// FIXME const-hack
fn slice_index_order_fail_rt(index: usize, end: usize) -> ! {
panic!("slice index starts at {} but ends at {}", index, end);
panic!("slice index starts at {index} but ends at {end}");
}
const fn slice_index_order_fail_ct(_: usize, _: usize) -> ! {

View File

@ -55,7 +55,7 @@ fn size_from_ptr<T>(_: *const T) -> usize {
///
/// // Then, we iterate over it:
/// for element in slice.iter() {
/// println!("{}", element);
/// println!("{element}");
/// }
/// ```
///
@ -176,7 +176,7 @@ impl<T> AsRef<[T]> for Iter<'_, T> {
/// }
///
/// // We now have "[2, 3, 4]":
/// println!("{:?}", slice);
/// println!("{slice:?}");
/// ```
///
/// [`iter_mut`]: slice::iter_mut
@ -266,7 +266,7 @@ impl<'a, T> IterMut<'a, T> {
/// *iter.next().unwrap() += 1;
/// }
/// // Now slice is "[2, 2, 3]":
/// println!("{:?}", slice);
/// println!("{slice:?}");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "iter_to_slice", since = "1.4.0")]

View File

@ -16,7 +16,6 @@ use crate::option::Option::{None, Some};
use crate::ptr;
use crate::result::Result;
use crate::result::Result::{Err, Ok};
#[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests
use crate::simd::{self, Simd};
use crate::slice;
@ -2012,7 +2011,7 @@ impl<T> [T] {
/// let v = [10, 40, 30, 20, 60, 50];
///
/// for group in v.splitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group);
/// println!("{group:?}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -2067,7 +2066,7 @@ impl<T> [T] {
/// let v = [10, 40, 30, 20, 60, 50];
///
/// for group in v.rsplitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group);
/// println!("{group:?}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -3544,7 +3543,6 @@ impl<T> [T] {
/// assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
/// ```
#[unstable(feature = "portable_simd", issue = "86656")]
#[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests
pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
where
Simd<T, LANES>: AsRef<[T; LANES]>,
@ -3588,7 +3586,6 @@ impl<T> [T] {
/// be lifted in a way that would make it possible to see panics from this
/// method for something like `LANES == 3`.
#[unstable(feature = "portable_simd", issue = "86656")]
#[cfg(not(all(miri, doctest)))] // Miri skips SIMD doctests
pub fn as_simd_mut<const LANES: usize>(&mut self) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
where
Simd<T, LANES>: AsMut<[T; LANES]>,

View File

@ -104,7 +104,7 @@ fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
// 1. out of bounds
if begin > s.len() || end > s.len() {
let oob_index = if begin > s.len() { begin } else { end };
panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis);
panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
}
// 2. begin <= end
@ -2446,7 +2446,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_debug() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -2492,7 +2492,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_default() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -2530,7 +2530,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_unicode() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```

View File

@ -94,7 +94,7 @@
//! }
//!
//! if let Err(panic) = thread.join() {
//! println!("Thread had an error: {:?}", panic);
//! println!("Thread had an error: {panic:?}");
//! }
//! }
//! ```
@ -1345,7 +1345,7 @@ impl const From<bool> for AtomicBool {
/// ```
/// use std::sync::atomic::AtomicBool;
/// let atomic_bool = AtomicBool::from(true);
/// assert_eq!(format!("{:?}", atomic_bool), "true")
/// assert_eq!(format!("{atomic_bool:?}"), "true")
/// ```
#[inline]
fn from(b: bool) -> Self {

View File

@ -1214,7 +1214,7 @@ impl fmt::Debug for Duration {
/// use std::time::Duration;
///
/// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
/// println!("Failed conversion to Duration: {}", e);
/// println!("Failed conversion to Duration: {e}");
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]

View File

@ -9,7 +9,7 @@ use crate::iter::FromIterator;
/// use std::io::*;
/// let data = vec![1, 2, 3, 4, 5];
/// let res: Result<()> = data.iter()
/// .map(|x| writeln!(stdout(), "{}", x))
/// .map(|x| writeln!(stdout(), "{x}"))
/// .collect();
/// assert!(res.is_ok());
/// ```

View File

@ -46,12 +46,12 @@ fn any_downcast_ref() {
match a.downcast_ref::<usize>() {
Some(&5) => {}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match a.downcast_ref::<Test>() {
None => {}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
}
@ -69,7 +69,7 @@ fn any_downcast_mut() {
assert_eq!(*x, 5);
*x = 612;
}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match b_r.downcast_mut::<usize>() {
@ -77,27 +77,27 @@ fn any_downcast_mut() {
assert_eq!(*x, 7);
*x = 413;
}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match a_r.downcast_mut::<Test>() {
None => (),
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match b_r.downcast_mut::<Test>() {
None => (),
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match a_r.downcast_mut::<usize>() {
Some(&mut 612) => {}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
match b_r.downcast_mut::<usize>() {
Some(&mut 413) => {}
x => panic!("Unexpected value {:?}", x),
x => panic!("Unexpected value {x:?}"),
}
}

View File

@ -62,10 +62,10 @@ fn cell_update() {
#[test]
fn cell_has_sensible_show() {
let x = Cell::new("foo bar");
assert!(format!("{:?}", x).contains(x.get()));
assert!(format!("{x:?}").contains(x.get()));
x.set("baz qux");
assert!(format!("{:?}", x).contains(x.get()));
assert!(format!("{x:?}").contains(x.get()));
}
#[test]
@ -73,11 +73,11 @@ fn ref_and_refmut_have_sensible_show() {
let refcell = RefCell::new("foo");
let refcell_refmut = refcell.borrow_mut();
assert!(format!("{:?}", refcell_refmut).contains("foo"));
assert!(format!("{refcell_refmut:?}").contains("foo"));
drop(refcell_refmut);
let refcell_ref = refcell.borrow();
assert!(format!("{:?}", refcell_ref).contains("foo"));
assert!(format!("{refcell_ref:?}").contains("foo"));
drop(refcell_ref);
}

View File

@ -11,8 +11,8 @@ mod debug_struct {
}
}
assert_eq!("Foo", format!("{:?}", Foo));
assert_eq!("Foo", format!("{:#?}", Foo));
assert_eq!("Foo", format!("{Foo:?}"));
assert_eq!("Foo", format!("{Foo:#?}"));
}
#[test]
@ -25,12 +25,12 @@ mod debug_struct {
}
}
assert_eq!("Foo { bar: true }", format!("{:?}", Foo));
assert_eq!("Foo { bar: true }", format!("{Foo:?}"));
assert_eq!(
"Foo {
bar: true,
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -47,13 +47,13 @@ mod debug_struct {
}
}
assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{:?}", Foo));
assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{Foo:?}"));
assert_eq!(
"Foo {
bar: true,
baz: 10/20,
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -80,7 +80,7 @@ mod debug_struct {
assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"Bar {
@ -90,7 +90,7 @@ mod debug_struct {
},
hello: \"world\",
}",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
@ -104,8 +104,8 @@ mod debug_struct {
}
}
assert_eq!("Foo { .. }", format!("{:?}", Foo));
assert_eq!("Foo { .. }", format!("{:#?}", Foo));
assert_eq!("Foo { .. }", format!("{Foo:?}"));
assert_eq!("Foo { .. }", format!("{Foo:#?}"));
}
#[test]
@ -121,14 +121,14 @@ mod debug_struct {
}
}
assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{:?}", Foo));
assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{Foo:?}"));
assert_eq!(
"Foo {
bar: true,
baz: 10/20,
..
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -158,7 +158,7 @@ mod debug_struct {
assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20, .. }, hello: \"world\", .. }",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"Bar {
@ -170,7 +170,7 @@ mod debug_struct {
hello: \"world\",
..
}",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
}
@ -188,8 +188,8 @@ mod debug_tuple {
}
}
assert_eq!("Foo", format!("{:?}", Foo));
assert_eq!("Foo", format!("{:#?}", Foo));
assert_eq!("Foo", format!("{Foo:?}"));
assert_eq!("Foo", format!("{Foo:#?}"));
}
#[test]
@ -202,12 +202,12 @@ mod debug_tuple {
}
}
assert_eq!("Foo(true)", format!("{:?}", Foo));
assert_eq!("Foo(true)", format!("{Foo:?}"));
assert_eq!(
"Foo(
true,
)",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -221,13 +221,13 @@ mod debug_tuple {
}
}
assert_eq!("Foo(true, 10/20)", format!("{:?}", Foo));
assert_eq!("Foo(true, 10/20)", format!("{Foo:?}"));
assert_eq!(
"Foo(
true,
10/20,
)",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -249,7 +249,7 @@ mod debug_tuple {
}
}
assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{:?}", Bar));
assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{Bar:?}"));
assert_eq!(
"Bar(
Foo(
@ -258,7 +258,7 @@ mod debug_tuple {
),
\"world\",
)",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
}
@ -276,8 +276,8 @@ mod debug_map {
}
}
assert_eq!("{}", format!("{:?}", Foo));
assert_eq!("{}", format!("{:#?}", Foo));
assert_eq!("{}", format!("{Foo:?}"));
assert_eq!("{}", format!("{Foo:#?}"));
}
#[test]
@ -298,15 +298,15 @@ mod debug_map {
}
}
assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue));
assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue));
assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}"));
assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}"));
assert_eq!("{\"bar\": true}", format!("{:?}", Entry));
assert_eq!("{\"bar\": true}", format!("{Entry:?}"));
assert_eq!(
"{
\"bar\": true,
}",
format!("{:#?}", Entry)
format!("{Entry:#?}")
);
}
@ -336,16 +336,16 @@ mod debug_map {
}
}
assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue));
assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue));
assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}"));
assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}"));
assert_eq!("{\"bar\": true, 10: 10/20}", format!("{:?}", Entry));
assert_eq!("{\"bar\": true, 10: 10/20}", format!("{Entry:?}"));
assert_eq!(
"{
\"bar\": true,
10: 10/20,
}",
format!("{:#?}", Entry)
format!("{Entry:#?}")
);
}
@ -373,7 +373,7 @@ mod debug_map {
assert_eq!(
"{\"foo\": {\"bar\": true, 10: 10/20}, \
{\"bar\": true, 10: 10/20}: \"world\"}",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"{
@ -386,7 +386,7 @@ mod debug_map {
10: 10/20,
}: \"world\",
}",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
@ -441,7 +441,7 @@ mod debug_map {
}
}
format!("{:?}", Foo);
format!("{Foo:?}");
}
#[test]
@ -455,7 +455,7 @@ mod debug_map {
}
}
format!("{:?}", Foo);
format!("{Foo:?}");
}
#[test]
@ -469,7 +469,7 @@ mod debug_map {
}
}
format!("{:?}", Foo);
format!("{Foo:?}");
}
}
@ -486,8 +486,8 @@ mod debug_set {
}
}
assert_eq!("{}", format!("{:?}", Foo));
assert_eq!("{}", format!("{:#?}", Foo));
assert_eq!("{}", format!("{Foo:?}"));
assert_eq!("{}", format!("{Foo:#?}"));
}
#[test]
@ -500,12 +500,12 @@ mod debug_set {
}
}
assert_eq!("{true}", format!("{:?}", Foo));
assert_eq!("{true}", format!("{Foo:?}"));
assert_eq!(
"{
true,
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -519,13 +519,13 @@ mod debug_set {
}
}
assert_eq!("{true, 10/20}", format!("{:?}", Foo));
assert_eq!("{true, 10/20}", format!("{Foo:?}"));
assert_eq!(
"{
true,
10/20,
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -547,7 +547,7 @@ mod debug_set {
}
}
assert_eq!("{{true, 10/20}, \"world\"}", format!("{:?}", Bar));
assert_eq!("{{true, 10/20}, \"world\"}", format!("{Bar:?}"));
assert_eq!(
"{
{
@ -556,7 +556,7 @@ mod debug_set {
},
\"world\",
}",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
}
@ -574,8 +574,8 @@ mod debug_list {
}
}
assert_eq!("[]", format!("{:?}", Foo));
assert_eq!("[]", format!("{:#?}", Foo));
assert_eq!("[]", format!("{Foo:?}"));
assert_eq!("[]", format!("{Foo:#?}"));
}
#[test]
@ -588,12 +588,12 @@ mod debug_list {
}
}
assert_eq!("[true]", format!("{:?}", Foo));
assert_eq!("[true]", format!("{Foo:?}"));
assert_eq!(
"[
true,
]",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -607,13 +607,13 @@ mod debug_list {
}
}
assert_eq!("[true, 10/20]", format!("{:?}", Foo));
assert_eq!("[true, 10/20]", format!("{Foo:?}"));
assert_eq!(
"[
true,
10/20,
]",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -635,7 +635,7 @@ mod debug_list {
}
}
assert_eq!("[[true, 10/20], \"world\"]", format!("{:?}", Bar));
assert_eq!("[[true, 10/20], \"world\"]", format!("{Bar:?}"));
assert_eq!(
"[
[
@ -644,7 +644,7 @@ mod debug_list {
],
\"world\",
]",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
}
@ -668,13 +668,13 @@ fn test_formatting_parameters_are_forwarded() {
set.insert(1024);
set.insert(7);
assert_eq!(format!("{:03?}", struct_), "Foo { bar: 1024, baz: 007 }");
assert_eq!(format!("{:03?}", tuple), "(1024, 007)");
assert_eq!(format!("{:03?}", list), "[1024, 007]");
assert_eq!(format!("{:03?}", map), r#"{"bar": 1024, "baz": 007}"#);
assert_eq!(format!("{:03?}", set), "{007, 1024}");
assert_eq!(format!("{struct_:03?}"), "Foo { bar: 1024, baz: 007 }");
assert_eq!(format!("{tuple:03?}"), "(1024, 007)");
assert_eq!(format!("{list:03?}"), "[1024, 007]");
assert_eq!(format!("{map:03?}"), r#"{"bar": 1024, "baz": 007}"#);
assert_eq!(format!("{set:03?}"), "{007, 1024}");
assert_eq!(
format!("{:#03?}", struct_),
format!("{struct_:#03?}"),
"
Foo {
bar: 1024,
@ -684,7 +684,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", tuple),
format!("{tuple:#03?}"),
"
(
1024,
@ -694,7 +694,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", list),
format!("{list:#03?}"),
"
[
1024,
@ -704,7 +704,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", map),
format!("{map:#03?}"),
r#"
{
"bar": 1024,
@ -714,7 +714,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", set),
format!("{set:#03?}"),
"
{
007,

View File

@ -6,7 +6,7 @@ mod num;
fn test_format_flags() {
// No residual flags left by pointer formatting
let p = "".as_ptr();
assert_eq!(format!("{:p} {:x}", p, 16), format!("{:p} 10", p));
assert_eq!(format!("{:p} {:x}", p, 16), format!("{p:p} 10"));
assert_eq!(format!("{: >3}", 'a'), " a");
}
@ -15,8 +15,8 @@ fn test_format_flags() {
fn test_pointer_formats_data_pointer() {
let b: &[u8] = b"";
let s: &str = "";
assert_eq!(format!("{:p}", s), format!("{:p}", s.as_ptr()));
assert_eq!(format!("{:p}", b), format!("{:p}", b.as_ptr()));
assert_eq!(format!("{s:p}"), format!("{:p}", s.as_ptr()));
assert_eq!(format!("{b:p}"), format!("{:p}", b.as_ptr()));
}
#[test]
@ -41,5 +41,5 @@ fn pad_integral_resets() {
}
}
assert_eq!(format!("{:<03}", Bar), "1 0051 ");
assert_eq!(format!("{Bar:<03}"), "1 0051 ");
}

View File

@ -126,7 +126,7 @@ fn test_format_int_exp_limits() {
fn test_format_int_exp_precision() {
//test that float and integer match
let big_int: u32 = 314_159_265;
assert_eq!(format!("{:.1e}", big_int), format!("{:.1e}", f64::from(big_int)));
assert_eq!(format!("{big_int:.1e}"), format!("{:.1e}", f64::from(big_int)));
//test adding precision
assert_eq!(format!("{:.10e}", i8::MIN), "-1.2800000000e2");

View File

@ -113,7 +113,7 @@ fn aliasing_in_get() {
x.set(42).unwrap();
let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
println!("{}", at_x); // <------- up until here ---------------------------+
println!("{at_x}"); // <------- up until here ---------------------------+
}
#[test]

View File

@ -15,7 +15,7 @@ macro_rules! test_literal {
for input in inputs {
assert_eq!(input.parse(), Ok(x64));
assert_eq!(input.parse(), Ok(x32));
let neg_input = &format!("-{}", input);
let neg_input = &format!("-{input}");
assert_eq!(neg_input.parse(), Ok(-x64));
assert_eq!(neg_input.parse(), Ok(-x32));
}
@ -123,9 +123,9 @@ fn inf() {
#[test]
fn massive_exponent() {
let max = i64::MAX;
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e-{}000", max).parse(), Ok(0.0));
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e-{max}000").parse(), Ok(0.0));
assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
}
#[test]

View File

@ -46,7 +46,7 @@ fn valid() {
assert_eq!(parse_positive(b".1e300"), Some(new_number(299, 1)));
assert_eq!(parse_positive(b"101e-33"), Some(new_number(-33, 101)));
let zeros = "0".repeat(25);
let s = format!("1.5e{}", zeros);
let s = format!("1.5e{zeros}");
assert_eq!(parse_positive(s.as_bytes()), Some(new_number(-1, 15)));
}

View File

@ -20,7 +20,7 @@ mod random;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded),
full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
}
}

View File

@ -15,7 +15,7 @@ use rand::SeedableRng;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded),
full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
}
}

View File

@ -550,7 +550,7 @@ fn dyn_metadata() {
assert_eq!(meta.align_of(), std::mem::align_of::<Something>());
assert_eq!(meta.layout(), std::alloc::Layout::new::<Something>());
assert!(format!("{:?}", meta).starts_with("DynMetadata(0x"));
assert!(format!("{meta:?}").starts_with("DynMetadata(0x"));
}
#[test]

View File

@ -80,9 +80,9 @@ fn test_fmt_default() {
let ok: Result<isize, &'static str> = Ok(100);
let err: Result<isize, &'static str> = Err("Err");
let s = format!("{:?}", ok);
let s = format!("{ok:?}");
assert_eq!(s, "Ok(100)");
let s = format!("{:?}", err);
let s = format!("{err:?}");
assert_eq!(s, "Err(\"Err\")");
}

View File

@ -187,7 +187,7 @@ mod tests {
fn main() {
{
let (energy_before, energy_after) = nbody::run(1000);
println!("Energy before: {}", energy_before);
println!("Energy after: {}", energy_after);
println!("Energy before: {energy_before}");
println!("Energy after: {energy_after}");
}
}

View File

@ -1106,7 +1106,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f32_unsuffixed(n: f32) -> Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
panic!("Invalid float literal {n}");
}
let mut repr = n.to_string();
if !repr.contains('.') {
@ -1131,7 +1131,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f32_suffixed(n: f32) -> Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
panic!("Invalid float literal {n}");
}
Literal(bridge::client::Literal::f32(&n.to_string()))
}
@ -1151,7 +1151,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f64_unsuffixed(n: f64) -> Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
panic!("Invalid float literal {n}");
}
let mut repr = n.to_string();
if !repr.contains('.') {
@ -1176,7 +1176,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f64_suffixed(n: f64) -> Literal {
if !n.is_finite() {
panic!("Invalid float literal {}", n);
panic!("Invalid float literal {n}");
}
Literal(bridge::client::Literal::f64(&n.to_string()))
}

View File

@ -83,7 +83,7 @@ pub use alloc_crate::alloc::*;
///
/// fn main() {
/// let a = Box::new(4); // Allocates from the system allocator.
/// println!("{}", a);
/// println!("{a}");
/// }
/// ```
///

View File

@ -57,10 +57,10 @@ fn test_debug() {
\n { fn: \"std::rt::lang_start\", file: \"rust/rt.rs\", line: 400 },\
\n]";
assert_eq!(format!("{:#?}", backtrace), expected);
assert_eq!(format!("{backtrace:#?}"), expected);
// Format the backtrace a second time, just to make sure lazily resolved state is stable
assert_eq!(format!("{:#?}", backtrace), expected);
assert_eq!(format!("{backtrace:#?}"), expected);
}
#[test]
@ -91,5 +91,5 @@ fn test_frames() {
let mut iter = frames.iter().zip(expected.iter());
assert!(iter.all(|(f, e)| format!("{:#?}", f) == *e));
assert!(iter.all(|(f, e)| format!("{f:#?}") == *e));
}

View File

@ -109,8 +109,8 @@ use crate::sys;
/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
/// for &book in &to_find {
/// match book_reviews.get(book) {
/// Some(review) => println!("{}: {}", book, review),
/// None => println!("{} is unreviewed.", book)
/// Some(review) => println!("{book}: {review}"),
/// None => println!("{book} is unreviewed.")
/// }
/// }
///
@ -119,7 +119,7 @@ use crate::sys;
///
/// // Iterate over everything.
/// for (book, review) in &book_reviews {
/// println!("{}: \"{}\"", book, review);
/// println!("{book}: \"{review}\"");
/// }
/// ```
///
@ -199,7 +199,7 @@ use crate::sys;
///
/// // Use derived implementation to print the status of the vikings.
/// for (viking, health) in &vikings {
/// println!("{:?} has {} hp", viking, health);
/// println!("{viking:?} has {health} hp");
/// }
/// ```
@ -341,7 +341,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]);
///
/// for key in map.keys() {
/// println!("{}", key);
/// println!("{key}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -392,7 +392,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]);
///
/// for val in map.values() {
/// println!("{}", val);
/// println!("{val}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -419,7 +419,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// }
///
/// for val in map.values() {
/// println!("{}", val);
/// println!("{val}");
/// }
/// ```
#[stable(feature = "map_values_mut", since = "1.10.0")]
@ -470,7 +470,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]);
///
/// for (key, val) in map.iter() {
/// println!("key: {} val: {}", key, val);
/// println!("key: {key} val: {val}");
/// }
/// ```
#[rustc_lint_query_instability]
@ -500,7 +500,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// }
///
/// for (key, val) in &map {
/// println!("key: {} val: {}", key, val);
/// println!("key: {key} val: {val}");
/// }
/// ```
#[rustc_lint_query_instability]

View File

@ -515,10 +515,10 @@ fn test_show() {
map.insert(1, 2);
map.insert(3, 4);
let map_str = format!("{:?}", map);
let map_str = format!("{map:?}");
assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
assert_eq!(format!("{:?}", empty), "{}");
assert_eq!(format!("{empty:?}"), "{}");
}
#[test]
@ -702,7 +702,7 @@ fn test_entry_take_doesnt_corrupt() {
// Test for #19292
fn check(m: &HashMap<i32, ()>) {
for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k);
assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
}
}

View File

@ -66,7 +66,7 @@ use super::map::{map_try_reserve_error, RandomState};
///
/// // Iterate over everything.
/// for book in &books {
/// println!("{}", book);
/// println!("{book}");
/// }
/// ```
///
@ -91,7 +91,7 @@ use super::map::{map_try_reserve_error, RandomState};
///
/// // Use derived implementation to print the vikings.
/// for x in &vikings {
/// println!("{:?}", x);
/// println!("{x:?}");
/// }
/// ```
///
@ -181,7 +181,7 @@ impl<T, S> HashSet<T, S> {
///
/// // Will print in an arbitrary order.
/// for x in set.iter() {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]
@ -244,7 +244,7 @@ impl<T, S> HashSet<T, S> {
///
/// // print 1, 2, 3 in an arbitrary order
/// for i in set.drain() {
/// println!("{}", i);
/// println!("{i}");
/// }
///
/// assert!(set.is_empty());
@ -525,7 +525,7 @@ where
///
/// // Can be seen as `a - b`.
/// for x in a.difference(&b) {
/// println!("{}", x); // Print 1
/// println!("{x}"); // Print 1
/// }
///
/// let diff: HashSet<_> = a.difference(&b).collect();
@ -555,7 +555,7 @@ where
///
/// // Print 1, 4 in arbitrary order.
/// for x in a.symmetric_difference(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
@ -586,7 +586,7 @@ where
///
/// // Print 2, 3 in arbitrary order.
/// for x in a.intersection(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// let intersection: HashSet<_> = a.intersection(&b).collect();
@ -615,7 +615,7 @@ where
///
/// // Print 1, 2, 3, 4 in arbitrary order.
/// for x in a.union(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// let union: HashSet<_> = a.union(&b).collect();
@ -1451,7 +1451,7 @@ impl<T, S> IntoIterator for HashSet<T, S> {
///
/// // Will print in an arbitrary order.
/// for x in &v {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]

View File

@ -301,10 +301,10 @@ fn test_show() {
set.insert(1);
set.insert(2);
let set_str = format!("{:?}", set);
let set_str = format!("{set:?}");
assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
assert_eq!(format!("{:?}", empty), "{}");
assert_eq!(format!("{empty:?}"), "{}");
}
#[test]

View File

@ -199,7 +199,7 @@
//! ```
//! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter() {
//! println!("vec contained {}", x);
//! println!("vec contained {x:?}");
//! }
//! ```
//!
@ -246,7 +246,7 @@
//! ```
//! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter().rev() {
//! println!("vec contained {}", x);
//! println!("vec contained {x:?}");
//! }
//! ```
//!
@ -306,7 +306,7 @@
//!
//! println!("Number of occurrences of each character");
//! for (char, count) in &count {
//! println!("{}: {}", char, count);
//! println!("{char}: {count}");
//! }
//! ```
//!
@ -339,7 +339,7 @@
//! // Check if they're sober enough to have another beer.
//! if person.blood_alcohol > 0.3 {
//! // Too drunk... for now.
//! println!("Sorry {}, I have to cut you off", id);
//! println!("Sorry {id}, I have to cut you off");
//! } else {
//! // Have another!
//! person.blood_alcohol += 0.1;

View File

@ -118,7 +118,7 @@ pub struct VarsOs {
/// // We will iterate through the references to the element returned by
/// // env::vars();
/// for (key, value) in env::vars() {
/// println!("{}: {}", key, value);
/// println!("{key}: {value}");
/// }
/// ```
///
@ -148,7 +148,7 @@ pub fn vars() -> Vars {
/// // We will iterate through the references to the element returned by
/// // env::vars_os();
/// for (key, value) in env::vars_os() {
/// println!("{:?}: {:?}", key, value);
/// println!("{key:?}: {value:?}");
/// }
/// ```
#[must_use]
@ -212,8 +212,8 @@ impl fmt::Debug for VarsOs {
///
/// let key = "HOME";
/// match env::var(key) {
/// Ok(val) => println!("{}: {:?}", key, val),
/// Err(e) => println!("couldn't interpret {}: {}", key, e),
/// Ok(val) => println!("{key}: {val:?}"),
/// Err(e) => println!("couldn't interpret {key}: {e}"),
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -252,8 +252,8 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
///
/// let key = "HOME";
/// match env::var_os(key) {
/// Some(val) => println!("{}: {:?}", key, val),
/// None => println!("{} is not defined in the environment.", key)
/// Some(val) => println!("{key}: {val:?}"),
/// None => println!("{key} is not defined in the environment.")
/// }
/// ```
#[must_use]
@ -343,7 +343,7 @@ pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
fn _set_var(key: &OsStr, value: &OsStr) {
os_imp::setenv(key, value).unwrap_or_else(|e| {
panic!("failed to set environment variable `{:?}` to `{:?}`: {}", key, value, e)
panic!("failed to set environment variable `{key:?}` to `{value:?}`: {e}")
})
}
@ -385,7 +385,7 @@ pub fn remove_var<K: AsRef<OsStr>>(key: K) {
fn _remove_var(key: &OsStr) {
os_imp::unsetenv(key)
.unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", key, e))
.unwrap_or_else(|e| panic!("failed to remove environment variable `{key:?}`: {e}"))
}
/// An iterator that splits an environment variable into paths according to
@ -421,7 +421,7 @@ pub struct SplitPaths<'a> {
/// println!("'{}'", path.display());
/// }
/// }
/// None => println!("{} is not defined in the environment.", key)
/// None => println!("{key} is not defined in the environment.")
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -684,7 +684,7 @@ pub fn temp_dir() -> PathBuf {
/// match env::current_exe() {
/// Ok(exe_path) => println!("Path of this executable is: {}",
/// exe_path.display()),
/// Err(e) => println!("failed to get current exe path: {}", e),
/// Err(e) => println!("failed to get current exe path: {e}"),
/// };
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -755,7 +755,7 @@ pub struct ArgsOs {
///
/// // Prints each argument on a separate line
/// for argument in env::args() {
/// println!("{}", argument);
/// println!("{argument}");
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -790,7 +790,7 @@ pub fn args() -> Args {
///
/// // Prints each argument on a separate line
/// for argument in env::args_os() {
/// println!("{:?}", argument);
/// println!("{argument:?}");
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]

View File

@ -96,7 +96,7 @@ pub trait Error: Debug + Display {
/// fn main() {
/// match get_super_error() {
/// Err(e) => {
/// println!("Error: {}", e);
/// println!("Error: {e}");
/// println!("Caused by: {}", e.source().unwrap());
/// }
/// _ => println!("No error"),
@ -139,7 +139,7 @@ pub trait Error: Debug + Display {
/// ```
/// if let Err(e) = "xc".parse::<u32>() {
/// // Print `e` itself, no need for description().
/// eprintln!("Error: {}", e);
/// eprintln!("Error: {e}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -1074,7 +1074,7 @@ impl<E> Report<E> {
///
/// let error = SuperError { source: SuperErrorSideKick };
/// let report = Report::new(error).pretty(true);
/// eprintln!("Error: {:?}", report);
/// eprintln!("Error: {report:?}");
/// ```
///
/// This example produces the following output:
@ -1135,7 +1135,7 @@ impl<E> Report<E> {
/// let source = SuperErrorSideKick { source };
/// let error = SuperError { source };
/// let report = Report::new(error).pretty(true);
/// eprintln!("Error: {:?}", report);
/// eprintln!("Error: {report:?}");
/// ```
///
/// This example produces the following output:
@ -1210,7 +1210,7 @@ impl<E> Report<E> {
/// let source = SuperErrorSideKick::new();
/// let error = SuperError { source };
/// let report = Report::new(error).pretty(true).show_backtrace(true);
/// eprintln!("Error: {:?}", report);
/// eprintln!("Error: {report:?}");
/// ```
///
/// This example produces something similar to the following output:
@ -1267,7 +1267,7 @@ where
let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
for cause in sources {
write!(f, ": {}", cause)?;
write!(f, ": {cause}")?;
}
Ok(())
@ -1278,7 +1278,7 @@ where
fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error = &self.error;
write!(f, "{}", error)?;
write!(f, "{error}")?;
if let Some(cause) = error.source() {
write!(f, "\n\nCaused by:")?;
@ -1289,9 +1289,9 @@ where
writeln!(f)?;
let mut indented = Indented { inner: f };
if multiple {
write!(indented, "{: >4}: {}", ind, error)?;
write!(indented, "{ind: >4}: {error}")?;
} else {
write!(indented, " {}", error)?;
write!(indented, " {error}")?;
}
}
}
@ -1333,7 +1333,7 @@ impl Report<Box<dyn Error>> {
let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
for cause in sources {
write!(f, ": {}", cause)?;
write!(f, ": {cause}")?;
}
Ok(())
@ -1344,7 +1344,7 @@ impl Report<Box<dyn Error>> {
fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error = &self.error;
write!(f, "{}", error)?;
write!(f, "{error}")?;
if let Some(cause) = error.source() {
write!(f, "\n\nCaused by:")?;
@ -1355,9 +1355,9 @@ impl Report<Box<dyn Error>> {
writeln!(f)?;
let mut indented = Indented { inner: f };
if multiple {
write!(indented, "{: >4}: {}", ind, error)?;
write!(indented, "{ind: >4}: {error}")?;
} else {
write!(indented, " {}", error)?;
write!(indented, " {error}")?;
}
}
}

View File

@ -130,7 +130,7 @@ Stack backtrace:
error.backtrace = Some(trace);
let report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report);
println!("Error: {report}");
assert_eq!(expected.trim_end(), report.to_string());
}
@ -155,7 +155,7 @@ Stack backtrace:
let error = GenericError::new_with_source("Error with two sources", error);
let report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report);
println!("Error: {report}");
assert_eq!(expected.trim_end(), report.to_string());
}
@ -355,7 +355,7 @@ Caused by:
1: The message goes on and on.";
let actual = report.to_string();
println!("{}", actual);
println!("{actual}");
assert_eq!(expected, actual);
}

Some files were not shown because too many files have changed in this diff Show More