diff --git a/compiler/rustc/build.rs b/compiler/rustc/build.rs index 39cf3e094c823..8b7d28d2b8aa6 100644 --- a/compiler/rustc/build.rs +++ b/compiler/rustc/build.rs @@ -18,7 +18,7 @@ fn set_windows_exe_options() { let mut manifest = env::current_dir().unwrap(); manifest.push(WINDOWS_MANIFEST_FILE); - println!("cargo:rerun-if-changed={}", WINDOWS_MANIFEST_FILE); + println!("cargo:rerun-if-changed={WINDOWS_MANIFEST_FILE}"); // Embed the Windows application manifest file. println!("cargo:rustc-link-arg-bin=rustc-main=/MANIFEST:EMBED"); println!("cargo:rustc-link-arg-bin=rustc-main=/MANIFESTINPUT:{}", manifest.to_str().unwrap()); diff --git a/compiler/rustc_apfloat/src/ieee.rs b/compiler/rustc_apfloat/src/ieee.rs index 3db8adb2a2444..17ff70742d80c 100644 --- a/compiler/rustc_apfloat/src/ieee.rs +++ b/compiler/rustc_apfloat/src/ieee.rs @@ -571,9 +571,9 @@ impl fmt::Display for IeeeFloat { // Exponent always at least two digits if we do not truncate zeros. if truncate_zero { - write!(f, "{:+}", exp)?; + write!(f, "{exp:+}")?; } else { - write!(f, "{:+03}", exp)?; + write!(f, "{exp:+03}")?; } return Ok(()); diff --git a/compiler/rustc_apfloat/tests/ieee.rs b/compiler/rustc_apfloat/tests/ieee.rs index f8fac0c2358c9..87bbcf71cd670 100644 --- a/compiler/rustc_apfloat/tests/ieee.rs +++ b/compiler/rustc_apfloat/tests/ieee.rs @@ -963,9 +963,9 @@ fn to_string() { let to_string = |d: f64, precision: usize, width: usize| { let x = Double::from_f64(d); if precision == 0 { - format!("{:1$}", x, width) + format!("{x:width$}") } else { - format!("{:2$.1$}", x, precision, width) + format!("{x:width$.precision$}") } }; assert_eq!("10", to_string(10.0, 6, 3)); @@ -985,9 +985,9 @@ fn to_string() { let to_string = |d: f64, precision: usize, width: usize| { let x = Double::from_f64(d); if precision == 0 { - format!("{:#1$}", x, width) + format!("{x:#width$}") } else { - format!("{:#2$.1$}", x, precision, width) + format!("{x:#width$.precision$}") } }; assert_eq!("10", to_string(10.0, 6, 3)); diff --git a/compiler/rustc_apfloat/tests/ppc.rs b/compiler/rustc_apfloat/tests/ppc.rs index c769d26543786..a53d187ec53bd 100644 --- a/compiler/rustc_apfloat/tests/ppc.rs +++ b/compiler/rustc_apfloat/tests/ppc.rs @@ -70,14 +70,14 @@ fn ppc_double_double_add_special() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.add_r(a2, round).value; - assert_eq!(expected, a1.category(), "{:#x} + {:#x}", op1, op2); + assert_eq!(expected, a1.category(), "{op1:#x} + {op2:#x}"); } { let a1 = DoubleDouble::from_bits(op1); let mut a2 = DoubleDouble::from_bits(op2); a2 = a2.add_r(a1, round).value; - assert_eq!(expected, a2.category(), "{:#x} + {:#x}", op2, op1); + assert_eq!(expected, a2.category(), "{op2:#x} + {op1:#x}"); } } } @@ -141,14 +141,14 @@ fn ppc_double_double_add() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.add_r(a2, round).value; - assert_eq!(expected, a1.to_bits(), "{:#x} + {:#x}", op1, op2); + assert_eq!(expected, a1.to_bits(), "{op1:#x} + {op2:#x}"); } { let a1 = DoubleDouble::from_bits(op1); let mut a2 = DoubleDouble::from_bits(op2); a2 = a2.add_r(a1, round).value; - assert_eq!(expected, a2.to_bits(), "{:#x} + {:#x}", op2, op1); + assert_eq!(expected, a2.to_bits(), "{op2:#x} + {op1:#x}"); } } } @@ -177,7 +177,7 @@ fn ppc_double_double_subtract() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.sub_r(a2, round).value; - assert_eq!(expected, a1.to_bits(), "{:#x} - {:#x}", op1, op2); + assert_eq!(expected, a1.to_bits(), "{op1:#x} - {op2:#x}"); } } @@ -210,14 +210,14 @@ fn ppc_double_double_multiply_special() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.mul_r(a2, round).value; - assert_eq!(expected, a1.category(), "{:#x} * {:#x}", op1, op2); + assert_eq!(expected, a1.category(), "{op1:#x} * {op2:#x}"); } { let a1 = DoubleDouble::from_bits(op1); let mut a2 = DoubleDouble::from_bits(op2); a2 = a2.mul_r(a1, round).value; - assert_eq!(expected, a2.category(), "{:#x} * {:#x}", op2, op1); + assert_eq!(expected, a2.category(), "{op2:#x} * {op1:#x}"); } } } @@ -296,14 +296,14 @@ fn ppc_double_double_multiply() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.mul_r(a2, round).value; - assert_eq!(expected, a1.to_bits(), "{:#x} * {:#x}", op1, op2); + assert_eq!(expected, a1.to_bits(), "{op1:#x} * {op2:#x}"); } { let a1 = DoubleDouble::from_bits(op1); let mut a2 = DoubleDouble::from_bits(op2); a2 = a2.mul_r(a1, round).value; - assert_eq!(expected, a2.to_bits(), "{:#x} * {:#x}", op2, op1); + assert_eq!(expected, a2.to_bits(), "{op2:#x} * {op1:#x}"); } } } @@ -327,7 +327,7 @@ fn ppc_double_double_divide() { let a2 = DoubleDouble::from_bits(op2); a1 = a1.div_r(a2, round).value; - assert_eq!(expected, a1.to_bits(), "{:#x} / {:#x}", op1, op2); + assert_eq!(expected, a1.to_bits(), "{op1:#x} / {op2:#x}"); } } @@ -353,7 +353,7 @@ fn ppc_double_double_remainder() { let a2 = DoubleDouble::from_bits(op2); let result = a1.ieee_rem(a2).value; - assert_eq!(expected, result.to_bits(), "ieee_rem({:#x}, {:#x})", op1, op2); + assert_eq!(expected, result.to_bits(), "ieee_rem({op1:#x}, {op2:#x})"); } } @@ -381,7 +381,7 @@ fn ppc_double_double_mod() { let a2 = DoubleDouble::from_bits(op2); let r = (a1 % a2).value; - assert_eq!(expected, r.to_bits(), "fmod({:#x}, {:#x})", op1, op2); + assert_eq!(expected, r.to_bits(), "fmod({op1:#x}, {op2:#x})"); } } @@ -429,7 +429,7 @@ fn ppc_double_double_compare() { for (op1, op2, expected) in data { let a1 = DoubleDouble::from_bits(op1); let a2 = DoubleDouble::from_bits(op2); - assert_eq!(expected, a1.partial_cmp(&a2), "compare({:#x}, {:#x})", op1, op2,); + assert_eq!(expected, a1.partial_cmp(&a2), "compare({op1:#x}, {op2:#x})",); } } @@ -451,7 +451,7 @@ fn ppc_double_double_bitwise_eq() { for (op1, op2, expected) in data { let a1 = DoubleDouble::from_bits(op1); let a2 = DoubleDouble::from_bits(op2); - assert_eq!(expected, a1.bitwise_eq(a2), "{:#x} = {:#x}", op1, op2); + assert_eq!(expected, a1.bitwise_eq(a2), "{op1:#x} = {op2:#x}"); } } diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 0efde1e7b2124..bf41e2ea0a405 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -69,7 +69,7 @@ pub struct Lifetime { impl fmt::Debug for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "lifetime({}: {})", self.id, self) + write!(f, "lifetime({}: {self})", self.id) } } @@ -2120,10 +2120,10 @@ impl fmt::Display for InlineAsmTemplatePiece { Ok(()) } Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => { - write!(f, "{{{}:{}}}", operand_idx, modifier) + write!(f, "{{{operand_idx}:{modifier}}}") } Self::Placeholder { operand_idx, modifier: None, .. } => { - write!(f, "{{{}}}", operand_idx) + write!(f, "{{{operand_idx}}}") } } } @@ -2135,7 +2135,7 @@ impl InlineAsmTemplatePiece { use fmt::Write; let mut out = String::new(); for p in s.iter() { - let _ = write!(out, "{}", p); + let _ = write!(out, "{p}"); } out } diff --git a/compiler/rustc_ast/src/ast_traits.rs b/compiler/rustc_ast/src/ast_traits.rs index 1b31be07f7ad1..4dc9c30a2c807 100644 --- a/compiler/rustc_ast/src/ast_traits.rs +++ b/compiler/rustc_ast/src/ast_traits.rs @@ -214,7 +214,7 @@ impl HasTokens for Attribute { match &self.kind { AttrKind::Normal(normal) => normal.tokens.as_ref(), kind @ AttrKind::DocComment(..) => { - panic!("Called tokens on doc comment attr {:?}", kind) + panic!("Called tokens on doc comment attr {kind:?}") } } } @@ -222,7 +222,7 @@ impl HasTokens for Attribute { Some(match &mut self.kind { AttrKind::Normal(normal) => &mut normal.tokens, kind @ AttrKind::DocComment(..) => { - panic!("Called tokens_mut on doc comment attr {:?}", kind) + panic!("Called tokens_mut on doc comment attr {kind:?}") } }) } diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 990f4f8f1329f..2e69609c56959 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -316,7 +316,7 @@ impl Attribute { AttrKind::Normal(ref normal) => normal .tokens .as_ref() - .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self)) + .unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}")) .to_attr_token_stream() .to_tokenstream(), AttrKind::DocComment(comment_kind, data) => TokenStream::new(vec![TokenTree::Token( diff --git a/compiler/rustc_ast/src/expand/allocator.rs b/compiler/rustc_ast/src/expand/allocator.rs index 1976e4ad3c9fc..3593949634898 100644 --- a/compiler/rustc_ast/src/expand/allocator.rs +++ b/compiler/rustc_ast/src/expand/allocator.rs @@ -9,8 +9,8 @@ pub enum AllocatorKind { impl AllocatorKind { pub fn fn_name(&self, base: Symbol) -> String { match *self { - AllocatorKind::Global => format!("__rg_{}", base), - AllocatorKind::Default => format!("__rdl_{}", base), + AllocatorKind::Global => format!("__rg_{base}"), + AllocatorKind::Default => format!("__rdl_{base}"), } } } diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index 16224d71e4569..78c98ecc5b751 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -84,27 +84,27 @@ impl fmt::Display for Lit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let Lit { kind, symbol, suffix } = *self; match kind { - Byte => write!(f, "b'{}'", symbol)?, - Char => write!(f, "'{}'", symbol)?, - Str => write!(f, "\"{}\"", symbol)?, + Byte => write!(f, "b'{symbol}'")?, + Char => write!(f, "'{symbol}'")?, + Str => write!(f, "\"{symbol}\"")?, StrRaw(n) => write!( f, "r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol )?, - ByteStr => write!(f, "b\"{}\"", symbol)?, + ByteStr => write!(f, "b\"{symbol}\"")?, ByteStrRaw(n) => write!( f, "br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol )?, - Integer | Float | Bool | Err => write!(f, "{}", symbol)?, + Integer | Float | Bool | Err => write!(f, "{symbol}")?, } if let Some(suffix) = suffix { - write!(f, "{}", suffix)?; + write!(f, "{suffix}")?; } Ok(()) @@ -706,7 +706,7 @@ impl Token { _ => return None, }, SingleQuote => match joint.kind { - Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), + Ident(name, false) => Lifetime(Symbol::intern(&format!("'{name}"))), _ => return None, }, diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 4d2049cbc41ee..6204df6eb926b 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -430,7 +430,7 @@ impl TokenStream { pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream { let Some(tokens) = node.tokens() else { - panic!("missing tokens for node at {:?}: {:?}", node.span(), node); + panic!("missing tokens for node at {:?}: {node:?}", node.span()); }; let attrs = node.attrs(); let attr_stream = if attrs.is_empty() { diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index b87c6f78d7285..e9f5369fff138 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -188,25 +188,25 @@ fn doc_comment_to_string( data: Symbol, ) -> String { match (comment_kind, attr_style) { - (CommentKind::Line, ast::AttrStyle::Outer) => format!("///{}", data), - (CommentKind::Line, ast::AttrStyle::Inner) => format!("//!{}", data), - (CommentKind::Block, ast::AttrStyle::Outer) => format!("/**{}*/", data), - (CommentKind::Block, ast::AttrStyle::Inner) => format!("/*!{}*/", data), + (CommentKind::Line, ast::AttrStyle::Outer) => format!("///{data}"), + (CommentKind::Line, ast::AttrStyle::Inner) => format!("//!{data}"), + (CommentKind::Block, ast::AttrStyle::Outer) => format!("/**{data}*/"), + (CommentKind::Block, ast::AttrStyle::Inner) => format!("/*!{data}*/"), } } pub fn literal_to_string(lit: token::Lit) -> String { let token::Lit { kind, symbol, suffix } = lit; let mut out = match kind { - token::Byte => format!("b'{}'", symbol), - token::Char => format!("'{}'", symbol), - token::Str => format!("\"{}\"", symbol), + token::Byte => format!("b'{symbol}'"), + token::Char => format!("'{symbol}'"), + token::Str => format!("\"{symbol}\""), token::StrRaw(n) => { - format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol) + format!("r{delim}\"{symbol}\"{delim}", delim = "#".repeat(n as usize)) } - token::ByteStr => format!("b\"{}\"", symbol), + token::ByteStr => format!("b\"{symbol}\""), token::ByteStrRaw(n) => { - format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol) + format!("br{delim}\"{symbol}\"{delim}", delim = "#".repeat(n as usize)) } token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(), }; @@ -381,7 +381,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere let st = match style { ast::StrStyle::Cooked => format!("\"{}\"", st.escape_debug()), ast::StrStyle::Raw(n) => { - format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st) + format!("r{delim}\"{st}\"{delim}", delim = "#".repeat(n as usize)) } }; self.word(st) diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 54bac29a6cee0..58385658b9c83 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -8,7 +8,7 @@ use rustc_ast::ModKind; use rustc_span::symbol::Ident; fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String { - format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s) + format!("{}{s}", State::to_string(|s| s.print_visibility(vis))) } impl<'a> State<'a> { @@ -417,9 +417,9 @@ impl<'a> State<'a> { ast::VisibilityKind::Restricted { ref path, id: _, shorthand } => { let path = Self::to_string(|s| s.print_path(path, false, 0)); if shorthand && (path == "crate" || path == "self" || path == "super") { - self.word_nbsp(format!("pub({})", path)) + self.word_nbsp(format!("pub({path})")) } else { - self.word_nbsp(format!("pub(in {})", path)) + self.word_nbsp(format!("pub(in {path})")) } } ast::VisibilityKind::Inherited => {} diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index 00913a483db0e..f78787407656d 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -277,12 +277,12 @@ impl Dominators { } pub fn immediate_dominator(&self, node: Node) -> Node { - assert!(self.is_reachable(node), "node {:?} is not reachable", node); + assert!(self.is_reachable(node), "node {node:?} is not reachable"); self.immediate_dominators[node].unwrap() } pub fn dominators(&self, node: Node) -> Iter<'_, Node> { - assert!(self.is_reachable(node), "node {:?} is not reachable", node); + assert!(self.is_reachable(node), "node {node:?} is not reachable"); Iter { dominators: self, node: Some(node) } } diff --git a/compiler/rustc_data_structures/src/graph/iterate/tests.rs b/compiler/rustc_data_structures/src/graph/iterate/tests.rs index c498c289337f1..2794365bd5fbe 100644 --- a/compiler/rustc_data_structures/src/graph/iterate/tests.rs +++ b/compiler/rustc_data_structures/src/graph/iterate/tests.rs @@ -34,5 +34,5 @@ fn dfs_debug() { let graph = TestGraph::new(0, &[(0, 1), (0, 2), (1, 3), (2, 3), (3, 0)]); let mut dfs = DepthFirstSearch::new(&graph).with_start_node(0); dfs.complete_search(); - assert_eq!(format!("{{0, 1, 2, 3}}"), format!("{:?}", dfs)); + assert_eq!(format!("{{0, 1, 2, 3}}"), format!("{dfs:?}")); } diff --git a/compiler/rustc_data_structures/src/graph/scc/mod.rs b/compiler/rustc_data_structures/src/graph/scc/mod.rs index 7099ca7eb88c2..1538fbe35b417 100644 --- a/compiler/rustc_data_structures/src/graph/scc/mod.rs +++ b/compiler/rustc_data_structures/src/graph/scc/mod.rs @@ -370,7 +370,7 @@ where previous_node = previous; } // Only InCycleWith nodes were added to the reverse linked list. - other => panic!("Invalid previous link while compressing cycle: {:?}", other), + other => panic!("Invalid previous link while compressing cycle: {other:?}"), } debug!("find_state: parent_state = {:?}", node_state); @@ -395,7 +395,7 @@ where // NotVisited can not be part of a cycle since it should // have instead gotten explored. NodeState::NotVisited | NodeState::InCycleWith { .. } => { - panic!("invalid parent state: {:?}", node_state) + panic!("invalid parent state: {node_state:?}") } } } diff --git a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs index 3a268e4b4f432..4b6aa116520df 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/graphviz.rs @@ -30,7 +30,7 @@ impl ObligationForest { let counter = COUNTER.fetch_add(1, Ordering::AcqRel); - let file_path = dir.as_ref().join(format!("{:010}_{}.gv", counter, description)); + let file_path = dir.as_ref().join(format!("{counter:010}_{description}.gv")); let mut gv_file = BufWriter::new(File::create(file_path).unwrap()); @@ -47,7 +47,7 @@ impl<'a, O: ForestObligation + 'a> dot::Labeller<'a> for &'a ObligationForest } fn node_id(&self, index: &Self::Node) -> dot::Id<'_> { - dot::Id::new(format!("obligation_{}", index)).unwrap() + dot::Id::new(format!("obligation_{index}")).unwrap() } fn node_label(&self, index: &Self::Node) -> dot::LabelText<'_> { diff --git a/compiler/rustc_data_structures/src/obligation_forest/tests.rs b/compiler/rustc_data_structures/src/obligation_forest/tests.rs index bc252f772a168..12e56dd08dbb8 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/tests.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/tests.rs @@ -160,7 +160,7 @@ fn push_pop() { |obligation| match *obligation { "D.1.i" => ProcessResult::Error("D is for dumb"), "D.2.i" => ProcessResult::Changed(vec![]), - _ => panic!("unexpected obligation {:?}", obligation), + _ => panic!("unexpected obligation {obligation:?}"), }, |_| {}, )); diff --git a/compiler/rustc_data_structures/src/owning_ref/tests.rs b/compiler/rustc_data_structures/src/owning_ref/tests.rs index 320c03d5139f4..6e079fbe5aaa7 100644 --- a/compiler/rustc_data_structures/src/owning_ref/tests.rs +++ b/compiler/rustc_data_structures/src/owning_ref/tests.rs @@ -87,7 +87,7 @@ mod owning_ref { fn fmt_debug() { let or: BoxRef = Box::new(example().1).into(); let or = or.map(|x| &x[..5]); - let s = format!("{:?}", or); + let s = format!("{or:?}"); assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }"); } @@ -507,7 +507,7 @@ mod owning_ref_mut { fn fmt_debug() { let or: BoxRefMut = Box::new(example().1).into(); let or = or.map_mut(|x| &mut x[..5]); - let s = format!("{:?}", or); + let s = format!("{or:?}"); assert_eq!(&s, "OwningRefMut { owner: \"hello world\", reference: \"hello\" }"); } diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index ba1960805d84b..f14ed66712be2 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -226,7 +226,7 @@ impl SelfProfilerRef { A: Borrow + Into, { let message = if self.print_verbose_generic_activities { - Some(format!("{}({})", event_label, event_arg.borrow())) + Some(format!("{event_label}({})", event_arg.borrow())) } else { None }; @@ -549,7 +549,7 @@ impl SelfProfiler { // length can behave as a source of entropy for heap addresses, when // ASLR is disabled and the heap is otherwise determinic. let pid: u32 = process::id(); - let filename = format!("{}-{:07}.rustc_profile", crate_name, pid); + let filename = format!("{crate_name}-{pid:07}.rustc_profile"); let path = output_directory.join(&filename); let profiler = Profiler::with_counter(&path, measureme::counters::Counter::by_name(counter_name)?)?; @@ -783,7 +783,7 @@ pub fn print_time_passes_entry( (None, None) => String::new(), }; - eprintln!("time: {:>7}{}\t{}", duration_to_secs_str(dur), mem_string, what); + eprintln!("time: {:>7}{mem_string}\t{what}", duration_to_secs_str(dur)); } // Hack up our own formatting for the duration to make it easier for scripts diff --git a/compiler/rustc_data_structures/src/small_c_str.rs b/compiler/rustc_data_structures/src/small_c_str.rs index 3a8ab8ff9911e..719e4e3d97443 100644 --- a/compiler/rustc_data_structures/src/small_c_str.rs +++ b/compiler/rustc_data_structures/src/small_c_str.rs @@ -30,7 +30,7 @@ impl SmallCStr { SmallVec::from_vec(data) }; if let Err(e) = ffi::CStr::from_bytes_with_nul(&data) { - panic!("The string \"{}\" cannot be converted into a CStr: {}", s, e); + panic!("The string \"{s}\" cannot be converted into a CStr: {e}"); } SmallCStr { data } } @@ -39,7 +39,7 @@ impl SmallCStr { pub fn new_with_nul(s: &str) -> SmallCStr { let b = s.as_bytes(); if let Err(e) = ffi::CStr::from_bytes_with_nul(b) { - panic!("The string \"{}\" cannot be converted into a CStr: {}", s, e); + panic!("The string \"{s}\" cannot be converted into a CStr: {e}"); } SmallCStr { data: SmallVec::from_slice(s.as_bytes()) } } @@ -74,7 +74,7 @@ impl<'a> FromIterator<&'a str> for SmallCStr { iter.into_iter().flat_map(|s| s.as_bytes()).copied().collect::>(); data.push(0); if let Err(e) = ffi::CStr::from_bytes_with_nul(&data) { - panic!("The iterator {:?} cannot be converted into a CStr: {}", data, e); + panic!("The iterator {data:?} cannot be converted into a CStr: {e}"); } Self { data } } diff --git a/compiler/rustc_data_structures/src/sorted_map/tests.rs b/compiler/rustc_data_structures/src/sorted_map/tests.rs index 1e977d709f1cd..d3e46b294e72a 100644 --- a/compiler/rustc_data_structures/src/sorted_map/tests.rs +++ b/compiler/rustc_data_structures/src/sorted_map/tests.rs @@ -85,7 +85,7 @@ fn test_range() { let mut expected = vec![1, 3, 6, 9]; expected.retain(|&x| x >= start && x < end); - assert_eq!(keys(map.range(start..end)), expected, "range = {}..{}", start, end); + assert_eq!(keys(map.range(start..end)), expected, "range = {start}..{end}"); } } } @@ -135,7 +135,7 @@ fn test_remove_range() { let mut map = map.clone(); map.remove_range(start..end); - assert_eq!(keys(map), expected, "range = {}..{}", start, end); + assert_eq!(keys(map), expected, "range = {start}..{end}"); } } } diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 18be60975e4eb..052b040580149 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -100,17 +100,17 @@ pub enum TranslationBundleError { impl fmt::Display for TranslationBundleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e), + TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {e}"), TranslationBundleError::ParseFtl(e) => { - write!(f, "could not parse ftl file: {}", e) + write!(f, "could not parse ftl file: {e}") } - TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e), + TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {e}"), TranslationBundleError::MissingLocale => write!(f, "missing locale directory"), TranslationBundleError::ReadLocalesDir(e) => { - write!(f, "could not read locales dir: {}", e) + write!(f, "could not read locales dir: {e}") } TranslationBundleError::ReadLocalesDirEntry(e) => { - write!(f, "could not read locales dir entry: {}", e) + write!(f, "could not read locales dir entry: {e}") } TranslationBundleError::LocaleIsNotDir => { write!(f, "`$sysroot/share/locales/$locale` is not a directory") diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 31e410aaaf082..4f813e3c83e10 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -112,7 +112,7 @@ impl IntoDiagnosticArg for bool { impl IntoDiagnosticArg for char { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { - DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self))) + DiagnosticArgValue::Str(Cow::Owned(format!("{self:?}"))) } } @@ -494,13 +494,13 @@ impl Diagnostic { let expected_label = if expected_label.is_empty() { "expected".to_string() } else { - format!("expected {}", expected_label) + format!("expected {expected_label}") }; let found_label = found_label.to_string(); let found_label = if found_label.is_empty() { "found".to_string() } else { - format!("found {}", found_label) + format!("found {found_label}") }; let (found_padding, expected_padding) = if expected_label.len() > found_label.len() { (expected_label.len() - found_label.len(), 0) @@ -508,18 +508,18 @@ impl Diagnostic { (0, found_label.len() - expected_label.len()) }; let mut msg: Vec<_> = - vec![(format!("{}{} `", " ".repeat(expected_padding), expected_label), Style::NoStyle)]; + vec![(format!("{}{expected_label} `", " ".repeat(expected_padding)), Style::NoStyle)]; msg.extend(expected.0.iter().map(|x| match *x { StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle), StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight), })); - msg.push((format!("`{}\n", expected_extra), Style::NoStyle)); - msg.push((format!("{}{} `", " ".repeat(found_padding), found_label), Style::NoStyle)); + msg.push((format!("`{expected_extra}\n"), Style::NoStyle)); + msg.push((format!("{}{found_label} `", " ".repeat(found_padding)), Style::NoStyle)); msg.extend(found.0.iter().map(|x| match *x { StringPart::Normal(ref s) => (s.to_owned(), Style::NoStyle), StringPart::Highlighted(ref s) => (s.to_owned(), Style::Highlight), })); - msg.push((format!("`{}", found_extra), Style::NoStyle)); + msg.push((format!("`{found_extra}"), Style::NoStyle)); // For now, just attach these as notes. self.highlighted_note(msg); @@ -528,7 +528,7 @@ impl Diagnostic { pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self { self.highlighted_note(vec![ - (format!("`{}` from trait: `", name), Style::NoStyle), + (format!("`{name}` from trait: `"), Style::NoStyle), (signature, Style::Highlight), ("`".to_string(), Style::NoStyle), ]); @@ -628,9 +628,9 @@ impl Diagnostic { /// This is factored out to make sure it does the right thing with `Cargo.toml`. pub fn help_use_latest_edition(&mut self) -> &mut Self { if std::env::var_os("CARGO").is_some() { - self.help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION)); + self.help(&format!("set `edition = \"{LATEST_STABLE_EDITION}\"` in `Cargo.toml`")); } else { - self.help(&format!("pass `--edition {}` to `rustc`", LATEST_STABLE_EDITION)); + self.help(&format!("pass `--edition {LATEST_STABLE_EDITION}` to `rustc`")); } self.note("for more on editions, read https://doc.rust-lang.org/edition-guide"); self diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 66fbb8f1213e0..ecfc98adab78a 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -1958,7 +1958,7 @@ impl EmitterWriter { } if suggestions.len() > MAX_SUGGESTIONS { let others = suggestions.len() - MAX_SUGGESTIONS; - let msg = format!("and {} other candidate{}", others, pluralize!(others)); + let msg = format!("and {others} other candidate{}", pluralize!(others)); buffer.puts(row_num, max_line_num_len + 3, &msg, Style::NoStyle); } else if notice_capitalization { let msg = "notice the capitalization difference"; @@ -2000,7 +2000,7 @@ impl EmitterWriter { &mut self.dst, self.short_message, ) { - panic!("failed to emit error: {}", e) + panic!("failed to emit error: {e}") } } if !self.short_message { @@ -2015,7 +2015,7 @@ impl EmitterWriter { max_line_num_len, true, ) { - panic!("failed to emit error: {}", err); + panic!("failed to emit error: {err}"); } } for sugg in suggestions { @@ -2031,7 +2031,7 @@ impl EmitterWriter { max_line_num_len, true, ) { - panic!("failed to emit error: {}", e); + panic!("failed to emit error: {e}"); } } else if let Err(e) = self.emit_suggestion_default( span, @@ -2040,20 +2040,20 @@ impl EmitterWriter { &Level::Help, max_line_num_len, ) { - panic!("failed to emit error: {}", e); + panic!("failed to emit error: {e}"); }; } } } - Err(e) => panic!("failed to emit error: {}", e), + Err(e) => panic!("failed to emit error: {e}"), } let mut dst = self.dst.writable(); match writeln!(dst) { - Err(e) => panic!("failed to emit error: {}", e), + Err(e) => panic!("failed to emit error: {e}"), _ => { if let Err(e) = dst.flush() { - panic!("failed to emit error: {}", e) + panic!("failed to emit error: {e}") } } } diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index 1680c6accd78c..4d87f54a67591 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -143,7 +143,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print diagnostics: {:?}", e); + panic!("failed to print diagnostics: {e:?}"); } } @@ -156,7 +156,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print notification: {:?}", e); + panic!("failed to print notification: {e:?}"); } } @@ -178,7 +178,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print future breakage report: {:?}", e); + panic!("failed to print future breakage report: {e:?}"); } } @@ -192,7 +192,7 @@ impl Emitter for JsonEmitter { } .and_then(|_| self.dst.flush()); if let Err(e) = result { - panic!("failed to print unused externs: {:?}", e); + panic!("failed to print unused externs: {e:?}"); } } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 94a493992e593..ef941cde36fbf 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -1686,7 +1686,7 @@ pub fn add_elided_lifetime_in_path_suggestion( } let anon_lts = vec!["'_"; n].join(", "); let suggestion = - if incl_angl_brckt { format!("<{}>", anon_lts) } else { format!("{}, ", anon_lts) }; + if incl_angl_brckt { format!("<{anon_lts}>") } else { format!("{anon_lts}, ") }; diag.span_suggestion_verbose( insertion_span.shrink_to_hi(), &format!("indicate the anonymous lifetime{}", pluralize!(n)), diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 5ee6c9f238770..f9ba2384bed71 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -70,7 +70,7 @@ impl std::fmt::Debug for AttributeGate { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { Self::Gated(ref stab, name, expl, _) => { - write!(fmt, "Gated({:?}, {}, {})", stab, name, expl) + write!(fmt, "Gated({stab:?}, {name}, {expl})") } Self::Ungated => write!(fmt, "Ungated"), } diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index bdaa0ee88eba1..8e2a13a6c0ab1 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -120,7 +120,7 @@ fn find_lang_feature_issue(feature: Symbol) -> Option { .find(|t| t.name == feature); match found { Some(found) => found.issue, - None => panic!("feature `{}` is not declared anywhere", feature), + None => panic!("feature `{feature}` is not declared anywhere"), } } } diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index 3c1bb5532661a..963c77c9e7385 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -512,7 +512,7 @@ impl<'a> LabelText<'a> { match *self { LabelStr(ref s) => format!("\"{}\"", s.escape_default()), EscStr(ref s) => format!("\"{}\"", LabelText::escape_str(&s)), - HtmlStr(ref s) => format!("<{}>", s), + HtmlStr(ref s) => format!("<{s}>"), } } @@ -618,7 +618,7 @@ where if let Some(fontname) = options.iter().find_map(|option| { if let RenderOption::Fontname(fontname) = option { Some(fontname) } else { None } }) { - font = format!(r#"fontname="{}""#, fontname); + font = format!(r#"fontname="{fontname}""#); graph_attrs.push(&font[..]); content_attrs.push(&font[..]); } @@ -631,8 +631,8 @@ where if !(graph_attrs.is_empty() && content_attrs.is_empty()) { writeln!(w, r#" graph[{}];"#, graph_attrs.join(" "))?; let content_attrs_str = content_attrs.join(" "); - writeln!(w, r#" node[{}];"#, content_attrs_str)?; - writeln!(w, r#" edge[{}];"#, content_attrs_str)?; + writeln!(w, r#" node[{content_attrs_str}];"#)?; + writeln!(w, r#" edge[{content_attrs_str}];"#)?; } let mut text = Vec::new(); @@ -645,7 +645,7 @@ where write!(text, "{}", id.as_slice()).unwrap(); if !options.contains(&RenderOption::NoNodeLabels) { - write!(text, "[label={}]", escaped).unwrap(); + write!(text, "[label={escaped}]").unwrap(); } let style = g.node_style(n); @@ -674,7 +674,7 @@ where write!(text, "{} -> {}", source_id.as_slice(), target_id.as_slice()).unwrap(); if !options.contains(&RenderOption::NoEdgeLabels) { - write!(text, "[label={}]", escaped_label).unwrap(); + write!(text, "[label={escaped_label}]").unwrap(); } let style = g.edge_style(e); diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index f1f0c224bbdd1..53af539fe3b72 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -602,7 +602,7 @@ impl Res { Id: Debug, { self.opt_def_id() - .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self)) + .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {self:?}")) } /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`. diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index d85ac960f9b2f..8e4a1ff681f57 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -163,13 +163,13 @@ impl DisambiguatedDefPathData { match self.data.name() { DefPathDataName::Named(name) => { if verbose && self.disambiguator != 0 { - write!(writer, "{}#{}", name, self.disambiguator) + write!(writer, "{name}#{}", self.disambiguator) } else { writer.write_str(name.as_str()) } } DefPathDataName::Anon { namespace } => { - write!(writer, "{{{}#{}}}", namespace, self.disambiguator) + write!(writer, "{{{namespace}#{}}}", self.disambiguator) } } } @@ -224,7 +224,7 @@ impl DefPath { let mut s = String::with_capacity(self.data.len() * 16); for component in &self.data { - write!(s, "::{}", component).unwrap(); + write!(s, "::{component}").unwrap(); } s @@ -240,7 +240,7 @@ impl DefPath { for component in &self.data { s.extend(opt_delimiter); opt_delimiter = Some('-'); - write!(s, "{}", component).unwrap(); + write!(s, "{component}").unwrap(); } s @@ -433,7 +433,7 @@ impl fmt::Display for DefPathData { match self.name() { DefPathDataName::Named(name) => f.write_str(name.as_str()), // FIXME(#70334): this will generate legacy {{closure}}, {{impl}}, etc - DefPathDataName::Anon { namespace } => write!(f, "{{{{{}}}}}", namespace), + DefPathDataName::Anon { namespace } => write!(f, "{{{{{namespace}}}}}"), } } } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index 752f760ea9719..4a1cc78cd1845 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -92,7 +92,7 @@ impl HirId { impl fmt::Display for HirId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 35a58296e370e..2f19778bdde84 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -1279,7 +1279,7 @@ impl<'a> State<'a> { hir::InlineAsmOperand::In { reg, ref expr } => { s.word("in"); s.popen(); - s.word(format!("{}", reg)); + s.word(format!("{reg}")); s.pclose(); s.space(); s.print_expr(expr); @@ -1287,7 +1287,7 @@ impl<'a> State<'a> { hir::InlineAsmOperand::Out { reg, late, ref expr } => { s.word(if late { "lateout" } else { "out" }); s.popen(); - s.word(format!("{}", reg)); + s.word(format!("{reg}")); s.pclose(); s.space(); match expr { @@ -1298,7 +1298,7 @@ impl<'a> State<'a> { hir::InlineAsmOperand::InOut { reg, late, ref expr } => { s.word(if late { "inlateout" } else { "inout" }); s.popen(); - s.word(format!("{}", reg)); + s.word(format!("{reg}")); s.pclose(); s.space(); s.print_expr(expr); @@ -1306,7 +1306,7 @@ impl<'a> State<'a> { hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => { s.word(if late { "inlateout" } else { "inout" }); s.popen(); - s.word(format!("{}", reg)); + s.word(format!("{reg}")); s.pclose(); s.space(); s.print_expr(in_expr); diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index 777112442f010..4c4a72ed149cf 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -1091,7 +1091,7 @@ impl ToString for BitSet { assert!(mask <= 0xFF); let byte = word & mask; - result.push_str(&format!("{}{:02x}", sep, byte)); + result.push_str(&format!("{sep}{byte:02x}")); if remain <= 8 { break; diff --git a/compiler/rustc_index/src/bit_set/tests.rs b/compiler/rustc_index/src/bit_set/tests.rs index 351d62feed949..912077dba8203 100644 --- a/compiler/rustc_index/src/bit_set/tests.rs +++ b/compiler/rustc_index/src/bit_set/tests.rs @@ -548,7 +548,7 @@ fn matrix_iter() { assert_eq!(count, 100); if let Some(i) = matrix.iter(7).next() { - panic!("expected no elements in row, but contains element {:?}", i); + panic!("expected no elements in row, but contains element {i:?}"); } } @@ -673,7 +673,7 @@ fn dense_insert_range() { assert!(range.contains(&i)); } for i in range.clone() { - assert!(set.contains(i), "{} in {:?}, inserted {:?}", i, set, range); + assert!(set.contains(i), "{i} in {set:?}, inserted {range:?}"); } } check(300, 10..10); diff --git a/compiler/rustc_index/src/interval/tests.rs b/compiler/rustc_index/src/interval/tests.rs index 375af60f66207..f8901e46faed9 100644 --- a/compiler/rustc_index/src/interval/tests.rs +++ b/compiler/rustc_index/src/interval/tests.rs @@ -86,14 +86,14 @@ fn insert_range() { assert!(range.contains(&i)); } for i in range.clone() { - assert!(set.contains(i), "A: {} in {:?}, inserted {:?}", i, set, range); + assert!(set.contains(i), "A: {i} in {set:?}, inserted {range:?}"); } set.insert_range(range.clone()); for i in set.iter() { - assert!(range.contains(&i), "{} in {:?}", i, set); + assert!(range.contains(&i), "{i} in {set:?}"); } for i in range.clone() { - assert!(set.contains(i), "B: {} in {:?}, inserted {:?}", i, set, range); + assert!(set.contains(i), "B: {i} in {set:?}, inserted {range:?}"); } } check(10..10); diff --git a/compiler/rustc_lexer/src/tests.rs b/compiler/rustc_lexer/src/tests.rs index e4c1787f2ccef..5630baa1593d1 100644 --- a/compiler/rustc_lexer/src/tests.rs +++ b/compiler/rustc_lexer/src/tests.rs @@ -3,7 +3,7 @@ use super::*; use expect_test::{expect, Expect}; fn check_raw_str(s: &str, expected: Result) { - let s = &format!("r{}", s); + let s = &format!("r{s}"); let mut cursor = Cursor::new(s); cursor.bump(); let res = cursor.raw_double_quoted_string(0); @@ -135,7 +135,7 @@ fn test_shebang_followed_by_attrib() { } fn check_lexing(src: &str, expect: Expect) { - let actual: String = tokenize(src).map(|token| format!("{:?}\n", token)).collect(); + let actual: String = tokenize(src).map(|token| format!("{token:?}\n")).collect(); expect.assert_eq(&actual) } diff --git a/compiler/rustc_llvm/build.rs b/compiler/rustc_llvm/build.rs index 28e092c1eb72c..bea4b85dc2dc2 100644 --- a/compiler/rustc_llvm/build.rs +++ b/compiler/rustc_llvm/build.rs @@ -58,7 +58,7 @@ fn restore_library_path() { /// Supposed to be used for all variables except those set for build scripts by cargo /// fn tracked_env_var_os + Display>(key: K) -> Option { - println!("cargo:rerun-if-env-changed={}", key); + println!("cargo:rerun-if-env-changed={key}"); env::var_os(key) } @@ -84,7 +84,7 @@ fn output(cmd: &mut Command) -> String { let output = match cmd.stderr(Stdio::inherit()).output() { Ok(status) => status, Err(e) => { - println!("\n\nfailed to execute command: {:?}\nerror: {}\n\n", cmd, e); + println!("\n\nfailed to execute command: {cmd:?}\nerror: {e}\n\n"); std::process::exit(1); } }; @@ -100,7 +100,7 @@ fn output(cmd: &mut Command) -> String { fn main() { for component in REQUIRED_COMPONENTS.iter().chain(OPTIONAL_COMPONENTS.iter()) { - println!("cargo:rustc-check-cfg=values(llvm_component,\"{}\")", component); + println!("cargo:rustc-check-cfg=values(llvm_component,\"{component}\")"); } if tracked_env_var_os("RUST_CHECK").is_some() { @@ -164,12 +164,12 @@ fn main() { for component in REQUIRED_COMPONENTS { if !components.contains(component) { - panic!("require llvm component {} but wasn't found", component); + panic!("require llvm component {component} but wasn't found"); } } for component in components.iter() { - println!("cargo:rustc-cfg=llvm_component=\"{}\"", component); + println!("cargo:rustc-cfg=llvm_component=\"{component}\""); } // Link in our own LLVM shims, compiled with the same flags as LLVM @@ -280,7 +280,7 @@ fn main() { } let kind = if name.starts_with("LLVM") { llvm_kind } else { "dylib" }; - println!("cargo:rustc-link-lib={}={}", kind, name); + println!("cargo:rustc-link-lib={kind}={name}"); } // LLVM ldflags @@ -299,11 +299,11 @@ fn main() { println!("cargo:rustc-link-search=native={}", stripped.replace(&host, &target)); } } else if let Some(stripped) = lib.strip_prefix("-LIBPATH:") { - println!("cargo:rustc-link-search=native={}", stripped); + println!("cargo:rustc-link-search=native={stripped}"); } else if let Some(stripped) = lib.strip_prefix("-l") { - println!("cargo:rustc-link-lib={}", stripped); + println!("cargo:rustc-link-lib={stripped}"); } else if let Some(stripped) = lib.strip_prefix("-L") { - println!("cargo:rustc-link-search=native={}", stripped); + println!("cargo:rustc-link-search=native={stripped}"); } } @@ -315,9 +315,9 @@ fn main() { if let Some(s) = llvm_linker_flags { for lib in s.into_string().unwrap().split_whitespace() { if let Some(stripped) = lib.strip_prefix("-l") { - println!("cargo:rustc-link-lib={}", stripped); + println!("cargo:rustc-link-lib={stripped}"); } else if let Some(stripped) = lib.strip_prefix("-L") { - println!("cargo:rustc-link-search=native={}", stripped); + println!("cargo:rustc-link-search=native={stripped}"); } } } @@ -356,14 +356,14 @@ fn main() { let path = PathBuf::from(s); println!("cargo:rustc-link-search=native={}", path.parent().unwrap().display()); if target.contains("windows") { - println!("cargo:rustc-link-lib=static:-bundle={}", stdcppname); + println!("cargo:rustc-link-lib=static:-bundle={stdcppname}"); } else { - println!("cargo:rustc-link-lib=static={}", stdcppname); + println!("cargo:rustc-link-lib=static={stdcppname}"); } } else if cxxflags.contains("stdlib=libc++") { println!("cargo:rustc-link-lib=c++"); } else { - println!("cargo:rustc-link-lib={}", stdcppname); + println!("cargo:rustc-link-lib={stdcppname}"); } } diff --git a/compiler/rustc_macros/src/diagnostics/error.rs b/compiler/rustc_macros/src/diagnostics/error.rs index 0b1ededa77510..8a2f1e04e4c03 100644 --- a/compiler/rustc_macros/src/diagnostics/error.rs +++ b/compiler/rustc_macros/src/diagnostics/error.rs @@ -76,11 +76,11 @@ pub(crate) fn invalid_attr(attr: &Attribute, meta: &Meta) -> Diagnostic { let span = attr.span().unwrap(); let path = path_to_string(&attr.path); match meta { - Meta::Path(_) => span_err(span, &format!("`#[{}]` is not a valid attribute", path)), + Meta::Path(_) => span_err(span, &format!("`#[{path}]` is not a valid attribute")), Meta::NameValue(_) => { - span_err(span, &format!("`#[{} = ...]` is not a valid attribute", path)) + span_err(span, &format!("`#[{path} = ...]` is not a valid attribute")) } - Meta::List(_) => span_err(span, &format!("`#[{}(...)]` is not a valid attribute", path)), + Meta::List(_) => span_err(span, &format!("`#[{path}(...)]` is not a valid attribute")), } } @@ -107,7 +107,7 @@ pub(crate) fn invalid_nested_attr(attr: &Attribute, nested: &NestedMeta) -> Diag let meta = match nested { syn::NestedMeta::Meta(meta) => meta, syn::NestedMeta::Lit(_) => { - return span_err(span, &format!("`#[{}(\"...\")]` is not a valid attribute", name)); + return span_err(span, &format!("`#[{name}(\"...\")]` is not a valid attribute")); } }; @@ -115,13 +115,13 @@ pub(crate) fn invalid_nested_attr(attr: &Attribute, nested: &NestedMeta) -> Diag let path = path_to_string(meta.path()); match meta { Meta::NameValue(..) => { - span_err(span, &format!("`#[{}({} = ...)]` is not a valid attribute", name, path)) + span_err(span, &format!("`#[{name}({path} = ...)]` is not a valid attribute")) } Meta::Path(..) => { - span_err(span, &format!("`#[{}({})]` is not a valid attribute", name, path)) + span_err(span, &format!("`#[{name}({path})]` is not a valid attribute")) } Meta::List(..) => { - span_err(span, &format!("`#[{}({}(...))]` is not a valid attribute", name, path)) + span_err(span, &format!("`#[{name}({path}(...))]` is not a valid attribute")) } } } diff --git a/compiler/rustc_macros/src/diagnostics/fluent.rs b/compiler/rustc_macros/src/diagnostics/fluent.rs index f7d8b494ee257..e618f9a841cd0 100644 --- a/compiler/rustc_macros/src/diagnostics/fluent.rs +++ b/compiler/rustc_macros/src/diagnostics/fluent.rs @@ -177,7 +177,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok opt: Default::default(), }; let dl = DisplayList::from(snippet); - eprintln!("{}\n", dl); + eprintln!("{dl}\n"); } continue; } @@ -263,7 +263,7 @@ pub(crate) fn fluent_messages(input: proc_macro::TokenStream) -> proc_macro::Tok Diagnostic::spanned( path_span, Level::Error, - format!("overrides existing {}: `{}`", kind, id), + format!("overrides existing {kind}: `{id}`"), ) .span_help(previous_defns[&id], "previously defined in this resource") .emit(); diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index 162699c286872..3debef044fc99 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -300,7 +300,7 @@ pub(crate) trait HasFieldMap { None => { span_err( span.unwrap(), - &format!("`{}` doesn't refer to a field on this type", field), + &format!("`{field}` doesn't refer to a field on this type"), ) .emit(); quote! { diff --git a/compiler/rustc_macros/src/newtype.rs b/compiler/rustc_macros/src/newtype.rs index 0a77b734c7641..c76d5f02c2a85 100644 --- a/compiler/rustc_macros/src/newtype.rs +++ b/compiler/rustc_macros/src/newtype.rs @@ -79,7 +79,7 @@ impl Parse for Newtype { }; try_comma()?; if let Some(old) = debug_format.replace(new_debug_format) { - panic!("Specified multiple debug format options: {:?}", old); + panic!("Specified multiple debug format options: {old:?}"); } continue; } @@ -89,7 +89,7 @@ impl Parse for Newtype { let val: Lit = body.parse()?; try_comma()?; if let Some(old) = max.replace(val) { - panic!("Specified multiple MAX: {:?}", old); + panic!("Specified multiple MAX: {old:?}"); } continue; } diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index d49926c90ca9f..18f5127e892c7 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -232,7 +232,7 @@ fn doc_comment_from_desc(list: &Punctuated) -> Result (TokenStream, Vec) { let mut check_dup = |span: Span, str: &str, errors: &mut Errors| { if let Some(prev_span) = keys.get(str) { - errors.error(span, format!("Symbol `{}` is duplicated", str)); + errors.error(span, format!("Symbol `{str}` is duplicated")); errors.error(*prev_span, "location of previous definition".to_string()); } else { keys.insert(str.to_string(), span); @@ -144,8 +144,8 @@ fn symbols_with_errors(input: TokenStream) -> (TokenStream, Vec) { let mut check_order = |span: Span, str: &str, errors: &mut Errors| { if let Some((prev_span, ref prev_str)) = prev_key { if str < prev_str { - errors.error(span, format!("Symbol `{}` must precede `{}`", str, prev_str)); - errors.error(prev_span, format!("location of previous symbol `{}`", prev_str)); + errors.error(span, format!("Symbol `{str}` must precede `{prev_str}`")); + errors.error(prev_span, format!("location of previous symbol `{prev_str}`")); } } prev_key = Some((span, str.to_string())); diff --git a/compiler/rustc_macros/src/symbols/tests.rs b/compiler/rustc_macros/src/symbols/tests.rs index 842d2a977189d..100f33dca07d9 100644 --- a/compiler/rustc_macros/src/symbols/tests.rs +++ b/compiler/rustc_macros/src/symbols/tests.rs @@ -44,7 +44,7 @@ fn test_symbols_macro(input: TokenStream, expected_errors: &[&str]) { ); for (found_error, &expected_error) in found_errors.iter().zip(expected_errors) { - let found_error_str = format!("{}", found_error); + let found_error_str = format!("{found_error}"); assert_eq!(found_error_str, expected_error); } } diff --git a/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs index 3d6095d2738cb..f41adf667ec55 100644 --- a/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs +++ b/compiler/rustc_mir_transform/src/coverage/test_macros/src/lib.rs @@ -2,5 +2,5 @@ use proc_macro::TokenStream; #[proc_macro] pub fn let_bcb(item: TokenStream) -> TokenStream { - format!("let bcb{} = graph::BasicCoverageBlock::from_usize({});", item, item).parse().unwrap() + format!("let bcb{item} = graph::BasicCoverageBlock::from_usize({item});").parse().unwrap() } diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 88540e13ef243..78566baf8f66a 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -137,7 +137,7 @@ impl<'a> StringReader<'a> { let span = self.mk_sp(start, self.pos); self.sess.symbol_gallery.insert(sym, span); if !sym.can_be_raw() { - self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); + self.err_span(span, &format!("`{sym}` cannot be a raw identifier")); } self.sess.raw_identifier_spans.borrow_mut().push(span); token::Ident(sym, true) @@ -294,7 +294,7 @@ impl<'a> StringReader<'a> { ) -> DiagnosticBuilder<'a, !> { self.sess .span_diagnostic - .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) + .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{m}: {}", escaped_char(c))) } fn struct_err_span_char( @@ -306,7 +306,7 @@ impl<'a> StringReader<'a> { ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { self.sess .span_diagnostic - .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) + .struct_span_err(self.mk_sp(from_pos, to_pos), &format!("{m}: {}", escaped_char(c))) } /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly @@ -605,7 +605,7 @@ impl<'a> StringReader<'a> { fn report_unknown_prefix(&self, start: BytePos) { let prefix_span = self.mk_sp(start, self.pos); let prefix_str = self.str_from_to(start, self.pos); - let msg = format!("prefix `{}` is unknown", prefix_str); + let msg = format!("prefix `{prefix_str}` is unknown"); let expn_data = prefix_span.ctxt().outer_expn_data(); @@ -697,7 +697,7 @@ impl<'a> StringReader<'a> { if c != '_' && c.to_digit(base).is_none() { let lo = content_start + BytePos(2 + idx); let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); - self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); + self.err_span_(lo, hi, &format!("invalid digit for a base {base} literal")); } } } diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index b2701817d489b..9f51841b197aa 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -232,7 +232,7 @@ impl<'a> TokenTreesReader<'a> { // An unexpected closing delimiter (i.e., there is no // matching opening delimiter). let token_str = token_to_string(&self.token); - let msg = format!("unexpected closing delimiter: `{}`", token_str); + let msg = format!("unexpected closing delimiter: `{token_str}`"); let mut err = self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); diff --git a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs index 77c4fadab45ea..a9f2cb2aef82f 100644 --- a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs +++ b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs @@ -117,7 +117,7 @@ pub(crate) fn emit_unescape_error( handler.span_suggestion( span_with_quotes, msg, - format!("{}\"{}\"", prefix, lit), + format!("{prefix}\"{lit}\""), Applicability::MachineApplicable, ); } @@ -133,7 +133,7 @@ pub(crate) fn emit_unescape_error( "character constant must be escaped" }; handler - .struct_span_err(span, &format!("{}: `{}`", msg, escaped_char(c))) + .struct_span_err(span, &format!("{msg}: `{}`", escaped_char(c))) .span_suggestion( char_span, "escape the character", @@ -169,7 +169,7 @@ pub(crate) fn emit_unescape_error( let label = if mode.is_bytes() { "unknown byte escape" } else { "unknown character escape" }; let ec = escaped_char(c); - let mut diag = handler.struct_span_err(span, &format!("{}: `{}`", label, ec)); + let mut diag = handler.struct_span_err(span, &format!("{label}: `{ec}`")); diag.span_label(span, label); if c == '{' || c == '}' && !mode.is_bytes() { diag.help( @@ -185,7 +185,7 @@ pub(crate) fn emit_unescape_error( diag.span_suggestion( span_with_quotes, "if you meant to write a literal backslash (perhaps escaping in a regular expression), consider a raw string literal", - format!("r\"{}\"", lit), + format!("r\"{lit}\""), Applicability::MaybeIncorrect, ); } @@ -211,7 +211,7 @@ pub(crate) fn emit_unescape_error( let c = escaped_char(c); handler - .struct_span_err(span, &format!("{}: `{}`", msg, c)) + .struct_span_err(span, &format!("{msg}: `{c}`")) .span_label(span, msg) .emit(); } @@ -220,11 +220,11 @@ pub(crate) fn emit_unescape_error( let (c, span) = last_char(); let mut err = handler.struct_span_err(span, "non-ASCII character in byte constant"); let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 { - format!(" but is {:?}", c) + format!(" but is {c:?}") } else { String::new() }; - err.span_label(span, &format!("byte constant must be ASCII{}", postfix)); + err.span_label(span, &format!("byte constant must be ASCII{postfix}")); if (c as u32) <= 0xFF { err.span_suggestion( span, @@ -259,13 +259,13 @@ pub(crate) fn emit_unescape_error( assert!(mode.is_bytes()); let (c, span) = last_char(); let postfix = if unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) == 0 { - format!(" but is {:?}", c) + format!(" but is {c:?}") } else { String::new() }; handler .struct_span_err(span, "raw byte string must be ASCII") - .span_label(span, &format!("must be ASCII{}", postfix)) + .span_label(span, &format!("must be ASCII{postfix}")) .emit(); } EscapeError::OutOfRangeHexEscape => { @@ -278,7 +278,7 @@ pub(crate) fn emit_unescape_error( let (c, span) = last_char(); let msg = "invalid start of unicode escape"; handler - .struct_span_err(span, &format!("{}: `{}`", msg, c)) + .struct_span_err(span, &format!("{msg}: `{c}`")) .span_label(span, msg) .emit(); } diff --git a/compiler/rustc_parse/src/lexer/unicode_chars.rs b/compiler/rustc_parse/src/lexer/unicode_chars.rs index 2c68cc5895c6e..932e5f77b3338 100644 --- a/compiler/rustc_parse/src/lexer/unicode_chars.rs +++ b/compiler/rustc_parse/src/lexer/unicode_chars.rs @@ -343,7 +343,7 @@ pub(super) fn check_for_substitution<'a>( let span = Span::with_root_ctxt(pos, pos + Pos::from_usize(ch.len_utf8())); let Some((_ascii_char, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(c, _, _)| c == ascii_char) else { - let msg = format!("substitution character not found for '{}'", ch); + let msg = format!("substitution character not found for '{ch}'"); reader.sess.span_diagnostic.span_bug_no_panic(span, &msg); return None; }; @@ -361,7 +361,7 @@ pub(super) fn check_for_substitution<'a>( pos + Pos::from_usize('“'.len_utf8() + s.len() + '”'.len_utf8()), ), &msg, - format!("\"{}\"", s), + format!("\"{s}\""), Applicability::MaybeIncorrect, ); } else { diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 0bdfe10359c0b..66650e20ebbd7 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -151,7 +151,7 @@ fn try_file_to_source_file( spanopt: Option, ) -> Result, Diagnostic> { sess.source_map().load_file(path).map_err(|e| { - let msg = format!("couldn't read {}: {}", path.display(), e); + let msg = format!("couldn't read {}: {e}", path.display()); let mut diag = Diagnostic::new(Level::Fatal, &msg); if let Some(sp) = spanopt { diag.set_span(sp); @@ -261,7 +261,7 @@ pub fn parse_cfg_attr( match parse_in(parse_sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) { Ok(r) => return Some(r), Err(mut e) => { - e.help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP)) + e.help(&format!("the valid syntax is `{CFG_ATTR_GRAMMAR_HELP}`")) .note(CFG_ATTR_NOTE_REF) .emit(); } diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index 0dc05475ce944..466a052154d49 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -140,7 +140,7 @@ impl ToAttrTokenStream for LazyAttrTokenStreamImpl { // another replace range will capture the *replaced* tokens for the inner // range, not the original tokens. for (range, new_tokens) in replace_ranges.into_iter().rev() { - assert!(!range.is_empty(), "Cannot replace an empty range: {:?}", range); + assert!(!range.is_empty(), "Cannot replace an empty range: {range:?}"); // Replace ranges are only allowed to decrease the number of tokens. assert!( range.len() >= new_tokens.len(), @@ -401,7 +401,7 @@ fn make_token_stream( FlatToken::Token(Token { kind: TokenKind::CloseDelim(delim), span }) => { let frame_data = stack .pop() - .unwrap_or_else(|| panic!("Token stack was empty for token: {:?}", token)); + .unwrap_or_else(|| panic!("Token stack was empty for token: {token:?}")); let (open_delim, open_sp) = frame_data.open_delim_sp.unwrap(); assert_eq!( @@ -415,7 +415,7 @@ fn make_token_stream( stack .last_mut() .unwrap_or_else(|| { - panic!("Bottom token frame is missing for token: {:?}", token) + panic!("Bottom token frame is missing for token: {token:?}") }) .inner .push(delimited); @@ -448,7 +448,7 @@ fn make_token_stream( .inner .push(AttrTokenTree::Token(Token::new(unglued_first, first_span), spacing)); } else { - panic!("Unexpected last token {:?}", last_token) + panic!("Unexpected last token {last_token:?}") } } AttrTokenStream::new(final_buf.inner) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index f57bd9cec1920..9a29ac8e159ec 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1346,7 +1346,7 @@ impl<'a> Parser<'a> { msg: format!("use `{}= 1` instead", kind.op.chr()), patches: vec![ (pre_span, "{ ".to_string()), - (post_span, format!(" {}= 1; {} }}", kind.op.chr(), base_src)), + (post_span, format!(" {}= 1; {base_src} }}", kind.op.chr())), ], applicability: Applicability::MachineApplicable, } @@ -1363,7 +1363,7 @@ impl<'a> Parser<'a> { msg: format!("use `{}= 1` instead", kind.op.chr()), patches: vec![ (pre_span, format!("{{ let {tmp_var} = ")), - (post_span, format!("; {} {}= 1; {} }}", base_src, kind.op.chr(), tmp_var)), + (post_span, format!("; {base_src} {}= 1; {tmp_var} }}", kind.op.chr())), ], applicability: Applicability::HasPlaceholders, } @@ -1413,7 +1413,7 @@ impl<'a> Parser<'a> { let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty)); self.sess.emit_err(BadQPathStage2 { span: path.span, - ty: format!("<{}>::{}", ty_str, pprust::path_to_string(&path)), + ty: format!("<{ty_str}>::{}", pprust::path_to_string(&path)), }); let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`. diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 11301f03e48eb..b23489524de0a 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -1067,7 +1067,7 @@ impl<'a> Parser<'a> { } components.push(Punct(c)); } else { - panic!("unexpected character in a float token: {:?}", c) + panic!("unexpected character in a float token: {c:?}") } } if !ident_like.is_empty() { @@ -1139,7 +1139,7 @@ impl<'a> Parser<'a> { self.error_unexpected_after_dot(); base } - _ => panic!("unexpected components in a float token: {:?}", components), + _ => panic!("unexpected components in a float token: {components:?}"), } } diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 25425fbb2c6a6..9f7901db26843 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -407,7 +407,7 @@ impl<'a> Parser<'a> { err.span_suggestion( full_sp, "if you meant to call a macro, try", - format!("{}!", snippet), + format!("{snippet}!"), // this is the `ambiguous` conditional branch Applicability::MaybeIncorrect, ); @@ -435,7 +435,7 @@ impl<'a> Parser<'a> { err.span_suggestion_short( sp, &format!("add `{kw}` here to parse `{ident}` as a public {kw_name}"), - format!(" {} ", kw), + format!(" {kw} "), Applicability::MachineApplicable, ); } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index b934e087608a5..281b45ab11c9f 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -374,7 +374,7 @@ impl TokenType { fn to_string(&self) -> String { match *self { TokenType::Token(ref t) => format!("`{}`", pprust::token_kind_to_string(t)), - TokenType::Keyword(kw) => format!("`{}`", kw), + TokenType::Keyword(kw) => format!("`{kw}`"), TokenType::Operator => "an operator".to_string(), TokenType::Lifetime => "lifetime".to_string(), TokenType::Ident => "identifier".to_string(), @@ -444,7 +444,7 @@ pub(super) fn token_descr(token: &Token) -> String { TokenDescription::DocComment => "doc comment", }); - if let Some(kind) = kind { format!("{} `{}`", kind, name) } else { format!("`{}`", name) } + if let Some(kind) = kind { format!("{kind} `{name}`") } else { format!("`{name}`") } } impl<'a> Parser<'a> { @@ -861,7 +861,7 @@ impl<'a> Parser<'a> { expect_err .span_suggestion_short( sp, - &format!("missing `{}`", token_str), + &format!("missing `{token_str}`"), token_str, Applicability::MaybeIncorrect, ) diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 0250b518243c1..a9bfc349dbdb1 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -181,7 +181,7 @@ impl<'a> Parser<'a> { let colon = self.eat(&token::Colon); if let PatKind::Or(pats) = &pat.kind { - let msg = format!("top-level or-patterns are not allowed in {}", syntax_loc); + let msg = format!("top-level or-patterns are not allowed in {syntax_loc}"); let (help, fix) = if pats.len() == 1 { // If all we have is a leading vert, then print a special message. This is the case // if `parse_pat_allow_top_alt` returns an or-pattern with one variant. @@ -296,7 +296,7 @@ impl<'a> Parser<'a> { /// A `|` or possibly `||` token shouldn't be here. Ban it. fn ban_illegal_vert(&mut self, lo: Option, pos: &str, ctx: &str) { let span = self.token.span; - let mut err = self.struct_span_err(span, &format!("a {} `|` is {}", pos, ctx)); + let mut err = self.struct_span_err(span, &format!("a {pos} `|` is {ctx}")); err.span_suggestion( span, &format!("remove the `{}`", pprust::token_to_string(&self.token)), @@ -539,7 +539,7 @@ impl<'a> Parser<'a> { self.bump(); // `'a` let span = self.prev_token.span; - self.struct_span_err(span, &format!("unexpected lifetime `{}` in pattern", name)) + self.struct_span_err(span, &format!("unexpected lifetime `{name}` in pattern")) .span_suggestion(span, "remove the lifetime", "", Applicability::MachineApplicable) .emit(); } @@ -687,10 +687,10 @@ impl<'a> Parser<'a> { err.cancel(); let expected = expected.unwrap_or("pattern"); - let msg = format!("expected {}, found {}", expected, super::token_descr(&self.token)); + let msg = format!("expected {expected}, found {}", super::token_descr(&self.token)); let mut err = self.struct_span_err(self.token.span, &msg); - err.span_label(self.token.span, format!("expected {}", expected)); + err.span_label(self.token.span, format!("expected {expected}")); let sp = self.sess.source_map().start_point(self.token.span); if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { @@ -996,7 +996,7 @@ impl<'a> Parser<'a> { break; } let token_str = super::token_descr(&self.token); - let msg = &format!("expected `}}`, found {}", token_str); + let msg = &format!("expected `}}`, found {token_str}"); let mut err = self.struct_span_err(self.token.span, msg); err.span_label(self.token.span, "expected `}`"); diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index fdc1af27f82e4..4e22c2923a67f 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -608,7 +608,7 @@ impl<'a> Parser<'a> { ); err.span_suggestion( eq.to(before_next), - &format!("remove the `=` if `{}` is a type", ident), + &format!("remove the `=` if `{ident}` is a type"), "", Applicability::MaybeIncorrect, ) diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index a61e77b7c3bfb..fe750554f10d0 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -273,7 +273,7 @@ impl<'a> Parser<'a> { Ok(ty) => (None, Some(ty)), Err(mut err) => { if let Ok(snip) = self.span_to_snippet(pat.span) { - err.span_label(pat.span, format!("while parsing the type for `{}`", snip)); + err.span_label(pat.span, format!("while parsing the type for `{snip}`")); } // we use noexpect here because we don't actually expect Eq to be here // but we are still checking for it in order to be able to handle it if @@ -474,7 +474,7 @@ impl<'a> Parser<'a> { fn error_block_no_opening_brace(&mut self) -> PResult<'a, T> { let tok = super::token_descr(&self.token); - let msg = format!("expected `{{`, found {}", tok); + let msg = format!("expected `{{`, found {tok}"); Err(self.error_block_no_opening_brace_msg(&msg)) } @@ -571,7 +571,7 @@ impl<'a> Parser<'a> { "add a space before `{}` to use a regular comment", doc_comment_marker, ), - format!("{} {}", comment_marker, doc_comment_marker), + format!("{comment_marker} {doc_comment_marker}"), Applicability::MaybeIncorrect, ); } diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 2a8512acf8cfa..4a15e7cf7b320 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -464,7 +464,7 @@ impl<'a> Parser<'a> { err.span_suggestion( span, "place the lifetime before `mut`", - format!("&{} mut", lifetime_src), + format!("&{lifetime_src} mut"), Applicability::MaybeIncorrect, ); } @@ -546,11 +546,11 @@ impl<'a> Parser<'a> { /// Emit an error for the given bad function pointer qualifier. fn error_fn_ptr_bad_qualifier(&self, span: Span, qual_span: Span, qual: &str) { - self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{}`", qual)) - .span_label(qual_span, format!("`{}` because of this", qual)) + self.struct_span_err(span, &format!("an `fn` pointer type cannot be `{qual}`")) + .span_label(qual_span, format!("`{qual}` because of this")) .span_suggestion_short( qual_span, - &format!("remove the `{}` qualifier", qual), + &format!("remove the `{qual}` qualifier"), "", Applicability::MaybeIncorrect, ) diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 47477898b240e..41b0df8a58a42 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -140,14 +140,14 @@ fn emit_malformed_attribute( matches!(name, sym::doc | sym::ignore | sym::inline | sym::link | sym::test | sym::bench) }; - let error_msg = format!("malformed `{}` attribute input", name); + let error_msg = format!("malformed `{name}` attribute input"); let mut msg = "attribute must be of the form ".to_owned(); let mut suggestions = vec![]; let mut first = true; let inner = if attr.style == ast::AttrStyle::Inner { "!" } else { "" }; if template.word { first = false; - let code = format!("#{}[{}]", inner, name); + let code = format!("#{inner}[{name}]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } @@ -156,7 +156,7 @@ fn emit_malformed_attribute( msg.push_str(" or "); } first = false; - let code = format!("#{}[{}({})]", inner, name, descr); + let code = format!("#{inner}[{name}({descr})]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } @@ -164,7 +164,7 @@ fn emit_malformed_attribute( if !first { msg.push_str(" or "); } - let code = format!("#{}[{} = \"{}\"]", inner, name, descr); + let code = format!("#{inner}[{name} = \"{descr}\"]"); msg.push_str(&format!("`{}`", &code)); suggestions.push(code); } diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index df22d79f82e85..1310d0eece186 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -401,7 +401,7 @@ impl<'a> Parser<'a> { Some(pos) } else { let pos = self.to_span_index(pos); - let description = format!("expected `'}}'`, found `{:?}`", maybe); + let description = format!("expected `'}}'`, found `{maybe:?}`"); let label = "expected `}`".to_owned(); let (note, secondary_label) = if c == '}' { ( @@ -425,12 +425,12 @@ impl<'a> Parser<'a> { None } } else { - let description = format!("expected `{:?}` but string was terminated", c); + let description = format!("expected `{c:?}` but string was terminated"); // point at closing `"` let pos = self.input.len() - if self.append_newline { 1 } else { 0 }; let pos = self.to_span_index(pos); if c == '}' { - let label = format!("expected `{:?}`", c); + let label = format!("expected `{c:?}`"); let (note, secondary_label) = if c == '}' { ( Some( @@ -451,7 +451,7 @@ impl<'a> Parser<'a> { should_be_replaced_with_positional_argument: false, }); } else { - self.err(description, format!("expected `{:?}`", c), pos.to(pos)); + self.err(description, format!("expected `{c:?}`"), pos.to(pos)); } None } diff --git a/compiler/rustc_query_system/src/dep_graph/debug.rs b/compiler/rustc_query_system/src/dep_graph/debug.rs index f9f3169af69c9..c2c9600f5552c 100644 --- a/compiler/rustc_query_system/src/dep_graph/debug.rs +++ b/compiler/rustc_query_system/src/dep_graph/debug.rs @@ -29,7 +29,7 @@ impl DepNodeFilter { /// Tests whether `node` meets the filter, returning true if so. pub fn test(&self, node: &DepNode) -> bool { - let debug_str = format!("{:?}", node); + let debug_str = format!("{node:?}"); self.text.split('&').map(|s| s.trim()).all(|f| debug_str.contains(f)) } } @@ -46,7 +46,7 @@ impl EdgeFilter { pub fn new(test: &str) -> Result, Box> { let parts: Vec<_> = test.split("->").collect(); if parts.len() != 2 { - Err(format!("expected a filter like `a&b -> c&d`, not `{}`", test).into()) + Err(format!("expected a filter like `a&b -> c&d`, not `{test}`").into()) } else { Ok(EdgeFilter { source: DepNodeFilter::new(parts[0]), diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index 5c6ce0556eb8a..26aaa2abc9f4e 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -120,7 +120,7 @@ pub trait DepNodeParams: fmt::Debug + Sized { } fn to_debug_str(&self, _: Ctxt) -> String { - format!("{:?}", self) + format!("{self:?}") } /// This method tries to recover the query key from the given `DepNode`, diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index 8ff56132749df..c687ddb3e631c 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -447,7 +447,7 @@ impl DepGraph { TaskDepsRef::Allow(deps) => deps.lock(), TaskDepsRef::Ignore => return, TaskDepsRef::Forbid => { - panic!("Illegal read of: {:?}", dep_node_index) + panic!("Illegal read of: {dep_node_index:?}") } }; let task_deps = &mut *task_deps; @@ -477,7 +477,7 @@ impl DepGraph { if let Some(ref forbidden_edge) = data.current.forbidden_edge { let src = forbidden_edge.index_to_node.lock()[&dep_node_index]; if forbidden_edge.test(&src, &target) { - panic!("forbidden edge {:?} -> {:?} created", src, target) + panic!("forbidden edge {src:?} -> {target:?} created") } } } @@ -991,7 +991,7 @@ impl CurrentDepGraph { let forbidden_edge = match env::var("RUST_FORBID_DEP_GRAPH_EDGE") { Ok(s) => match EdgeFilter::new(&s) { Ok(f) => Some(f), - Err(err) => panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {}", err), + Err(err) => panic!("RUST_FORBID_DEP_GRAPH_EDGE invalid: {err}"), }, Err(_) => None, }; @@ -1079,7 +1079,7 @@ impl CurrentDepGraph { if let Some(fingerprint) = fingerprint { if fingerprint == prev_graph.fingerprint_by_index(prev_index) { if print_status { - eprintln!("[task::green] {:?}", key); + eprintln!("[task::green] {key:?}"); } // This is a green node: it existed in the previous compilation, @@ -1101,7 +1101,7 @@ impl CurrentDepGraph { (dep_node_index, Some((prev_index, DepNodeColor::Green(dep_node_index)))) } else { if print_status { - eprintln!("[task::red] {:?}", key); + eprintln!("[task::red] {key:?}"); } // This is a red node: it existed in the previous compilation, its query @@ -1124,7 +1124,7 @@ impl CurrentDepGraph { } } else { if print_status { - eprintln!("[task::unknown] {:?}", key); + eprintln!("[task::unknown] {key:?}"); } // This is a red node, effectively: it existed in the previous compilation @@ -1149,7 +1149,7 @@ impl CurrentDepGraph { } } else { if print_status { - eprintln!("[task::new] {:?}", key); + eprintln!("[task::new] {key:?}"); } let fingerprint = fingerprint.unwrap_or(Fingerprint::ZERO); diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index 3b20ec70d73cb..1fee9527f446a 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -272,13 +272,13 @@ impl> GraphEncoder { eprintln!("[incremental]"); eprintln!("[incremental] DepGraph Statistics"); - eprintln!("{}", SEPARATOR); + eprintln!("{SEPARATOR}"); eprintln!("[incremental]"); eprintln!("[incremental] Total Node Count: {}", status.total_node_count); eprintln!("[incremental] Total Edge Count: {}", status.total_edge_count); if cfg!(debug_assertions) { - eprintln!("[incremental] Total Edge Reads: {}", total_read_count); + eprintln!("[incremental] Total Edge Reads: {total_read_count}"); eprintln!( "[incremental] Total Duplicate Edge Reads: {}", total_duplicate_read_count @@ -290,7 +290,7 @@ impl> GraphEncoder { "[incremental] {:<36}| {:<17}| {:<12}| {:<17}|", "Node Kind", "Node Frequency", "Node Count", "Avg. Edge Count" ); - eprintln!("{}", SEPARATOR); + eprintln!("{SEPARATOR}"); for stat in stats { let node_kind_ratio = @@ -306,7 +306,7 @@ impl> GraphEncoder { ); } - eprintln!("{}", SEPARATOR); + eprintln!("{SEPARATOR}"); eprintln!("[incremental]"); } } diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 64aba4703ca3a..7c77fd31491c0 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -617,7 +617,7 @@ pub fn print_query_stack( }; let mut diag = Diagnostic::new( Level::FailureNote, - &format!("#{} [{}] {}", i, query_info.query.name, query_info.query.description), + &format!("#{i} [{}] {}", query_info.query.name, query_info.query.description), ); diag.span = query_info.job.span.into(); handler.force_print_diagnostic(diag); diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 8179a674afaec..b59325ced5a90 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -630,7 +630,7 @@ impl std::fmt::Debug for DebugArg<'_> { #[cold] fn incremental_verify_ich_cold(sess: &Session, dep_node: DebugArg<'_>, result: DebugArg<'_>) { let run_cmd = if let Some(crate_name) = &sess.opts.crate_name { - format!("`cargo clean -p {}` or `cargo clean`", crate_name) + format!("`cargo clean -p {crate_name}` or `cargo clean`") } else { "`cargo clean`".to_string() }; @@ -652,9 +652,9 @@ fn incremental_verify_ich_cold(sess: &Session, dep_node: DebugArg<'_>, result: D } else { sess.emit_err(crate::error::IncrementCompilation { run_cmd, - dep_node: format!("{:?}", dep_node), + dep_node: format!("{dep_node:?}"), }); - panic!("Found unstable fingerprints for {:?}: {:?}", dep_node, result); + panic!("Found unstable fingerprints for {dep_node:?}: {result:?}"); } INSIDE_VERIFY_PANIC.with(|in_panic| in_panic.set(old_in_panic)); diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs index 2511bee46afeb..b7089ecc0be99 100644 --- a/compiler/rustc_session/src/output.rs +++ b/compiler/rustc_session/src/output.rs @@ -117,7 +117,7 @@ pub fn filename_for_metadata( return out_filename.clone(); } - let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename); + let libname = format!("{crate_name}{}", sess.opts.cg.extra_filename); let out_filename = outputs .single_output_file @@ -135,7 +135,7 @@ pub fn filename_for_input( crate_name: &str, outputs: &OutputFilenames, ) -> PathBuf { - let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename); + let libname = format!("{crate_name}{}", sess.opts.cg.extra_filename); match crate_type { CrateType::Rlib => outputs.out_directory.join(&format!("lib{libname}.rlib")), diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index bbeabdb55a72a..6ef1d4af844bd 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -303,7 +303,7 @@ impl DefId { // i.e. don't use closures. match self.as_local() { Some(local_def_id) => local_def_id, - None => panic!("DefId::expect_local: `{:?}` isn't local", self), + None => panic!("DefId::expect_local: `{self:?}` isn't local"), } } diff --git a/compiler/rustc_span/src/edition.rs b/compiler/rustc_span/src/edition.rs index 065d3660e5008..b43183916bca5 100644 --- a/compiler/rustc_span/src/edition.rs +++ b/compiler/rustc_span/src/edition.rs @@ -44,7 +44,7 @@ impl fmt::Display for Edition { Edition::Edition2021 => "2021", Edition::Edition2024 => "2024", }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 191186af6fa08..0cfdc0dbd3eb4 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -108,7 +108,7 @@ fn assert_default_hashing_controls(ctx: &CTX, msg: &str) // enabled. HashingControls { hash_spans } if hash_spans == !ctx.unstable_opts_incremental_ignore_spans() => {} - other => panic!("Attempted hashing of {msg} with non-default HashingControls: {:?}", other), + other => panic!("Attempted hashing of {msg} with non-default HashingControls: {other:?}"), } } @@ -626,7 +626,7 @@ pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symb pub fn debug_hygiene_data(verbose: bool) -> String { HygieneData::with(|data| { if verbose { - format!("{:#?}", data) + format!("{data:#?}") } else { let mut s = String::from("Expansions:"); let mut debug_expn_data = |(id, expn_data): (&ExpnId, &ExpnData)| { @@ -1064,9 +1064,9 @@ impl ExpnKind { match *self { ExpnKind::Root => kw::PathRoot.to_string(), ExpnKind::Macro(macro_kind, name) => match macro_kind { - MacroKind::Bang => format!("{}!", name), - MacroKind::Attr => format!("#[{}]", name), - MacroKind::Derive => format!("#[derive({})]", name), + MacroKind::Bang => format!("{name}!"), + MacroKind::Attr => format!("#[{name}]"), + MacroKind::Derive => format!("#[derive({name})]"), }, ExpnKind::AstPass(kind) => kind.descr().to_string(), ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()), diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index f8df416971593..a52dc60137327 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -320,7 +320,7 @@ impl fmt::Display for FileNameDisplay<'_> { ProcMacroSourceCode(_) => write!(fmt, ""), CfgSpec(_) => write!(fmt, ""), CliCrateAttr(_) => write!(fmt, ""), - Custom(ref s) => write!(fmt, "<{}>", s), + Custom(ref s) => write!(fmt, "<{s}>"), DocTest(ref path, _) => write!(fmt, "{}", path.display()), InlineAsm(_) => write!(fmt, ""), } @@ -1047,7 +1047,7 @@ impl NonNarrowChar { 0 => NonNarrowChar::ZeroWidth(pos), 2 => NonNarrowChar::Wide(pos), 4 => NonNarrowChar::Tab(pos), - _ => panic!("width {} given for non-narrow character", width), + _ => panic!("width {width} given for non-narrow character"), } } diff --git a/compiler/rustc_span/src/profiling.rs b/compiler/rustc_span/src/profiling.rs index f169007fab43d..0ab890b9f0121 100644 --- a/compiler/rustc_span/src/profiling.rs +++ b/compiler/rustc_span/src/profiling.rs @@ -27,7 +27,7 @@ impl SpannedEventArgRecorder for EventArgRecorder<'_> { if let Some(source_map) = &*session_globals.source_map.borrow() { source_map.span_to_embeddable_string(span) } else { - format!("{:?}", span) + format!("{span:?}") } }); self.record_arg(span_arg); diff --git a/compiler/rustc_span/src/source_map/tests.rs b/compiler/rustc_span/src/source_map/tests.rs index 3058ec45a6468..fcdef6e8f330b 100644 --- a/compiler/rustc_span/src/source_map/tests.rs +++ b/compiler/rustc_span/src/source_map/tests.rs @@ -286,8 +286,8 @@ impl SourceMapExtension for SourceMap { n: usize, ) -> Span { eprintln!( - "span_substr(file={:?}/{:?}, substring={:?}, n={})", - file.name, file.start_pos, substring, n + "span_substr(file={:?}/{:?}, substring={substring:?}, n={n})", + file.name, file.start_pos ); let mut i = 0; let mut hi = 0; diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index d2fb8c32ffd27..4ec02ca3eaede 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -175,12 +175,12 @@ impl Reg { 17..=32 => dl.i32_align.abi, 33..=64 => dl.i64_align.abi, 65..=128 => dl.i128_align.abi, - _ => panic!("unsupported integer: {:?}", self), + _ => panic!("unsupported integer: {self:?}"), }, RegKind::Float => match self.size.bits() { 32 => dl.f32_align.abi, 64 => dl.f64_align.abi, - _ => panic!("unsupported float: {:?}", self), + _ => panic!("unsupported float: {self:?}"), }, RegKind::Vector => dl.vector_align(self.size).abi, } @@ -640,7 +640,7 @@ impl fmt::Display for AdjustForForeignAbiError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Unsupported { arch, abi } => { - write!(f, "target architecture {:?} does not support `extern {}` ABI", arch, abi) + write!(f, "target architecture {arch:?} does not support `extern {abi}` ABI") } } } diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index 7171ca7bf8950..4537cd8c3e8e6 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -209,7 +209,7 @@ impl TargetDataLayout { 16 => 1 << 15, 32 => 1 << 31, 64 => 1 << 47, - bits => panic!("obj_size_bound: unknown pointer bit size {}", bits), + bits => panic!("obj_size_bound: unknown pointer bit size {bits}"), } } @@ -219,7 +219,7 @@ impl TargetDataLayout { 16 => I16, 32 => I32, 64 => I64, - bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits), + bits => panic!("ptr_sized_integer: unknown pointer bit size {bits}"), } } @@ -276,7 +276,7 @@ impl FromStr for Endian { match s { "little" => Ok(Self::Little), "big" => Ok(Self::Big), - _ => Err(format!(r#"unknown endian: "{}""#, s)), + _ => Err(format!(r#"unknown endian: "{s}""#)), } } } @@ -332,7 +332,7 @@ impl Size { pub fn bits(self) -> u64 { #[cold] fn overflow(bytes: u64) -> ! { - panic!("Size::bits: {} bytes in bits doesn't fit in u64", bytes) + panic!("Size::bits: {bytes} bytes in bits doesn't fit in u64") } self.bytes().checked_mul(8).unwrap_or_else(|| overflow(self.bytes())) @@ -454,7 +454,7 @@ impl Mul for Size { fn mul(self, count: u64) -> Size { match self.bytes().checked_mul(count) { Some(bytes) => Size::from_bytes(bytes), - None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count), + None => panic!("Size::mul: {} * {count} doesn't fit in u64", self.bytes()), } } } @@ -535,12 +535,12 @@ impl Align { #[cold] fn not_power_of_2(align: u64) -> String { - format!("`{}` is not a power of 2", align) + format!("`{align}` is not a power of 2") } #[cold] fn too_large(align: u64) -> String { - format!("`{}` is too large", align) + format!("`{align}` is too large") } let mut bytes = align; @@ -1091,7 +1091,7 @@ impl Abi { Primitive::Int(_, signed) => signed, _ => false, }, - _ => panic!("`is_signed` on non-scalar ABI {:?}", self), + _ => panic!("`is_signed` on non-scalar ABI {self:?}"), } } diff --git a/compiler/rustc_target/src/asm/aarch64.rs b/compiler/rustc_target/src/asm/aarch64.rs index 62a0f9fb03470..28493c7700ffc 100644 --- a/compiler/rustc_target/src/asm/aarch64.rs +++ b/compiler/rustc_target/src/asm/aarch64.rs @@ -195,6 +195,6 @@ impl AArch64InlineAsmReg { (modifier.unwrap_or('v'), self as u32 - Self::v0 as u32) }; assert!(index < 32); - write!(out, "{}{}", prefix, index) + write!(out, "{prefix}{index}") } } diff --git a/compiler/rustc_target/src/asm/arm.rs b/compiler/rustc_target/src/asm/arm.rs index 0db3eb6fcac0c..ec7429a306554 100644 --- a/compiler/rustc_target/src/asm/arm.rs +++ b/compiler/rustc_target/src/asm/arm.rs @@ -249,7 +249,7 @@ impl ArmInlineAsmReg { let index = self as u32 - Self::q0 as u32; assert!(index < 16); let index = index * 2 + (modifier == 'f') as u32; - write!(out, "d{}", index) + write!(out, "d{index}") } else { out.write_str(self.name()) } diff --git a/compiler/rustc_target/src/asm/mod.rs b/compiler/rustc_target/src/asm/mod.rs index 65d2cd64bf693..7f01f33d39c6c 100644 --- a/compiler/rustc_target/src/asm/mod.rs +++ b/compiler/rustc_target/src/asm/mod.rs @@ -679,13 +679,13 @@ impl fmt::Display for InlineAsmType { Self::I128 => f.write_str("i128"), Self::F32 => f.write_str("f32"), Self::F64 => f.write_str("f64"), - Self::VecI8(n) => write!(f, "i8x{}", n), - Self::VecI16(n) => write!(f, "i16x{}", n), - Self::VecI32(n) => write!(f, "i32x{}", n), - Self::VecI64(n) => write!(f, "i64x{}", n), - Self::VecI128(n) => write!(f, "i128x{}", n), - Self::VecF32(n) => write!(f, "f32x{}", n), - Self::VecF64(n) => write!(f, "f64x{}", n), + Self::VecI8(n) => write!(f, "i8x{n}"), + Self::VecI16(n) => write!(f, "i16x{n}"), + Self::VecI32(n) => write!(f, "i32x{n}"), + Self::VecI64(n) => write!(f, "i64x{n}"), + Self::VecI128(n) => write!(f, "i128x{n}"), + Self::VecF32(n) => write!(f, "f32x{n}"), + Self::VecF64(n) => write!(f, "f64x{n}"), } } } diff --git a/compiler/rustc_target/src/asm/x86.rs b/compiler/rustc_target/src/asm/x86.rs index 238c365093f08..5eae07f141fc0 100644 --- a/compiler/rustc_target/src/asm/x86.rs +++ b/compiler/rustc_target/src/asm/x86.rs @@ -357,28 +357,28 @@ impl X86InlineAsmReg { if self as u32 <= Self::dx as u32 { let root = ['a', 'b', 'c', 'd'][self as usize - Self::ax as usize]; match modifier.unwrap_or(reg_default_modifier) { - 'l' => write!(out, "{}l", root), - 'h' => write!(out, "{}h", root), - 'x' => write!(out, "{}x", root), - 'e' => write!(out, "e{}x", root), - 'r' => write!(out, "r{}x", root), + 'l' => write!(out, "{root}l"), + 'h' => write!(out, "{root}h"), + 'x' => write!(out, "{root}x"), + 'e' => write!(out, "e{root}x"), + 'r' => write!(out, "r{root}x"), _ => unreachable!(), } } else if self as u32 <= Self::di as u32 { let root = self.name(); match modifier.unwrap_or(reg_default_modifier) { - 'l' => write!(out, "{}l", root), - 'x' => write!(out, "{}", root), - 'e' => write!(out, "e{}", root), - 'r' => write!(out, "r{}", root), + 'l' => write!(out, "{root}l"), + 'x' => write!(out, "{root}"), + 'e' => write!(out, "e{root}"), + 'r' => write!(out, "r{root}"), _ => unreachable!(), } } else if self as u32 <= Self::r15 as u32 { let root = self.name(); match modifier.unwrap_or(reg_default_modifier) { - 'l' => write!(out, "{}b", root), - 'x' => write!(out, "{}w", root), - 'e' => write!(out, "{}d", root), + 'l' => write!(out, "{root}b"), + 'x' => write!(out, "{root}w"), + 'e' => write!(out, "{root}d"), 'r' => out.write_str(root), _ => unreachable!(), } @@ -387,15 +387,15 @@ impl X86InlineAsmReg { } else if self as u32 <= Self::xmm15 as u32 { let prefix = modifier.unwrap_or('x'); let index = self as u32 - Self::xmm0 as u32; - write!(out, "{}{}", prefix, index) + write!(out, "{prefix}{index}") } else if self as u32 <= Self::ymm15 as u32 { let prefix = modifier.unwrap_or('y'); let index = self as u32 - Self::ymm0 as u32; - write!(out, "{}{}", prefix, index) + write!(out, "{prefix}{index}") } else if self as u32 <= Self::zmm31 as u32 { let prefix = modifier.unwrap_or('z'); let index = self as u32 - Self::zmm0 as u32; - write!(out, "{}{}", prefix, index) + write!(out, "{prefix}{index}") } else { out.write_str(self.name()) } diff --git a/compiler/rustc_target/src/spec/apple_base.rs b/compiler/rustc_target/src/spec/apple_base.rs index 40bc59ca145e5..bc72f4945d8bf 100644 --- a/compiler/rustc_target/src/spec/apple_base.rs +++ b/compiler/rustc_target/src/spec/apple_base.rs @@ -5,7 +5,7 @@ use crate::spec::{LinkerFlavor, Lld, SplitDebuginfo, StaticCow, TargetOptions}; fn pre_link_args(os: &'static str, arch: &'static str, abi: &'static str) -> LinkArgs { let platform_name: StaticCow = match abi { - "sim" => format!("{}-simulator", os).into(), + "sim" => format!("{os}-simulator").into(), "macabi" => "mac-catalyst".into(), _ => os.into(), }; @@ -114,12 +114,12 @@ fn macos_deployment_target(arch: &str) -> (u32, u32) { fn macos_lld_platform_version(arch: &str) -> String { let (major, minor) = macos_deployment_target(arch); - format!("{}.{}", major, minor) + format!("{major}.{minor}") } pub fn macos_llvm_target(arch: &str) -> String { let (major, minor) = macos_deployment_target(arch); - format!("{}-apple-macosx{}.{}.0", arch, major, minor) + format!("{arch}-apple-macosx{major}.{minor}.0") } pub fn macos_link_env_remove() -> Vec> { @@ -150,17 +150,17 @@ pub fn ios_llvm_target(arch: &str) -> String { // to pick it up (since std and core are still built with the fallback // of version 7.0 and hence emit the old LC_IPHONE_MIN_VERSION). let (major, minor) = ios_deployment_target(); - format!("{}-apple-ios{}.{}.0", arch, major, minor) + format!("{arch}-apple-ios{major}.{minor}.0") } fn ios_lld_platform_version() -> String { let (major, minor) = ios_deployment_target(); - format!("{}.{}", major, minor) + format!("{major}.{minor}") } pub fn ios_sim_llvm_target(arch: &str) -> String { let (major, minor) = ios_deployment_target(); - format!("{}-apple-ios{}.{}.0-simulator", arch, major, minor) + format!("{arch}-apple-ios{major}.{minor}.0-simulator") } fn tvos_deployment_target() -> (u32, u32) { @@ -169,7 +169,7 @@ fn tvos_deployment_target() -> (u32, u32) { fn tvos_lld_platform_version() -> String { let (major, minor) = tvos_deployment_target(); - format!("{}.{}", major, minor) + format!("{major}.{minor}") } fn watchos_deployment_target() -> (u32, u32) { @@ -178,10 +178,10 @@ fn watchos_deployment_target() -> (u32, u32) { fn watchos_lld_platform_version() -> String { let (major, minor) = watchos_deployment_target(); - format!("{}.{}", major, minor) + format!("{major}.{minor}") } pub fn watchos_sim_llvm_target(arch: &str) -> String { let (major, minor) = watchos_deployment_target(); - format!("{}-apple-watchos{}.{}.0-simulator", arch, major, minor) + format!("{arch}-apple-watchos{major}.{minor}.0-simulator") } diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 9396d769dc702..b65dbc6509978 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -839,7 +839,7 @@ impl fmt::Display for SanitizerSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut first = true; for s in *self { - let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {:?}", s)); + let name = s.as_str().unwrap_or_else(|| panic!("unrecognized sanitizer {s:?}")); if !first { f.write_str(", ")?; } @@ -2017,7 +2017,7 @@ impl Target { let mut get_req_field = |name: &str| { obj.remove(name) .and_then(|j| j.as_str().map(str::to_string)) - .ok_or_else(|| format!("Field {} in target specification is required", name)) + .ok_or_else(|| format!("Field {name} in target specification is required")) }; let mut base = Target { @@ -2410,7 +2410,7 @@ impl Target { if let Some(s) = fp.as_str() { base.frame_pointer = s .parse() - .map_err(|()| format!("'{}' is not a valid value for frame-pointer", s))?; + .map_err(|()| format!("'{s}' is not a valid value for frame-pointer"))?; } else { incorrect_type.push("frame-pointer".into()) } @@ -2599,7 +2599,7 @@ impl Target { return load_file(&p); } - Err(format!("Could not find specification for target {:?}", target_triple)) + Err(format!("Could not find specification for target {target_triple:?}")) } TargetTriple::TargetJson { ref contents, .. } => { let obj = serde_json::from_str(contents).map_err(|e| e.to_string())?; @@ -2860,7 +2860,7 @@ impl TargetTriple { let contents = std::fs::read_to_string(&canonicalized_path).map_err(|err| { io::Error::new( io::ErrorKind::InvalidInput, - format!("target path {:?} is not a valid file: {}", canonicalized_path, err), + format!("target path {canonicalized_path:?} is not a valid file: {err}"), ) })?; let triple = canonicalized_path @@ -2895,7 +2895,7 @@ impl TargetTriple { let mut hasher = DefaultHasher::new(); content.hash(&mut hasher); let hash = hasher.finish(); - format!("{}-{}", triple, hash) + format!("{triple}-{hash}") } } } diff --git a/compiler/rustc_target/src/spec/solid_base.rs b/compiler/rustc_target/src/spec/solid_base.rs index c585a6cd58ea2..eaf72b7616c71 100644 --- a/compiler/rustc_target/src/spec/solid_base.rs +++ b/compiler/rustc_target/src/spec/solid_base.rs @@ -3,7 +3,7 @@ use crate::spec::TargetOptions; pub fn opts(kernel: &str) -> TargetOptions { TargetOptions { - os: format!("solid_{}", kernel).into(), + os: format!("solid_{kernel}").into(), vendor: "kmc".into(), executables: false, frame_pointer: FramePointer::NonLeaf, diff --git a/compiler/rustc_transmute/src/layout/mod.rs b/compiler/rustc_transmute/src/layout/mod.rs index 07035ebdfb167..f8d05bc89d26d 100644 --- a/compiler/rustc_transmute/src/layout/mod.rs +++ b/compiler/rustc_transmute/src/layout/mod.rs @@ -24,7 +24,7 @@ impl fmt::Debug for Byte { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self { Self::Uninit => f.write_str("??u8"), - Self::Init(b) => write!(f, "{:#04x}u8", b), + Self::Init(b) => write!(f, "{b:#04x}u8"), } } } diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index da30344ef7ec0..197f578701d6d 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -717,9 +717,9 @@ impl fmt::Debug for InferTy { TyVar(ref v) => v.fmt(f), IntVar(ref v) => v.fmt(f), FloatVar(ref v) => v.fmt(f), - FreshTy(v) => write!(f, "FreshTy({:?})", v), - FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v), - FreshFloatTy(v) => write!(f, "FreshFloatTy({:?})", v), + FreshTy(v) => write!(f, "FreshTy({v:?})"), + FreshIntTy(v) => write!(f, "FreshIntTy({v:?})"), + FreshFloatTy(v) => write!(f, "FreshFloatTy({v:?})"), } } } @@ -742,9 +742,9 @@ impl fmt::Display for InferTy { TyVar(_) => write!(f, "_"), IntVar(_) => write!(f, "{}", "{integer}"), FloatVar(_) => write!(f, "{}", "{float}"), - FreshTy(v) => write!(f, "FreshTy({})", v), - FreshIntTy(v) => write!(f, "FreshIntTy({})", v), - FreshFloatTy(v) => write!(f, "FreshFloatTy({})", v), + FreshTy(v) => write!(f, "FreshTy({v})"), + FreshIntTy(v) => write!(f, "FreshIntTy({v})"), + FreshFloatTy(v) => write!(f, "FreshFloatTy({v})"), } } } diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 6d54924e515fc..aecec208fb605 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -1217,10 +1217,10 @@ impl hash::Hash for RegionKind { impl fmt::Debug for RegionKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ReEarlyBound(ref data) => write!(f, "ReEarlyBound({:?})", data), + ReEarlyBound(ref data) => write!(f, "ReEarlyBound({data:?})"), ReLateBound(binder_id, ref bound_region) => { - write!(f, "ReLateBound({:?}, {:?})", binder_id, bound_region) + write!(f, "ReLateBound({binder_id:?}, {bound_region:?})") } ReFree(ref fr) => fr.fmt(f), @@ -1229,7 +1229,7 @@ impl fmt::Debug for RegionKind { ReVar(ref vid) => vid.fmt(f), - RePlaceholder(placeholder) => write!(f, "RePlaceholder({:?})", placeholder), + RePlaceholder(placeholder) => write!(f, "RePlaceholder({placeholder:?})"), ReErased => write!(f, "ReErased"), } diff --git a/library/core/src/panic/panic_info.rs b/library/core/src/panic/panic_info.rs index 1923155ebc15f..73a2170bc5921 100644 --- a/library/core/src/panic/panic_info.rs +++ b/library/core/src/panic/panic_info.rs @@ -152,9 +152,9 @@ impl fmt::Display for PanicInfo<'_> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("panicked at ")?; if let Some(message) = self.message { - write!(formatter, "'{}', ", message)? + write!(formatter, "'{message}', ")? } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() { - write!(formatter, "'{}', ", payload)? + write!(formatter, "'{payload}', ")? } // NOTE: we cannot use downcast_ref::() here // since String is not available in libcore! diff --git a/library/core/src/str/lossy.rs b/library/core/src/str/lossy.rs index 59f873d1268ce..b9b24b3865046 100644 --- a/library/core/src/str/lossy.rs +++ b/library/core/src/str/lossy.rs @@ -100,7 +100,7 @@ impl fmt::Debug for Debug<'_> { // Broken parts of string as hex escape. for &b in chunk.invalid() { - write!(f, "\\x{:02X}", b)?; + write!(f, "\\x{b:02X}")?; } } diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 1d0c51c3c8368..c543288372acd 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -1121,10 +1121,10 @@ impl fmt::Debug for Duration { // padding (padding is calculated below). let emit_without_padding = |f: &mut fmt::Formatter<'_>| { if let Some(integer_part) = integer_part { - write!(f, "{}{}", prefix, integer_part)?; + write!(f, "{prefix}{integer_part}")?; } else { // u64::MAX + 1 == 18446744073709551616 - write!(f, "{}18446744073709551616", prefix)?; + write!(f, "{prefix}18446744073709551616")?; } // Write the decimal point and the fractional part (if any). @@ -1135,10 +1135,10 @@ impl fmt::Debug for Duration { // If the user request a precision > 9, we pad '0's at the end. let w = f.precision().unwrap_or(pos); - write!(f, ".{:0 core::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/library/test/src/formatters/json.rs b/library/test/src/formatters/json.rs index c07fdafb167c9..eae57b3f64433 100644 --- a/library/test/src/formatters/json.rs +++ b/library/test/src/formatters/json.rs @@ -53,7 +53,7 @@ impl JsonFormatter { self.write_message(&*format!(r#", "stdout": "{}""#, EscapedString(stdout)))?; } if let Some(extra) = extra { - self.write_message(&*format!(r#", {}"#, extra))?; + self.write_message(&*format!(r#", {extra}"#))?; } self.writeln_message(" }") } @@ -62,7 +62,7 @@ impl JsonFormatter { impl OutputFormatter for JsonFormatter { fn write_run_start(&mut self, test_count: usize, shuffle_seed: Option) -> io::Result<()> { let shuffle_seed_json = if let Some(shuffle_seed) = shuffle_seed { - format!(r#", "shuffle_seed": {}"#, shuffle_seed) + format!(r#", "shuffle_seed": {shuffle_seed}"#) } else { String::new() }; diff --git a/library/test/src/formatters/mod.rs b/library/test/src/formatters/mod.rs index cb80859759fad..cb67b6491a392 100644 --- a/library/test/src/formatters/mod.rs +++ b/library/test/src/formatters/mod.rs @@ -38,5 +38,5 @@ pub(crate) fn write_stderr_delimiter(test_output: &mut Vec, test_name: &Test Some(_) => test_output.push(b'\n'), None => (), } - writeln!(test_output, "---- {} stderr ----", test_name).unwrap(); + writeln!(test_output, "---- {test_name} stderr ----").unwrap(); } diff --git a/library/test/src/formatters/pretty.rs b/library/test/src/formatters/pretty.rs index 694202229802f..0299c8b543359 100644 --- a/library/test/src/formatters/pretty.rs +++ b/library/test/src/formatters/pretty.rs @@ -47,7 +47,7 @@ impl PrettyFormatter { pub fn write_ignored(&mut self, message: Option<&'static str>) -> io::Result<()> { if let Some(message) = message { - self.write_short_result(&format!("ignored, {}", message), term::color::YELLOW) + self.write_short_result(&format!("ignored, {message}"), term::color::YELLOW) } else { self.write_short_result("ignored", term::color::YELLOW) } diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index c30257fc79200..5949bc3d855b4 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -649,7 +649,7 @@ fn spawn_test_subprocess( let output = match command.output() { Ok(out) => out, Err(e) => { - let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e); + let err = format!("Failed to spawn {} as child for test: {e:?}", args[0]); return (TrFailed, err.into_bytes(), None); } }; @@ -669,7 +669,7 @@ fn spawn_test_subprocess( })() { Ok(r) => r, Err(e) => { - write!(&mut test_output, "Unexpected error: {}", e).unwrap(); + write!(&mut test_output, "Unexpected error: {e}").unwrap(); TrFailed } }; diff --git a/src/bootstrap/bin/main.rs b/src/bootstrap/bin/main.rs index 9b4861ccd95f4..beeae63120ca0 100644 --- a/src/bootstrap/bin/main.rs +++ b/src/bootstrap/bin/main.rs @@ -43,7 +43,7 @@ fn main() { `cp config.toml.example config.toml`" ); } else if let Some(suggestion) = &changelog_suggestion { - println!("{}", suggestion); + println!("{suggestion}"); } let pre_commit = config.src.join(".git").join("hooks").join("pre-commit"); @@ -56,7 +56,7 @@ fn main() { `cp config.toml.example config.toml`" ); } else if let Some(suggestion) = &changelog_suggestion { - println!("{}", suggestion); + println!("{suggestion}"); } // Give a warning if the pre-commit script is in pre-commit and not pre-push. @@ -83,13 +83,13 @@ fn check_version(config: &Config) -> Option { let suggestion = if let Some(seen) = config.changelog_seen { if seen != VERSION { msg.push_str("warning: there have been changes to x.py since you last updated.\n"); - format!("update `config.toml` to use `changelog-seen = {}` instead", VERSION) + format!("update `config.toml` to use `changelog-seen = {VERSION}` instead") } else { return None; } } else { msg.push_str("warning: x.py has made several changes recently you may want to look at\n"); - format!("add `changelog-seen = {}` at the top of `config.toml`", VERSION) + format!("add `changelog-seen = {VERSION}` at the top of `config.toml`") }; msg.push_str("help: consider looking at the changes in `src/bootstrap/CHANGELOG.md`\n"); diff --git a/src/bootstrap/bin/rustc.rs b/src/bootstrap/bin/rustc.rs index 776d73b98c4f1..3f74df1b538f5 100644 --- a/src/bootstrap/bin/rustc.rs +++ b/src/bootstrap/bin/rustc.rs @@ -51,8 +51,8 @@ fn main() { let sysroot = env::var_os("RUSTC_SYSROOT").expect("RUSTC_SYSROOT was not set"); let on_fail = env::var_os("RUSTC_ON_FAIL").map(Command::new); - let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{:?} was not set", rustc)); - let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{:?} was not set", libdir)); + let rustc = env::var_os(rustc).unwrap_or_else(|| panic!("{rustc:?} was not set")); + let libdir = env::var_os(libdir).unwrap_or_else(|| panic!("{libdir:?} was not set")); let mut dylib_path = dylib_path(); dylib_path.insert(0, PathBuf::from(&libdir)); @@ -121,7 +121,7 @@ fn main() { // Override linker if necessary. if let Ok(host_linker) = env::var("RUSTC_HOST_LINKER") { - cmd.arg(format!("-Clinker={}", host_linker)); + cmd.arg(format!("-Clinker={host_linker}")); } if env::var_os("RUSTC_HOST_FUSE_LD_LLD").is_some() { cmd.arg("-Clink-args=-fuse-ld=lld"); @@ -172,13 +172,13 @@ fn main() { env::vars().filter(|(k, _)| k.starts_with("RUST") || k.starts_with("CARGO")); let prefix = if is_test { "[RUSTC-SHIM] rustc --test" } else { "[RUSTC-SHIM] rustc" }; let prefix = match crate_name { - Some(crate_name) => format!("{} {}", prefix, crate_name), + Some(crate_name) => format!("{prefix} {crate_name}"), None => prefix.to_string(), }; for (i, (k, v)) in rust_env_vars.enumerate() { - eprintln!("{} env[{}]: {:?}={:?}", prefix, i, k, v); + eprintln!("{prefix} env[{i}]: {k:?}={v:?}"); } - eprintln!("{} working directory: {}", prefix, env::current_dir().unwrap().display()); + eprintln!("{prefix} working directory: {}", env::current_dir().unwrap().display()); eprintln!( "{} command: {:?}={:?} {:?}", prefix, @@ -186,13 +186,13 @@ fn main() { env::join_paths(&dylib_path).unwrap(), cmd, ); - eprintln!("{} sysroot: {:?}", prefix, sysroot); - eprintln!("{} libdir: {:?}", prefix, libdir); + eprintln!("{prefix} sysroot: {sysroot:?}"); + eprintln!("{prefix} libdir: {libdir:?}"); } let start = Instant::now(); let (child, status) = { - let errmsg = format!("\nFailed to run:\n{:?}\n-------------", cmd); + let errmsg = format!("\nFailed to run:\n{cmd:?}\n-------------"); let mut child = cmd.spawn().expect(&errmsg); let status = child.wait().expect(&errmsg); (child, status) @@ -225,7 +225,7 @@ fn main() { // should run on success, after this block. } if verbose > 0 { - println!("\nDid not run successfully: {}\n{:?}\n-------------", status, cmd); + println!("\nDid not run successfully: {status}\n{cmd:?}\n-------------"); } if let Some(mut on_fail) = on_fail { @@ -237,7 +237,7 @@ fn main() { match status.code() { Some(i) => std::process::exit(i), None => { - eprintln!("rustc exited with {}", status); + eprintln!("rustc exited with {status}"); std::process::exit(0xfe); } } @@ -354,13 +354,13 @@ fn format_rusage_data(_child: Child) -> Option { let minflt = rusage.ru_minflt; let majflt = rusage.ru_majflt; if minflt != 0 || majflt != 0 { - init_str.push_str(&format!(" page reclaims: {} page faults: {}", minflt, majflt)); + init_str.push_str(&format!(" page reclaims: {minflt} page faults: {majflt}")); } let inblock = rusage.ru_inblock; let oublock = rusage.ru_oublock; if inblock != 0 || oublock != 0 { - init_str.push_str(&format!(" fs block inputs: {} fs block outputs: {}", inblock, oublock)); + init_str.push_str(&format!(" fs block inputs: {inblock} fs block outputs: {oublock}")); } let nvcsw = rusage.ru_nvcsw; diff --git a/src/bootstrap/bin/rustdoc.rs b/src/bootstrap/bin/rustdoc.rs index e69cab956c507..5a0efd61175ec 100644 --- a/src/bootstrap/bin/rustdoc.rs +++ b/src/bootstrap/bin/rustdoc.rs @@ -81,12 +81,12 @@ fn main() { env::join_paths(&dylib_path).unwrap(), cmd, ); - eprintln!("sysroot: {:?}", sysroot); - eprintln!("libdir: {:?}", libdir); + eprintln!("sysroot: {sysroot:?}"); + eprintln!("libdir: {libdir:?}"); } std::process::exit(match cmd.status() { Ok(s) => s.code().unwrap_or(1), - Err(e) => panic!("\n\nfailed to run {:?}: {}\n\n", cmd, e), + Err(e) => panic!("\n\nfailed to run {cmd:?}: {e}\n\n"), }) } diff --git a/src/bootstrap/build.rs b/src/bootstrap/build.rs index cd1f418028c62..e0e32d3135354 100644 --- a/src/bootstrap/build.rs +++ b/src/bootstrap/build.rs @@ -3,5 +3,5 @@ use std::env; fn main() { let host = env::var("HOST").unwrap(); println!("cargo:rerun-if-changed=build.rs"); - println!("cargo:rustc-env=BUILD_TRIPLE={}", host); + println!("cargo:rustc-env=BUILD_TRIPLE={host}"); } diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index 415774d7255d7..b47a7e341d106 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -273,7 +273,7 @@ impl StepDescription { fn is_excluded(&self, builder: &Builder<'_>, pathset: &PathSet) -> bool { if builder.config.exclude.iter().any(|e| pathset.has(&e.path, e.kind)) { - println!("Skipping {:?} because it is excluded", pathset); + println!("Skipping {pathset:?} because it is excluded"); return true; } @@ -338,7 +338,7 @@ impl StepDescription { } if !paths.is_empty() { - eprintln!("error: no `{}` rules matched {:?}", builder.kind.as_str(), paths,); + eprintln!("error: no `{}` rules matched {paths:?}", builder.kind.as_str(),); eprintln!( "help: run `x.py {} --help --verbose` to show a list of available paths", builder.kind.as_str() @@ -883,7 +883,7 @@ impl<'a> Builder<'a> { const NIX_IDS: &[&str] = &["ID=nixos", "ID='nixos'", "ID=\"nixos\""]; let os_release = match File::open("/etc/os-release") { Err(e) if e.kind() == ErrorKind::NotFound => return, - Err(e) => panic!("failed to access /etc/os-release: {}", e), + Err(e) => panic!("failed to access /etc/os-release: {e}"), Ok(f) => f, }; if !BufReader::new(os_release).lines().any(|l| NIX_IDS.contains(&t!(l).trim())) { @@ -976,7 +976,7 @@ impl<'a> Builder<'a> { } fn download_http_with_retries(&self, tempfile: &Path, url: &str, help_on_error: &str) { - println!("downloading {}", url); + println!("downloading {url}"); // Try curl. If that fails and we are on windows, fallback to PowerShell. let mut curl = Command::new("curl"); curl.args(&[ @@ -1013,7 +1013,7 @@ impl<'a> Builder<'a> { } } if !help_on_error.is_empty() { - eprintln!("{}", help_on_error); + eprintln!("{help_on_error}"); } crate::detail_exit(1); } @@ -1342,7 +1342,7 @@ impl<'a> Builder<'a> { // This is the intended out directory for compiler documentation. Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target), Mode::Std => out_dir.join(target.triple).join("doc"), - _ => panic!("doc mode {:?} not expected", mode), + _ => panic!("doc mode {mode:?} not expected"), }; let rustdoc = self.rustdoc(compiler); self.clear_if_dirty(&my_out, &rustdoc); @@ -1352,7 +1352,7 @@ impl<'a> Builder<'a> { let profile_var = |name: &str| { let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" }; - format!("CARGO_PROFILE_{}_{}", profile, name) + format!("CARGO_PROFILE_{profile}_{name}") }; // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config @@ -1715,7 +1715,7 @@ impl<'a> Builder<'a> { None }; if let Some(rpath) = rpath { - rustflags.arg(&format!("-Clink-args={}", rpath)); + rustflags.arg(&format!("-Clink-args={rpath}")); } } @@ -1729,7 +1729,7 @@ impl<'a> Builder<'a> { if let Some(target_linker) = self.linker(target) { let target = crate::envify(&target.triple); - cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker); + cargo.env(&format!("CARGO_TARGET_{target}_LINKER"), target_linker); } if self.is_fuse_ld_lld(target) { rustflags.arg("-Clink-args=-fuse-ld=lld"); @@ -1805,7 +1805,7 @@ impl<'a> Builder<'a> { } if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) { - let map = format!("{}={}", self.build.src.display(), map_to); + let map = format!("{}={map_to}", self.build.src.display()); cargo.env("RUSTC_DEBUGINFO_MAP", map); // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to, @@ -1940,30 +1940,30 @@ impl<'a> Builder<'a> { // accept a new env var or otherwise work with custom ccache // vars. match &ccache[..] { - "ccache" | "sccache" => format!("{} {}", ccache, s.display()), + "ccache" | "sccache" => format!("{ccache} {}", s.display()), _ => s.display().to_string(), } }; let triple_underscored = target.triple.replace("-", "_"); let cc = ccacheify(&self.cc(target)); - cargo.env(format!("CC_{}", triple_underscored), &cc); + cargo.env(format!("CC_{triple_underscored}"), &cc); let cflags = self.cflags(target, GitRepo::Rustc, CLang::C).join(" "); - cargo.env(format!("CFLAGS_{}", triple_underscored), &cflags); + cargo.env(format!("CFLAGS_{triple_underscored}"), &cflags); if let Some(ar) = self.ar(target) { let ranlib = format!("{} s", ar.display()); cargo - .env(format!("AR_{}", triple_underscored), ar) - .env(format!("RANLIB_{}", triple_underscored), ranlib); + .env(format!("AR_{triple_underscored}"), ar) + .env(format!("RANLIB_{triple_underscored}"), ranlib); } if let Ok(cxx) = self.cxx(target) { let cxx = ccacheify(&cxx); let cxxflags = self.cflags(target, GitRepo::Rustc, CLang::Cxx).join(" "); cargo - .env(format!("CXX_{}", triple_underscored), &cxx) - .env(format!("CXXFLAGS_{}", triple_underscored), cxxflags); + .env(format!("CXX_{triple_underscored}"), &cxx) + .env(format!("CXXFLAGS_{triple_underscored}"), cxxflags); } } @@ -2091,7 +2091,7 @@ impl<'a> Builder<'a> { }; if let Some(limit) = limit { - rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit)); + rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}")); } } @@ -2110,18 +2110,18 @@ impl<'a> Builder<'a> { continue; } let mut out = String::new(); - out += &format!("\n\nCycle in build detected when adding {:?}\n", step); + out += &format!("\n\nCycle in build detected when adding {step:?}\n"); for el in stack.iter().rev() { - out += &format!("\t{:?}\n", el); + out += &format!("\t{el:?}\n"); } panic!("{}", out); } if let Some(out) = self.cache.get(&step) { - self.verbose_than(1, &format!("{}c {:?}", " ".repeat(stack.len()), step)); + self.verbose_than(1, &format!("{}c {step:?}", " ".repeat(stack.len()))); return out; } - self.verbose_than(1, &format!("{}> {:?}", " ".repeat(stack.len()), step)); + self.verbose_than(1, &format!("{}> {step:?}", " ".repeat(stack.len()))); stack.push(Box::new(step.clone())); } @@ -2139,7 +2139,7 @@ impl<'a> Builder<'a> { }; if self.config.print_step_timings && !self.config.dry_run { - let step_string = format!("{:?}", step); + let step_string = format!("{step:?}"); let brace_index = step_string.find("{").unwrap_or(0); let type_string = type_name::(); println!( @@ -2159,7 +2159,7 @@ impl<'a> Builder<'a> { let cur_step = stack.pop().expect("step stack empty"); assert_eq!(cur_step.downcast_ref(), Some(&step)); } - self.verbose_than(1, &format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step)); + self.verbose_than(1, &format!("{}< {step:?}", " ".repeat(self.stack.borrow().len()))); self.cache.put(step, out.clone()); out } @@ -2229,7 +2229,7 @@ impl Rustflags { self.env(prefix); // ... and also handle target-specific env RUSTFLAGS if they're configured. - let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix); + let target_specific = format!("CARGO_TARGET_{}_{prefix}", crate::envify(&self.1.triple)); self.env(&target_specific); } diff --git a/src/bootstrap/cache.rs b/src/bootstrap/cache.rs index be5c9bb078808..62fcba80ded64 100644 --- a/src/bootstrap/cache.rs +++ b/src/bootstrap/cache.rs @@ -76,7 +76,7 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s: &U = &*self; - f.write_fmt(format_args!("{:?}", s)) + f.write_fmt(format_args!("{s:?}")) } } @@ -237,7 +237,7 @@ impl Cache { .or_insert_with(|| Box::new(HashMap::::new())) .downcast_mut::>() .expect("invalid type mapped"); - assert!(!stepcache.contains_key(&step), "processing {:?} a second time", step); + assert!(!stepcache.contains_key(&step), "processing {step:?} a second time"); stepcache.insert(step, value); } diff --git a/src/bootstrap/cc_detect.rs b/src/bootstrap/cc_detect.rs index 759a99c330c27..63cef7078991e 100644 --- a/src/bootstrap/cc_detect.rs +++ b/src/bootstrap/cc_detect.rs @@ -136,14 +136,14 @@ pub fn find(build: &mut Build) { } build.verbose(&format!("CC_{} = {:?}", &target.triple, build.cc(target))); - build.verbose(&format!("CFLAGS_{} = {:?}", &target.triple, cflags)); + build.verbose(&format!("CFLAGS_{} = {cflags:?}", &target.triple)); if let Ok(cxx) = build.cxx(target) { let cxxflags = build.cflags(target, GitRepo::Rustc, CLang::Cxx); - build.verbose(&format!("CXX_{} = {:?}", &target.triple, cxx)); - build.verbose(&format!("CXXFLAGS_{} = {:?}", &target.triple, cxxflags)); + build.verbose(&format!("CXX_{} = {cxx:?}", &target.triple)); + build.verbose(&format!("CXXFLAGS_{} = {cxxflags:?}", &target.triple)); } if let Some(ar) = ar { - build.verbose(&format!("AR_{} = {:?}", &target.triple, ar)); + build.verbose(&format!("AR_{} = {ar:?}", &target.triple)); build.ar.insert(target, ar); } @@ -172,7 +172,7 @@ fn set_compiler( .replace("armv7", "arm") .replace("thumbv7neon", "arm") .replace("thumbv7", "arm"); - let compiler = format!("{}-{}", target, compiler.clang()); + let compiler = format!("{target}-{}", compiler.clang()); cfg.compiler(ndk.join("bin").join(compiler)); } } @@ -195,7 +195,7 @@ fn set_compiler( '0'..='6' => {} _ => return, } - let alternative = format!("e{}", gnu_compiler); + let alternative = format!("e{gnu_compiler}"); if Command::new(&alternative).output().is_ok() { cfg.compiler(alternative); } diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index 229851238f1d0..785f12d644b50 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -51,12 +51,12 @@ fn args(builder: &Builder<'_>) -> Vec { ])); } args.extend(strings(&["--", "--cap-lints", "warn"])); - args.extend(ignored_lints.iter().map(|lint| format!("-Aclippy::{}", lint))); + args.extend(ignored_lints.iter().map(|lint| format!("-Aclippy::{lint}"))); let mut clippy_lint_levels: Vec = Vec::new(); - clippy_lint_allow.iter().for_each(|v| clippy_lint_levels.push(format!("-A{}", v))); - clippy_lint_deny.iter().for_each(|v| clippy_lint_levels.push(format!("-D{}", v))); - clippy_lint_warn.iter().for_each(|v| clippy_lint_levels.push(format!("-W{}", v))); - clippy_lint_forbid.iter().for_each(|v| clippy_lint_levels.push(format!("-F{}", v))); + clippy_lint_allow.iter().for_each(|v| clippy_lint_levels.push(format!("-A{v}"))); + clippy_lint_deny.iter().for_each(|v| clippy_lint_levels.push(format!("-D{v}"))); + clippy_lint_warn.iter().for_each(|v| clippy_lint_levels.push(format!("-W{v}"))); + clippy_lint_forbid.iter().for_each(|v| clippy_lint_levels.push(format!("-F{v}"))); args.extend(clippy_lint_levels); args } else { @@ -101,8 +101,8 @@ impl Step for Std { std_cargo(builder, target, compiler.stage, &mut cargo); builder.info(&format!( - "Checking stage{} std artifacts ({} -> {})", - builder.top_stage, &compiler.host, target + "Checking stage{} std artifacts ({} -> {target})", + builder.top_stage, &compiler.host )); run_cargo( builder, @@ -157,8 +157,8 @@ impl Step for Std { } builder.info(&format!( - "Checking stage{} std test/bench/example targets ({} -> {})", - builder.top_stage, &compiler.host, target + "Checking stage{} std test/bench/example targets ({} -> {target})", + builder.top_stage, &compiler.host )); run_cargo( builder, @@ -233,8 +233,8 @@ impl Step for Rustc { } builder.info(&format!( - "Checking stage{} compiler artifacts ({} -> {})", - builder.top_stage, &compiler.host, target + "Checking stage{} compiler artifacts ({} -> {target})", + builder.top_stage, &compiler.host )); run_cargo( builder, @@ -288,12 +288,12 @@ impl Step for CodegenBackend { ); cargo .arg("--manifest-path") - .arg(builder.src.join(format!("compiler/rustc_codegen_{}/Cargo.toml", backend))); + .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); rustc_cargo_env(builder, &mut cargo, target); builder.info(&format!( - "Checking stage{} {} artifacts ({} -> {})", - builder.top_stage, backend, &compiler.host.triple, target.triple + "Checking stage{} {backend} artifacts ({} -> {})", + builder.top_stage, &compiler.host.triple, target.triple )); run_cargo( @@ -496,5 +496,5 @@ fn codegen_backend_stamp( ) -> PathBuf { builder .cargo_out(compiler, Mode::Codegen, target) - .join(format!(".librustc_codegen_{}-check.stamp", backend)) + .join(format!(".librustc_codegen_{backend}-check.stamp")) } diff --git a/src/bootstrap/clean.rs b/src/bootstrap/clean.rs index 069f3d6acf158..1e81d4c4ff8e6 100644 --- a/src/bootstrap/clean.rs +++ b/src/bootstrap/clean.rs @@ -46,7 +46,7 @@ fn rm_rf(path: &Path) { if e.kind() == ErrorKind::NotFound { return; } - panic!("failed to get metadata for file {}: {}", path.display(), e); + panic!("failed to get metadata for file {}: {e}", path.display()); } Ok(metadata) => { if metadata.file_type().is_file() || metadata.file_type().is_symlink() { @@ -108,11 +108,11 @@ where if m.file_type().is_symlink() && path.is_dir() && fs::remove_dir(path).is_ok() { return; } - panic!("failed to {} {}: {}", desc, path.display(), e); + panic!("failed to {desc} {}: {e}", path.display()); }); } Err(e) => { - panic!("failed to {} {}: {}", desc, path.display(), e); + panic!("failed to {desc} {}: {e}", path.display()); } } } diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index 4967bf50b48a1..a8426fa1f33f9 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -121,7 +121,7 @@ impl Step for Std { let compiler_to_use = builder.compiler_for(compiler.stage, compiler.host, target); if compiler_to_use != compiler { builder.ensure(Std::new(compiler_to_use, target)); - builder.info(&format!("Uplifting stage1 std ({} -> {})", compiler_to_use.host, target)); + builder.info(&format!("Uplifting stage1 std ({} -> {target})", compiler_to_use.host)); // Even if we're not building std this stage, the new sysroot must // still contain the third party objects needed by various targets. @@ -139,8 +139,8 @@ impl Step for Std { std_cargo(builder, target, compiler.stage, &mut cargo); builder.info(&format!( - "Building stage{} std artifacts ({} -> {})", - compiler.stage, &compiler.host, target + "Building stage{} std artifacts ({} -> {target})", + compiler.stage, &compiler.host )); run_cargo( builder, @@ -435,8 +435,8 @@ impl Step for StdLink { let target_compiler = self.target_compiler; let target = self.target; builder.info(&format!( - "Copying stage{} std from stage{} ({} -> {} / {})", - target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target + "Copying stage{} std from stage{} ({} -> {} / {target})", + target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host )); let libdir = builder.sysroot_libdir(target_compiler, target); let hostdir = builder.sysroot_libdir(target_compiler, compiler.host); @@ -641,7 +641,7 @@ impl Step for Rustc { if compiler_to_use != compiler { builder.ensure(Rustc::new(compiler_to_use, target)); builder - .info(&format!("Uplifting stage1 rustc ({} -> {})", builder.config.build, target)); + .info(&format!("Uplifting stage1 rustc ({} -> {target})", builder.config.build)); builder.ensure(RustcLink::from_rustc(self, compiler_to_use)); return; } @@ -674,7 +674,7 @@ impl Step for Rustc { let is_collecting = if let Some(path) = &builder.config.rust_profile_generate { if compiler.stage == 1 { - cargo.rustflag(&format!("-Cprofile-generate={}", path)); + cargo.rustflag(&format!("-Cprofile-generate={path}")); // Apparently necessary to avoid overflowing the counters during // a Cargo build profile cargo.rustflag("-Cllvm-args=-vp-counters-per-site=4"); @@ -684,7 +684,7 @@ impl Step for Rustc { } } else if let Some(path) = &builder.config.rust_profile_use { if compiler.stage == 1 { - cargo.rustflag(&format!("-Cprofile-use={}", path)); + cargo.rustflag(&format!("-Cprofile-use={path}")); cargo.rustflag("-Cllvm-args=-pgo-warn-missing-function"); true } else { @@ -702,8 +702,8 @@ impl Step for Rustc { } builder.info(&format!( - "Building stage{} compiler artifacts ({} -> {})", - compiler.stage, &compiler.host, target + "Building stage{} compiler artifacts ({} -> {target})", + compiler.stage, &compiler.host )); run_cargo( builder, @@ -888,8 +888,8 @@ impl Step for RustcLink { let target_compiler = self.target_compiler; let target = self.target; builder.info(&format!( - "Copying stage{} rustc from stage{} ({} -> {} / {})", - target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host, target + "Copying stage{} rustc from stage{} ({} -> {} / {target})", + target_compiler.stage, compiler.stage, &compiler.host, target_compiler.host )); add_to_sysroot( builder, @@ -959,14 +959,14 @@ impl Step for CodegenBackend { let mut cargo = builder.cargo(compiler, Mode::Codegen, SourceType::InTree, target, "build"); cargo .arg("--manifest-path") - .arg(builder.src.join(format!("compiler/rustc_codegen_{}/Cargo.toml", backend))); + .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); rustc_cargo_env(builder, &mut cargo, target); let tmp_stamp = out_dir.join(".tmp.stamp"); builder.info(&format!( - "Building stage{} codegen backend {} ({} -> {})", - compiler.stage, backend, &compiler.host, target + "Building stage{} codegen backend {backend} ({} -> {target})", + compiler.stage, &compiler.host )); let files = run_cargo(builder, cargo, vec![], &tmp_stamp, vec![], false); if builder.config.dry_run { @@ -1067,7 +1067,7 @@ fn codegen_backend_stamp( ) -> PathBuf { builder .cargo_out(compiler, Mode::Codegen, target) - .join(format!(".librustc_codegen_{}.stamp", backend)) + .join(format!(".librustc_codegen_{backend}.stamp")) } pub fn compiler_file( @@ -1079,7 +1079,7 @@ pub fn compiler_file( ) -> PathBuf { let mut cmd = Command::new(compiler); cmd.args(builder.cflags(target, GitRepo::Rustc, c)); - cmd.arg(format!("-print-file-name={}", file)); + cmd.arg(format!("-print-file-name={file}")); let out = output(&mut cmd); PathBuf::from(out.trim()) } @@ -1248,7 +1248,7 @@ impl Step for Assemble { let stage = target_compiler.stage; let host = target_compiler.host; - builder.info(&format!("Assembling stage{} compiler ({})", stage, host)); + builder.info(&format!("Assembling stage{stage} compiler ({host})")); // Link in all dylibs to the libdir let stamp = librustc_stamp(builder, build_compiler, target_compiler.host); @@ -1476,10 +1476,10 @@ pub fn run_cargo( }); let path_to_add = match max { Some(triple) => triple.0.to_str().unwrap(), - None => panic!("no output generated for {:?} {:?}", prefix, extension), + None => panic!("no output generated for {prefix:?} {extension:?}"), }; if is_dylib(path_to_add) { - let candidate = format!("{}.lib", path_to_add); + let candidate = format!("{path_to_add}.lib"); let candidate = PathBuf::from(candidate); if candidate.exists() { deps.push((candidate, DependencyType::Target)); @@ -1531,10 +1531,10 @@ pub fn stream_cargo( cargo.arg(arg); } - builder.verbose(&format!("running: {:?}", cargo)); + builder.verbose(&format!("running: {cargo:?}")); let mut child = match cargo.spawn() { Ok(child) => child, - Err(e) => panic!("failed to execute command: {:?}\nerror: {}", cargo, e), + Err(e) => panic!("failed to execute command: {cargo:?}\nerror: {e}"), }; // Spawn Cargo slurping up its JSON output. We'll start building up the @@ -1547,12 +1547,12 @@ pub fn stream_cargo( Ok(msg) => { if builder.config.json_output { // Forward JSON to stdout. - println!("{}", line); + println!("{line}"); } cb(msg) } // If this was informational, just print it out and continue - Err(_) => println!("{}", line), + Err(_) => println!("{line}"), } } diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 8c501f637d97e..2958531ff335d 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -272,7 +272,7 @@ impl FromStr for LlvmLibunwind { "no" => Ok(Self::No), "in-tree" => Ok(Self::InTree), "system" => Ok(Self::System), - invalid => Err(format!("Invalid value '{}' for rust.llvm-libunwind config.", invalid)), + invalid => Err(format!("Invalid value '{invalid}' for rust.llvm-libunwind config.")), } } } @@ -366,7 +366,7 @@ impl fmt::Display for TargetSelection { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.triple)?; if let Some(file) = self.file { - write!(f, "({})", file)?; + write!(f, "({file})")?; } Ok(()) } @@ -374,7 +374,7 @@ impl fmt::Display for TargetSelection { impl fmt::Debug for TargetSelection { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } @@ -865,7 +865,7 @@ impl Config { { Ok(table) => table, Err(err) => { - eprintln!("failed to parse TOML configuration '{}': {}", file.display(), err); + eprintln!("failed to parse TOML configuration '{}': {err}", file.display()); crate::detail_exit(2); } } @@ -895,7 +895,7 @@ impl Config { include_path.push("src"); include_path.push("bootstrap"); include_path.push("defaults"); - include_path.push(format!("config.{}.toml", include)); + include_path.push(format!("config.{include}.toml")); let included_toml = get_toml(&include_path); toml.merge(included_toml); } @@ -1045,7 +1045,7 @@ impl Config { config.llvm_build_config = llvm.build_config.clone().unwrap_or(Default::default()); config.llvm_from_ci = match llvm.download_ci_llvm { Some(StringOrBool::String(s)) => { - assert!(s == "if-available", "unknown option `{}` for download-ci-llvm", s); + assert!(s == "if-available", "unknown option `{s}` for download-ci-llvm"); crate::native::is_ci_llvm_available(&config, llvm_assertions.unwrap_or(false)) } Some(StringOrBool::Bool(b)) => b, @@ -1337,7 +1337,7 @@ impl Config { pub(crate) fn artifact_channel(&self, builder: &Builder<'_>, commit: &str) -> String { if builder.rust_info.is_managed_git_subrepository() { let mut channel = self.git(); - channel.arg("show").arg(format!("{}:src/ci/channel", commit)); + channel.arg("show").arg(format!("{commit}:src/ci/channel")); let channel = output(&mut channel); channel.trim().to_owned() } else if let Ok(channel) = fs::read_to_string(builder.src.join("src/ci/channel")) { @@ -1514,7 +1514,7 @@ fn download_ci_rustc_commit( Some(StringOrBool::Bool(true)) => false, Some(StringOrBool::String(s)) if s == "if-unchanged" => true, Some(StringOrBool::String(other)) => { - panic!("unrecognized option for download-rustc: {}", other) + panic!("unrecognized option for download-rustc: {other}") } }; diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 7eb8f8bbb30ed..084530c212a76 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -25,7 +25,7 @@ use crate::util::{exe, is_dylib, output, t, timeit}; use crate::{Compiler, DependencyType, Mode, LLVM_TOOLS}; pub fn pkgname(builder: &Builder<'_>, component: &str) -> String { - format!("{}-{}", component, builder.rust_package_vers()) + format!("{component}-{}", builder.rust_package_vers()) } pub(crate) fn distdir(builder: &Builder<'_>) -> PathBuf { @@ -148,7 +148,7 @@ fn find_files(files: &[&str], path: &[PathBuf]) -> Vec { if let Some(file_path) = file_path { found.push(file_path); } else { - panic!("Could not find '{}' in {:?}", file, path); + panic!("Could not find '{file}' in {path:?}"); } } @@ -1342,7 +1342,7 @@ impl Step for Extended { let stage = self.stage; let compiler = builder.compiler_for(self.stage, self.host, self.target); - builder.info(&format!("Dist extended stage{} ({})", compiler.stage, target)); + builder.info(&format!("Dist extended stage{} ({target})", compiler.stage)); let mut tarballs = Vec::new(); let mut built_tools = HashSet::new(); @@ -1408,8 +1408,8 @@ impl Step for Extended { rtf.push('}'); fn filter(contents: &str, marker: &str) -> String { - let start = format!("tool-{}-start", marker); - let end = format!("tool-{}-end", marker); + let start = format!("tool-{marker}-start"); + let end = format!("tool-{marker}-end"); let mut lines = Vec::new(); let mut omitted = false; for line in contents.lines() { @@ -1445,7 +1445,7 @@ impl Step for Extended { let pkgbuild = |component: &str| { let mut cmd = Command::new("pkgbuild"); cmd.arg("--identifier") - .arg(format!("org.rust-lang.{}", component)) + .arg(format!("org.rust-lang.{component}")) .arg("--scripts") .arg(pkg.join(component)) .arg("--nopayload") @@ -1504,7 +1504,7 @@ impl Step for Extended { let prepare = |name: &str| { builder.create_dir(&exe.join(name)); let dir = if name == "rust-std" || name == "rust-analysis" { - format!("{}-{}", name, target.triple) + format!("{name}-{}", target.triple) } else if name == "rust-analyzer" { "rust-analyzer-preview".to_string() } else if name == "clippy" { @@ -1775,7 +1775,7 @@ impl Step for Extended { builder.install(&etc.join("gfx/banner.bmp"), &exe, 0o644); builder.install(&etc.join("gfx/dialogbg.bmp"), &exe, 0o644); - builder.info(&format!("building `msi` installer with {:?}", light)); + builder.info(&format!("building `msi` installer with {light:?}")); let filename = format!("{}-{}.msi", pkgname(builder, "rust"), target.triple); let mut cmd = Command::new(&light); cmd.arg("-nologo") @@ -1879,7 +1879,7 @@ fn maybe_install_llvm(builder: &Builder<'_>, target: TargetSelection, dst_libdir } else if let Ok(llvm_config) = crate::native::prebuilt_llvm_config(builder, target) { let mut cmd = Command::new(llvm_config); cmd.arg("--libfiles"); - builder.verbose(&format!("running {:?}", cmd)); + builder.verbose(&format!("running {cmd:?}")); let files = if builder.config.dry_run { "".into() } else { output(&mut cmd) }; let build_llvm_out = &builder.llvm_out(builder.config.build); let target_llvm_out = &builder.llvm_out(target); @@ -1947,7 +1947,7 @@ impl Step for LlvmTools { /* run only if llvm-config isn't used */ if let Some(config) = builder.config.target_config.get(&target) { if let Some(ref _s) = config.llvm_config { - builder.info(&format!("Skipping LlvmTools ({}): external LLVM", target)); + builder.info(&format!("Skipping LlvmTools ({target}): external LLVM")); return None; } } @@ -2003,7 +2003,7 @@ impl Step for RustDev { /* run only if llvm-config isn't used */ if let Some(config) = builder.config.target_config.get(&target) { if let Some(ref _s) = config.llvm_config { - builder.info(&format!("Skipping RustDev ({}): external LLVM", target)); + builder.info(&format!("Skipping RustDev ({target}): external LLVM")); return None; } } diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index 819af6587484d..d650a297a71ef 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -92,7 +92,7 @@ fn open(builder: &Builder<'_>, path: impl AsRef) { let path = path.as_ref(); builder.info(&format!("Opening doc {}", path.display())); if let Err(err) = opener::open(path) { - builder.info(&format!("{}\n", err)); + builder.info(&format!("{err}\n")); } } @@ -165,7 +165,7 @@ impl Step for RustbookSrc { if builder.config.dry_run || up_to_date(&src, &index) && up_to_date(&rustbook, &index) { return; } - builder.info(&format!("Rustbook ({}) - {}", target, name)); + builder.info(&format!("Rustbook ({target}) - {name}")); let _ = fs::remove_dir_all(&out); builder.run(rustbook_cmd.arg("build").arg(&src).arg("-d").arg(out)); @@ -221,7 +221,7 @@ impl Step for TheBook { for edition in &["first-edition", "second-edition", "2018-edition"] { builder.ensure(RustbookSrc { target, - name: INTERNER.intern_string(format!("book/{}", edition)), + name: INTERNER.intern_string(format!("book/{edition}")), src: INTERNER.intern_path(builder.src.join(&relative_path).join(edition)), }); } @@ -230,7 +230,7 @@ impl Step for TheBook { builder.ensure(Standalone { compiler, target }); // build the redirect pages - builder.info(&format!("Documenting book redirect pages ({})", target)); + builder.info(&format!("Documenting book redirect pages ({target})")); for file in t!(fs::read_dir(builder.src.join(&relative_path).join("redirects"))) { let file = t!(file); let path = file.path(); @@ -320,7 +320,7 @@ impl Step for Standalone { fn run(self, builder: &Builder<'_>) { let target = self.target; let compiler = self.compiler; - builder.info(&format!("Documenting standalone ({})", target)); + builder.info(&format!("Documenting standalone ({target})")); let out = builder.doc_out(target); t!(fs::create_dir_all(&out)); @@ -660,7 +660,7 @@ impl Step for Rustc { let compiler = builder.compiler(stage, builder.config.build); builder.ensure(compile::Std::new(compiler, builder.config.build)); - builder.info(&format!("Documenting stage{} compiler ({})", stage, target)); + builder.info(&format!("Documenting stage{stage} compiler ({target})")); // This uses a shared directory so that librustdoc documentation gets // correctly built and merged with the rustc documentation. This is @@ -910,7 +910,7 @@ impl Step for UnstableBookGen { fn run(self, builder: &Builder<'_>) { let target = self.target; - builder.info(&format!("Generating unstable book md files ({})", target)); + builder.info(&format!("Generating unstable book md files ({target})")); let out = builder.md_doc_out(target).join("unstable-book"); builder.create_dir(&out); builder.remove_dir(&out); diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 802b49d748ac6..2ec41b7bb0913 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -267,7 +267,7 @@ To learn more about a subcommand, run `./x.py -h`", // No or an invalid subcommand -- show the general usage and subcommand help // An exit code will be 0 when no subcommand is given, and 1 in case of an invalid // subcommand. - println!("{}\n", subcommand_help); + println!("{subcommand_help}\n"); let exit_code = if args.is_empty() { 0 } else { 1 }; crate::detail_exit(exit_code); } @@ -350,7 +350,7 @@ To learn more about a subcommand, run `./x.py -h`", println!("{}", opts.usage(subcommand_help)); if let Some(s) = paths { if verbose { - println!("{}", s); + println!("{s}"); } else { println!( "Run `./x.py {} -h -v` to see a list of available paths.", @@ -366,7 +366,7 @@ To learn more about a subcommand, run `./x.py -h`", // Done specifying what options are possible, so do the getopts parsing let matches = opts.parse(args).unwrap_or_else(|e| { // Invalid argument/option format - println!("\n{}\n", e); + println!("\n{e}\n"); usage(1, &opts, false, &subcommand_help); }); @@ -387,7 +387,7 @@ To learn more about a subcommand, run `./x.py -h`", } } if !pass_sanity_check { - eprintln!("{}\n", subcommand_help); + eprintln!("{subcommand_help}\n"); eprintln!( "Sorry, I couldn't figure out which subcommand you were trying to specify.\n\ You may need to move some options to after the subcommand.\n" @@ -621,7 +621,7 @@ Arguments: )); profile_string.parse().unwrap_or_else(|err| { - eprintln!("error: {}", err); + eprintln!("error: {err}"); eprintln!("help: the available profiles are:"); eprint!("{}", Profile::all_for_help("- ")); crate::detail_exit(1); @@ -816,7 +816,7 @@ fn parse_deny_warnings(matches: &getopts::Matches) -> Option { Some("deny") => Some(true), Some("warn") => Some(false), Some(value) => { - eprintln!(r#"invalid value for --warnings: {:?}, expected "warn" or "deny""#, value,); + eprintln!(r#"invalid value for --warnings: {value:?}, expected "warn" or "deny""#,); crate::detail_exit(1); } None => None, diff --git a/src/bootstrap/format.rs b/src/bootstrap/format.rs index 37322670e6564..f44b3af225ab1 100644 --- a/src/bootstrap/format.rs +++ b/src/bootstrap/format.rs @@ -20,7 +20,7 @@ fn rustfmt(src: &Path, rustfmt: &Path, paths: &[PathBuf], check: bool) -> impl F cmd.arg("--check"); } cmd.args(paths); - let cmd_debug = format!("{:?}", cmd); + let cmd_debug = format!("{cmd:?}"); let mut cmd = cmd.spawn().expect("running rustfmt"); // poor man's async: return a closure that'll wait for rustfmt's completion move || { @@ -60,7 +60,7 @@ pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) { let rustfmt_config: RustfmtConfig = t!(toml::from_str(&rustfmt_config)); let mut ignore_fmt = ignore::overrides::OverrideBuilder::new(&build.src); for ignore in rustfmt_config.ignore { - ignore_fmt.add(&format!("!{}", ignore)).expect(&ignore); + ignore_fmt.add(&format!("!{ignore}")).expect(&ignore); } let git_available = match Command::new("git") .arg("--version") @@ -95,13 +95,13 @@ pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) { entry.split(' ').nth(1).expect("every git status entry should list a path") }); for untracked_path in untracked_paths { - println!("skip untracked path {} during rustfmt invocations", untracked_path); + println!("skip untracked path {untracked_path} during rustfmt invocations"); // The leading `/` makes it an exact match against the // repository root, rather than a glob. Without that, if you // have `foo.rs` in the repository root it will also match // against anything like `compiler/rustc_foo/src/foo.rs`, // preventing the latter from being formatted. - ignore_fmt.add(&format!("!/{}", untracked_path)).expect(&untracked_path); + ignore_fmt.add(&format!("!/{untracked_path}")).expect(&untracked_path); } } else { println!("Not in git tree. Skipping git-aware format checks"); diff --git a/src/bootstrap/install.rs b/src/bootstrap/install.rs index 7672b7c913594..d5fa034cc6fb1 100644 --- a/src/bootstrap/install.rs +++ b/src/bootstrap/install.rs @@ -41,7 +41,7 @@ fn sanitize_sh(path: &Path) -> String { if ch.next() != Some('/') { return None; } - Some(format!("/{}/{}", drive, &s[drive.len_utf8() + 2..])) + Some(format!("/{drive}/{}", &s[drive.len_utf8() + 2..])) } } @@ -52,7 +52,7 @@ fn install_sh( host: Option, tarball: &GeneratedTarball, ) { - builder.info(&format!("Install {} stage{} ({:?})", package, stage, host)); + builder.info(&format!("Install {package} stage{stage} ({host:?})")); let prefix = default_path(&builder.config.prefix, "/usr/local"); let sysconfdir = prefix.join(default_path(&builder.config.sysconfdir, "/etc")); diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 9ada3f315c148..626f13cbf67f1 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -542,7 +542,7 @@ impl Build { .unwrap() .trim(); if local_release.split('.').take(2).eq(version.split('.').take(2)) { - build.verbose(&format!("auto-detected local-rebuild {}", local_release)); + build.verbose(&format!("auto-detected local-rebuild {local_release}")); build.local_rebuild = true; } @@ -596,7 +596,7 @@ impl Build { let actual_hash = recorded .split_whitespace() .nth(2) - .unwrap_or_else(|| panic!("unexpected output `{}`", recorded)); + .unwrap_or_else(|| panic!("unexpected output `{recorded}`")); // update_submodule if actual_hash == checked_out_hash.trim_end() { @@ -707,7 +707,7 @@ impl Build { if failures.len() > 0 { eprintln!("\n{} command(s) did not execute successfully:\n", failures.len()); for failure in failures.iter() { - eprintln!(" - {}\n", failure); + eprintln!(" - {failure}\n"); } detail_exit(1); } @@ -806,7 +806,7 @@ impl Build { Mode::ToolBootstrap => "-bootstrap-tools", Mode::ToolStd | Mode::ToolRustc => "-tools", }; - self.out.join(&*compiler.host.triple).join(format!("stage{}{}", compiler.stage, suffix)) + self.out.join(&*compiler.host.triple).join(format!("stage{}{suffix}", compiler.stage)) } /// Returns the root output directory for all Cargo output in a given stage, @@ -949,7 +949,7 @@ impl Build { if self.config.dry_run { return; } - self.verbose(&format!("running: {:?}", cmd)); + self.verbose(&format!("running: {cmd:?}")); run(cmd, self.is_verbose()) } @@ -958,7 +958,7 @@ impl Build { if self.config.dry_run { return; } - self.verbose(&format!("running: {:?}", cmd)); + self.verbose(&format!("running: {cmd:?}")); run_suppressed(cmd) } @@ -969,7 +969,7 @@ impl Build { if self.config.dry_run { return true; } - self.verbose(&format!("running: {:?}", cmd)); + self.verbose(&format!("running: {cmd:?}")); try_run(cmd, self.is_verbose()) } @@ -980,7 +980,7 @@ impl Build { if self.config.dry_run { return true; } - self.verbose(&format!("running: {:?}", cmd)); + self.verbose(&format!("running: {cmd:?}")); try_run_suppressed(cmd) } @@ -991,7 +991,7 @@ impl Build { if self.config.dry_run { return true; } - self.verbose(&format!("running: {:?}", cmd)); + self.verbose(&format!("running: {cmd:?}")); check_run(cmd, self.is_verbose()) } @@ -1002,7 +1002,7 @@ impl Build { /// Prints a message if this build is configured in verbose mode. fn verbose(&self, msg: &str) { if self.is_verbose() { - println!("{}", msg); + println!("{msg}"); } } @@ -1013,7 +1013,7 @@ impl Build { /// Prints a message if this build is configured in more verbose mode than `level`. fn verbose_than(&self, level: usize, msg: &str) { if self.is_verbose_than(level) { - println!("{}", msg); + println!("{msg}"); } } @@ -1021,7 +1021,7 @@ impl Build { if self.config.dry_run { return; } - println!("{}", msg); + println!("{msg}"); } /// Returns the number of parallel jobs that have been configured for this @@ -1040,7 +1040,7 @@ impl Build { match which { GitRepo::Rustc => { let sha = self.rust_sha().unwrap_or(&self.version); - Some(format!("/rustc/{}", sha)) + Some(format!("/rustc/{sha}")) } GitRepo::Llvm => Some(String::from("/rustc/llvm")), } @@ -1084,13 +1084,13 @@ impl Build { } if let Some(map_to) = self.debuginfo_map_to(which) { - let map = format!("{}={}", self.src.display(), map_to); + let map = format!("{}={map_to}", self.src.display()); let cc = self.cc(target); if cc.ends_with("clang") || cc.ends_with("gcc") { - base.push(format!("-fdebug-prefix-map={}", map)); + base.push(format!("-fdebug-prefix-map={map}")); } else if cc.ends_with("clang-cl.exe") { base.push("-Xclang".into()); - base.push(format!("-fdebug-prefix-map={}", map)); + base.push(format!("-fdebug-prefix-map={map}")); } } base @@ -1111,7 +1111,7 @@ impl Build { match self.cxx.get(&target) { Some(p) => Ok(p.path()), None => { - Err(format!("target `{}` is not configured as a host, only as a target", target)) + Err(format!("target `{target}` is not configured as a host, only as a target")) } } } @@ -1152,7 +1152,7 @@ impl Build { } let threads = if target.contains("windows") { "/threads:1" } else { "--threads=1" }; - options[1] = Some(format!("-Clink-arg=-Wl,{}", threads)); + options[1] = Some(format!("-Clink-arg=-Wl,{threads}")); } IntoIterator::into_iter(options).flatten() @@ -1267,13 +1267,13 @@ impl Build { "stable" => num.to_string(), "beta" => { if self.rust_info.is_managed_git_subrepository() && !self.config.ignore_git { - format!("{}-beta.{}", num, self.beta_prerelease_version()) + format!("{num}-beta.{}", self.beta_prerelease_version()) } else { - format!("{}-beta", num) + format!("{num}-beta") } } - "nightly" => format!("{}-nightly", num), - _ => format!("{}-dev", num), + "nightly" => format!("{num}-nightly"), + _ => format!("{num}-dev"), } } @@ -1311,7 +1311,7 @@ impl Build { "stable" => num.to_string(), "beta" => "beta".to_string(), "nightly" => "nightly".to_string(), - _ => format!("{}-dev", num), + _ => format!("{num}-dev"), } } @@ -1342,7 +1342,7 @@ impl Build { /// Returns the `a.b.c` version that the given package is at. fn release_num(&self, package: &str) -> String { - let toml_file_name = self.src.join(&format!("src/tools/{}/Cargo.toml", package)); + let toml_file_name = self.src.join(&format!("src/tools/{package}/Cargo.toml")); let toml = t!(fs::read_to_string(&toml_file_name)); for line in toml.lines() { if let Some(stripped) = @@ -1352,7 +1352,7 @@ impl Build { } } - panic!("failed to find version in {}'s Cargo.toml", package) + panic!("failed to find version in {package}'s Cargo.toml") } /// Returns `true` if unstable features should be enabled for the compiler @@ -1442,7 +1442,7 @@ impl Build { if self.config.dry_run { return; } - self.verbose_than(1, &format!("Copy {:?} to {:?}", src, dst)); + self.verbose_than(1, &format!("Copy {src:?} to {dst:?}")); if src == dst { return; } @@ -1464,7 +1464,7 @@ impl Build { // just fall back to a slow `copy` operation. } else { if let Err(e) = fs::copy(&src, dst) { - panic!("failed to copy `{}` to `{}`: {}", src.display(), dst.display(), e) + panic!("failed to copy `{}` to `{}`: {e}", src.display(), dst.display()) } t!(fs::set_permissions(dst, metadata.permissions())); let atime = FileTime::from_last_access_time(&metadata); @@ -1533,7 +1533,7 @@ impl Build { return; } let dst = dstdir.join(src.file_name().unwrap()); - self.verbose_than(1, &format!("Install {:?} to {:?}", src, dst)); + self.verbose_than(1, &format!("Install {src:?} to {dst:?}")); t!(fs::create_dir_all(dstdir)); if !src.exists() { panic!("Error: File \"{}\" not found!", src.display()); @@ -1574,7 +1574,7 @@ impl Build { let iter = match fs::read_dir(dir) { Ok(v) => v, Err(_) if self.config.dry_run => return vec![].into_iter(), - Err(err) => panic!("could not read dir {:?}: {:?}", dir, err), + Err(err) => panic!("could not read dir {dir:?}: {err:?}"), }; iter.map(|e| t!(e)).collect::>().into_iter() } @@ -1591,7 +1591,7 @@ impl Build { if self.config.dry_run { return; } - fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {:?}", f)); + fs::remove_file(f).unwrap_or_else(|_| panic!("failed to remove {f:?}")); } /// Returns if config.ninja is enabled, and checks for ninja existence, @@ -1650,7 +1650,7 @@ fn chmod(_path: &Path, _perms: u32) {} fn detail_exit(code: i32) -> ! { // if in test and code is an error code, panic with status code provided if cfg!(test) && code != 0 { - panic!("status code: {}", code); + panic!("status code: {code}"); } else { //otherwise,exit with provided status code std::process::exit(code); diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 9045354d0b20a..df9adba931161 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -224,7 +224,7 @@ pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) { let llvm_root = config.ci_llvm_root(); let llvm_stamp = llvm_root.join(".llvm-stamp"); let llvm_sha = detect_llvm_sha(&config, builder.rust_info.is_managed_git_subrepository()); - let key = format!("{}{}", llvm_sha, config.llvm_assertions); + let key = format!("{llvm_sha}{}", config.llvm_assertions); if program_out_of_date(&llvm_stamp, &key) && !config.dry_run { download_ci_llvm(builder, &llvm_sha); for entry in t!(fs::read_dir(llvm_root.join("bin"))) { @@ -257,7 +257,7 @@ pub(crate) fn maybe_download_ci_llvm(builder: &Builder<'_>) { fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) { let llvm_assertions = builder.config.llvm_assertions; - let cache_prefix = format!("llvm-{}-{}", llvm_sha, llvm_assertions); + let cache_prefix = format!("llvm-{llvm_sha}-{llvm_assertions}"); let cache_dst = builder.out.join("cache"); let rustc_cache = cache_dst.join(cache_prefix); if !rustc_cache.exists() { @@ -269,7 +269,7 @@ fn download_ci_llvm(builder: &Builder<'_>, llvm_sha: &str) { &builder.config.stage0_metadata.config.artifacts_server }; let channel = builder.config.artifact_channel(builder, llvm_sha); - let filename = format!("rust-dev-{}-{}.tar.xz", channel, builder.build.build.triple); + let filename = format!("rust-dev-{channel}-{}.tar.xz", builder.build.build.triple); let tarball = rustc_cache.join(&filename); if !tarball.exists() { let help_on_error = "error: failed to download llvm from ci @@ -336,7 +336,7 @@ impl Step for Llvm { panic!("shared linking to LLVM is not currently supported on {}", target.triple); } - builder.info(&format!("Building LLVM for {}", target)); + builder.info(&format!("Building LLVM for {target}")); t!(stamp.remove()); let _time = util::timeit(&builder); t!(fs::create_dir_all(&out_dir)); @@ -561,8 +561,8 @@ impl Step for Llvm { let version = output(cmd.arg("--version")); let major = version.split('.').next().unwrap(); let lib_name = match llvm_version_suffix { - Some(s) => format!("libLLVM-{}{}.dylib", major, s), - None => format!("libLLVM-{}.dylib", major), + Some(s) => format!("libLLVM-{major}{s}.dylib"), + None => format!("libLLVM-{major}.dylib"), }; let lib_llvm = out_dir.join("build").join("lib").join(lib_name); @@ -594,7 +594,7 @@ fn check_llvm_version(builder: &Builder<'_>, llvm_config: &Path) { return; } } - panic!("\n\nbad LLVM version: {}, need >=13.0\n\n", version) + panic!("\n\nbad LLVM version: {version}, need >=13.0\n\n") } fn configure_cmake( @@ -738,7 +738,7 @@ fn configure_cmake( } } if builder.config.llvm_clang_cl.is_some() { - cflags.push(&format!(" --target={}", target)); + cflags.push(&format!(" --target={target}")); } cfg.define("CMAKE_C_FLAGS", cflags); let mut cxxflags: OsString = builder.cflags(target, GitRepo::Llvm, CLang::Cxx).join(" ").into(); @@ -747,7 +747,7 @@ fn configure_cmake( cxxflags.push(s); } if builder.config.llvm_clang_cl.is_some() { - cxxflags.push(&format!(" --target={}", target)); + cxxflags.push(&format!(" --target={target}")); } cfg.define("CMAKE_CXX_FLAGS", cxxflags); if let Some(ar) = builder.ar(target) { @@ -818,9 +818,9 @@ fn configure_llvm(builder: &Builder<'_>, target: TargetSelection, cfg: &mut cmak fn get_var(var_base: &str, host: &str, target: &str) -> Option { let kind = if host == target { "HOST" } else { "TARGET" }; let target_u = target.replace("-", "_"); - env::var_os(&format!("{}_{}", var_base, target)) - .or_else(|| env::var_os(&format!("{}_{}", var_base, target_u))) - .or_else(|| env::var_os(&format!("{}_{}", kind, var_base))) + env::var_os(&format!("{var_base}_{target}")) + .or_else(|| env::var_os(&format!("{var_base}_{target_u}"))) + .or_else(|| env::var_os(&format!("{kind}_{var_base}"))) .or_else(|| env::var_os(var_base)) } @@ -856,7 +856,7 @@ impl Step for Lld { return out_dir; } - builder.info(&format!("Building LLD for {}", target)); + builder.info(&format!("Building LLD for {target}")); let _time = util::timeit(&builder); t!(fs::create_dir_all(&out_dir)); @@ -1110,10 +1110,10 @@ fn supported_sanitizers( components .iter() .map(move |c| SanitizerRuntime { - cmake_target: format!("clang_rt.{}_{}_dynamic", c, os), + cmake_target: format!("clang_rt.{c}_{os}_dynamic"), path: out_dir - .join(&format!("build/lib/darwin/libclang_rt.{}_{}_dynamic.dylib", c, os)), - name: format!("librustc-{}_rt.{}.dylib", channel, c), + .join(&format!("build/lib/darwin/libclang_rt.{c}_{os}_dynamic.dylib")), + name: format!("librustc-{channel}_rt.{c}.dylib"), }) .collect() }; @@ -1122,9 +1122,9 @@ fn supported_sanitizers( components .iter() .map(move |c| SanitizerRuntime { - cmake_target: format!("clang_rt.{}-{}", c, arch), - path: out_dir.join(&format!("build/lib/{}/libclang_rt.{}-{}.a", os, c, arch)), - name: format!("librustc-{}_rt.{}.a", channel, c), + cmake_target: format!("clang_rt.{c}-{arch}"), + path: out_dir.join(&format!("build/lib/{os}/libclang_rt.{c}-{arch}.a")), + name: format!("librustc-{channel}_rt.{c}.a"), }) .collect() }; @@ -1168,7 +1168,7 @@ impl HashStamp { Ok(h) => self.hash.as_deref().unwrap_or(b"") == h.as_slice(), Err(e) if e.kind() == io::ErrorKind::NotFound => false, Err(e) => { - panic!("failed to read stamp file `{}`: {}", self.path.display(), e); + panic!("failed to read stamp file `{}`: {e}", self.path.display()); } } } diff --git a/src/bootstrap/run.rs b/src/bootstrap/run.rs index 511872903d14e..8e73fee3d3607 100644 --- a/src/bootstrap/run.rs +++ b/src/bootstrap/run.rs @@ -35,7 +35,7 @@ fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool { if !builder.fail_fast { if !builder.try_run(cmd) { let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); + failures.push(format!("{cmd:?}")); return false; } } else { diff --git a/src/bootstrap/sanity.rs b/src/bootstrap/sanity.rs index e905517253c0a..7c16ba9c03bb9 100644 --- a/src/bootstrap/sanity.rs +++ b/src/bootstrap/sanity.rs @@ -173,7 +173,7 @@ than building it. // Externally configured LLVM requires FileCheck to exist let filecheck = build.llvm_filecheck(build.build); if !filecheck.starts_with(&build.out) && !filecheck.exists() && build.config.codegen_tests { - panic!("FileCheck executable {:?} does not exist", filecheck); + panic!("FileCheck executable {filecheck:?} does not exist"); } } diff --git a/src/bootstrap/setup.rs b/src/bootstrap/setup.rs index eb7da1bda73cb..3022476c84075 100644 --- a/src/bootstrap/setup.rs +++ b/src/bootstrap/setup.rs @@ -22,7 +22,7 @@ pub enum Profile { impl Profile { fn include_path(&self, src_path: &Path) -> PathBuf { - PathBuf::from(format!("{}/src/bootstrap/defaults/config.{}.toml", src_path.display(), self)) + PathBuf::from(format!("{}/src/bootstrap/defaults/config.{self}.toml", src_path.display())) } pub fn all() -> impl Iterator { @@ -46,7 +46,7 @@ impl Profile { pub fn all_for_help(indent: &str) -> String { let mut out = String::new(); for choice in Profile::all() { - writeln!(&mut out, "{}{}: {}", indent, choice, choice.purpose()).unwrap(); + writeln!(&mut out, "{indent}{choice}: {}", choice.purpose()).unwrap(); } out } @@ -64,7 +64,7 @@ impl FromStr for Profile { "tools" | "tool" | "rustdoc" | "clippy" | "miri" | "rustfmt" | "rls" => { Ok(Profile::Tools) } - _ => Err(format!("unknown profile: '{}'", s)), + _ => Err(format!("unknown profile: '{s}'")), } } } @@ -89,7 +89,7 @@ pub fn setup(config: &Config, profile: Profile) { "error: you asked `x.py` to setup a new config file, but one already exists at `{}`", path.display() ); - eprintln!("help: try adding `profile = \"{}\"` at the top of {}", profile, path.display()); + eprintln!("help: try adding `profile = \"{profile}\"` at the top of {}", path.display()); eprintln!( "note: this will use the configuration in {}", profile.include_path(&config.src).display() @@ -142,7 +142,7 @@ pub fn setup(config: &Config, profile: Profile) { println!("To get started, try one of the following commands:"); for cmd in suggestions { - println!("- `x.py {}`", cmd); + println!("- `x.py {cmd}`"); } if profile != Profile::User { @@ -239,7 +239,7 @@ fn ensure_stage1_toolchain_placeholder_exists(stage_path: &str) -> bool { return false; }; - let pathbuf = pathbuf.join(format!("rustc{}", EXE_SUFFIX)); + let pathbuf = pathbuf.join(format!("rustc{EXE_SUFFIX}")); if pathbuf.exists() { return true; @@ -275,7 +275,7 @@ pub fn interactive_path() -> io::Result { println!("Welcome to the Rust project! What do you want to do with x.py?"); for ((letter, _), profile) in abbrev_all() { - println!("{}) {}: {}", letter, profile, profile.purpose()); + println!("{letter}) {profile}: {}", profile.purpose()); } let template = loop { print!( @@ -292,7 +292,7 @@ pub fn interactive_path() -> io::Result { break match parse_with_abbrev(&input) { Ok(profile) => profile, Err(err) => { - eprintln!("error: {}", err); + eprintln!("error: {err}"); eprintln!("note: press Ctrl+C to exit"); continue; } diff --git a/src/bootstrap/tarball.rs b/src/bootstrap/tarball.rs index d999b6c150333..0793235e10cdf 100644 --- a/src/bootstrap/tarball.rs +++ b/src/bootstrap/tarball.rs @@ -277,7 +277,7 @@ impl<'a> Tarball<'a> { fn package_name(&self) -> String { if let Some(target) = &self.target { - format!("{}-{}", self.pkgname, target) + format!("{}-{target}", self.pkgname) } else { self.pkgname.clone() } @@ -309,7 +309,7 @@ impl<'a> Tarball<'a> { let mut cmd = self.builder.tool_cmd(crate::tool::Tool::RustInstaller); let package_name = self.package_name(); - self.builder.info(&format!("Dist {}", package_name)); + self.builder.info(&format!("Dist {package_name}")); let _time = crate::util::timeit(self.builder); build_cli(&self, &mut cmd); @@ -343,7 +343,7 @@ impl<'a> Tarball<'a> { .unwrap_or("gz"); GeneratedTarball { - path: crate::dist::distdir(self.builder).join(format!("{}.tar.{}", package_name, ext)), + path: crate::dist::distdir(self.builder).join(format!("{package_name}.tar.{ext}")), decompressed_output, work: self.temp_dir, } diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 43e2470e633d0..e511b8948fbe6 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -39,7 +39,7 @@ impl From for TestKind { match kind { Kind::Test => TestKind::Test, Kind::Bench => TestKind::Bench, - _ => panic!("unexpected kind in crate: {:?}", kind), + _ => panic!("unexpected kind in crate: {kind:?}"), } } } @@ -67,7 +67,7 @@ fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> bool { if !builder.fail_fast { if !builder.try_run(cmd) { let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); + failures.push(format!("{cmd:?}")); return false; } } else { @@ -80,7 +80,7 @@ fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool { if !builder.fail_fast { if !builder.try_run_quiet(cmd) { let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); + failures.push(format!("{cmd:?}")); return false; } } else { @@ -119,7 +119,7 @@ You can skip linkcheck with --exclude src/tools/linkchecker" ); } - builder.info(&format!("Linkcheck ({})", host)); + builder.info(&format!("Linkcheck ({host})")); // Test the linkchecker itself. let bootstrap_host = builder.config.build; @@ -530,7 +530,7 @@ impl Step for Miri { let miri_sysroot = if builder.config.dry_run { String::new() } else { - builder.verbose(&format!("running: {:?}", cargo)); + builder.verbose(&format!("running: {cargo:?}")); let out = cargo.output().expect("We already ran `cargo miri setup` before and that worked"); assert!(out.status.success(), "`cargo miri setup` returned with non-0 exit code"); @@ -538,7 +538,7 @@ impl Step for Miri { let stdout = String::from_utf8(out.stdout) .expect("`cargo miri setup` stdout is not valid UTF-8"); let sysroot = stdout.trim_end(); - builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {:?}", sysroot)); + builder.verbose(&format!("`cargo miri setup --print-sysroot` said: {sysroot:?}")); sysroot.to_owned() }; @@ -858,7 +858,7 @@ fn compare_browser_ui_test_version(installed_version: &str, src: &Path) { ); } } - Err(e) => eprintln!("Couldn't find the CI browser-ui-test version: {:?}", e), + Err(e) => eprintln!("Couldn't find the CI browser-ui-test version: {e:?}"), } } @@ -1333,7 +1333,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--src-base").arg(builder.src.join("src/test").join(suite)); cmd.arg("--build-base").arg(testdir(builder, compiler.host).join(suite)); - cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target)); + cmd.arg("--stage-id").arg(format!("stage{}-{target}", compiler.stage)); cmd.arg("--suite").arg(suite); cmd.arg("--mode").arg(mode); cmd.arg("--target").arg(target.rustc_target_arg()); @@ -1401,7 +1401,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the String::from_utf8_lossy(&output.stdout) .lines() .next() - .unwrap_or_else(|| panic!("{:?} failed {:?}", cmd, output)) + .unwrap_or_else(|| panic!("{cmd:?} failed {output:?}")) .to_string() }) }; @@ -2266,7 +2266,7 @@ impl Step for RemoteCopyLibs { builder.ensure(compile::Std::new(compiler, target)); - builder.info(&format!("REMOTE copy libs to emulator ({})", target)); + builder.info(&format!("REMOTE copy libs to emulator ({target})")); let server = builder.ensure(tool::RemoteTestServer { compiler, target }); diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index d6e7f7872703e..489e5e86d790c 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -70,7 +70,7 @@ impl Step for ToolBuild { &self.extra_features, ); - builder.info(&format!("Building stage{} tool {} ({})", compiler.stage, tool, target)); + builder.info(&format!("Building stage{} tool {tool} ({target})", compiler.stage)); let mut duplicates = Vec::new(); let is_expected = compile::stream_cargo(builder, cargo, vec![], &mut |msg| { // Only care about big things like the RLS/Cargo for now @@ -166,7 +166,7 @@ impl Step for ToolBuild { have the same features enabled:" ); for (id, cur, prev) in same { - eprintln!(" {}", id); + eprintln!(" {id}"); // same features eprintln!(" `{}` ({:?})\n `{}` ({:?})", cur.0, cur.1, prev.0, prev.1); } @@ -174,7 +174,7 @@ impl Step for ToolBuild { if !different.is_empty() { eprintln!("the following dependencies have different features:"); for (id, cur, prev) in different { - eprintln!(" {}", id); + eprintln!(" {id}"); let cur_features: HashSet<_> = cur.2.into_iter().collect(); let prev_features: HashSet<_> = prev.2.into_iter().collect(); eprintln!( diff --git a/src/bootstrap/toolstate.rs b/src/bootstrap/toolstate.rs index 1a17744322753..a3b3f5154bb17 100644 --- a/src/bootstrap/toolstate.rs +++ b/src/bootstrap/toolstate.rs @@ -83,13 +83,13 @@ static NIGHTLY_TOOLS: &[(&str, &str)] = &[ fn print_error(tool: &str, submodule: &str) { eprintln!(); - eprintln!("We detected that this PR updated '{}', but its tests failed.", tool); + eprintln!("We detected that this PR updated '{tool}', but its tests failed."); eprintln!(); - eprintln!("If you do intend to update '{}', please check the error messages above and", tool); + eprintln!("If you do intend to update '{tool}', please check the error messages above and"); eprintln!("commit another update."); eprintln!(); - eprintln!("If you do NOT intend to update '{}', please ensure you did not accidentally", tool); - eprintln!("change the submodule at '{}'. You may ask your reviewer for the", submodule); + eprintln!("If you do NOT intend to update '{tool}', please ensure you did not accidentally"); + eprintln!("change the submodule at '{submodule}'. You may ask your reviewer for the"); eprintln!("proper steps."); crate::detail_exit(3); } @@ -105,7 +105,7 @@ fn check_changed_files(toolstates: &HashMap, ToolState>) { let output = match output { Ok(o) => o, Err(e) => { - eprintln!("Failed to get changed files: {:?}", e); + eprintln!("Failed to get changed files: {e:?}"); crate::detail_exit(1); } }; @@ -114,12 +114,12 @@ fn check_changed_files(toolstates: &HashMap, ToolState>) { for (tool, submodule) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) { let changed = output.lines().any(|l| l.starts_with('M') && l.ends_with(submodule)); - eprintln!("Verifying status of {}...", tool); + eprintln!("Verifying status of {tool}..."); if !changed { continue; } - eprintln!("This PR updated '{}', verifying if status is 'test-pass'...", submodule); + eprintln!("This PR updated '{submodule}', verifying if status is 'test-pass'..."); if toolstates[*tool] != ToolState::TestPass { print_error(tool, submodule); } @@ -172,7 +172,7 @@ impl Step for ToolStateCheck { for (tool, _) in STABLE_TOOLS.iter().chain(NIGHTLY_TOOLS.iter()) { if !toolstates.contains_key(*tool) { did_error = true; - eprintln!("error: Tool `{}` was not recorded in tool state.", tool); + eprintln!("error: Tool `{tool}` was not recorded in tool state."); } } @@ -190,7 +190,7 @@ impl Step for ToolStateCheck { if state != ToolState::TestPass { if !is_nightly { did_error = true; - eprintln!("error: Tool `{}` should be test-pass but is {}", tool, state); + eprintln!("error: Tool `{tool}` should be test-pass but is {state}"); } else if in_beta_week { let old_state = old_toolstate .iter() @@ -320,7 +320,7 @@ fn checkout_toolstate_repo() { Err(_) => false, }; if !success { - panic!("git clone unsuccessful (status: {:?})", status); + panic!("git clone unsuccessful (status: {status:?})"); } } @@ -333,7 +333,7 @@ fn prepare_toolstate_config(token: &str) { Err(_) => false, }; if !success { - panic!("git config key={} value={} failed (status: {:?})", key, value, status); + panic!("git config key={key} value={value} failed (status: {status:?})"); } } @@ -343,7 +343,7 @@ fn prepare_toolstate_config(token: &str) { git_config("user.name", "Rust Toolstate Update"); git_config("credential.helper", "store"); - let credential = format!("https://{}:x-oauth-basic@github.com\n", token,); + let credential = format!("https://{token}:x-oauth-basic@github.com\n",); let git_credential_path = PathBuf::from(t!(env::var("HOME"))).join(".git-credentials"); t!(fs::write(&git_credential_path, credential)); } @@ -453,7 +453,7 @@ fn publish_test_results(current_toolstate: &ToolstateData) { .join(format!("{}.tsv", OS.expect("linux/windows only"))); let mut file = t!(fs::read_to_string(&history_path)); let end_of_first_line = file.find('\n').unwrap(); - file.insert_str(end_of_first_line, &format!("\n{}\t{}", commit.trim(), toolstate_serialized)); + file.insert_str(end_of_first_line, &format!("\n{}\t{toolstate_serialized}", commit.trim())); t!(fs::write(&history_path, file)); } diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs index 0ebabbd5ca5c0..f08f0b689a8b9 100644 --- a/src/bootstrap/util.rs +++ b/src/bootstrap/util.rs @@ -43,7 +43,7 @@ pub use t; /// Given an executable called `name`, return the filename for the /// executable for a particular target. pub fn exe(name: &str, target: TargetSelection) -> String { - if target.contains("windows") { format!("{}.exe", name) } else { name.to_string() } + if target.contains("windows") { format!("{name}.exe") } else { name.to_string() } } /// Returns `true` if the file name given looks like a dynamic library. @@ -350,7 +350,7 @@ pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) { pub fn try_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool { let status = match cmd.status() { Ok(status) => status, - Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)), + Err(e) => fail(&format!("failed to execute command: {cmd:?}\nerror: {e}")), }; if !status.success() && print_cmd_on_fail { println!( @@ -366,7 +366,7 @@ pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool { let status = match cmd.status() { Ok(status) => status, Err(e) => { - println!("failed to execute command: {:?}\nerror: {}", cmd, e); + println!("failed to execute command: {cmd:?}\nerror: {e}"); return false; } }; @@ -389,7 +389,7 @@ pub fn run_suppressed(cmd: &mut Command) { pub fn try_run_suppressed(cmd: &mut Command) -> bool { let output = match cmd.output() { Ok(status) => status, - Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)), + Err(e) => fail(&format!("failed to execute command: {cmd:?}\nerror: {e}")), }; if !output.status.success() { println!( @@ -422,7 +422,7 @@ pub fn make(host: &str) -> PathBuf { pub fn output(cmd: &mut Command) -> String { let output = match cmd.stderr(Stdio::inherit()).output() { Ok(status) => status, - Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}", cmd, e)), + Err(e) => fail(&format!("failed to execute command: {cmd:?}\nerror: {e}")), }; if !output.status.success() { panic!( @@ -450,7 +450,7 @@ pub fn up_to_date(src: &Path, dst: &Path) -> bool { let threshold = mtime(dst); let meta = match fs::metadata(src) { Ok(meta) => meta, - Err(e) => panic!("source {:?} failed to get metadata: {}", src, e), + Err(e) => panic!("source {src:?} failed to get metadata: {e}"), }; if meta.is_dir() { dir_up_to_date(src, threshold) @@ -471,7 +471,7 @@ fn dir_up_to_date(src: &Path, threshold: SystemTime) -> bool { } fn fail(s: &str) -> ! { - eprintln!("\n\n{}\n\n", s); + eprintln!("\n\n{s}\n\n"); crate::detail_exit(1); } diff --git a/src/etc/pre-push.sh b/src/etc/pre-push.sh index be7de3ebaf571..283b6b95429c0 100755 --- a/src/etc/pre-push.sh +++ b/src/etc/pre-push.sh @@ -1,25 +1,23 @@ -#!/usr/bin/env bash -# -# Call `tidy --bless` before git push -# Copy this script to .git/hooks to activate, -# and remove it from .git/hooks to deactivate. -# +#!/bin/sh +# rusty-hook +# version 0.8.4 -set -Eeuo pipefail +hookName=$(basename "$0") +gitParams="$*" -# https://github.com/rust-lang/rust/issues/77620#issuecomment-705144570 -unset GIT_DIR -ROOT_DIR="$(git rev-parse --show-toplevel)" -COMMAND="$ROOT_DIR/x.py test tidy" - -if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then - COMMAND="python $COMMAND" -elif ! command -v python &> /dev/null; then - COMMAND="python3 $COMMAND" +if ! command -v rusty-hook >/dev/null 2>&1; then + if [ -z "${RUSTY_HOOK_SKIP_AUTO_INSTALL}" ]; then + echo "Finalizing rusty-hook configuration..." + echo "This may take a few seconds..." + cargo install rusty-hook >/dev/null 2>&1 + else + echo "rusty-hook is not installed, and auto install is disabled" + echo "skipping $hookName hook" + echo "You can reinstall it using 'cargo install rusty-hook' or delete this hook" + exit 0 + fi fi -echo "Running pre-push script '$COMMAND'" - -cd "$ROOT_DIR" - -$COMMAND +# echo "rusty-hook version: $(rusty-hook --version)" +# echo "hook file version: 0.8.4" +rusty-hook run --hook "$hookName" "$gitParams" \ No newline at end of file diff --git a/src/etc/test-float-parse/src/bin/huge-pow10.rs b/src/etc/test-float-parse/src/bin/huge-pow10.rs index 722a24ffcd8d9..c0aad3697bf31 100644 --- a/src/etc/test-float-parse/src/bin/huge-pow10.rs +++ b/src/etc/test-float-parse/src/bin/huge-pow10.rs @@ -3,7 +3,7 @@ use test_float_parse::validate; fn main() { for e in 300..310 { for i in 0..100000 { - validate(&format!("{}e{}", i, e)); + validate(&format!("{i}e{e}")); } } } diff --git a/src/etc/test-float-parse/src/bin/rand-f64.rs b/src/etc/test-float-parse/src/bin/rand-f64.rs index 6991e8be15e1c..a43bc2a2a7433 100644 --- a/src/etc/test-float-parse/src/bin/rand-f64.rs +++ b/src/etc/test-float-parse/src/bin/rand-f64.rs @@ -11,7 +11,7 @@ fn main() { let bits = rnd.next_u64(); let x: f64 = unsafe { transmute(bits) }; if x.is_finite() { - validate(&format!("{:e}", x)); + validate(&format!("{x:e}")); i += 1; } } diff --git a/src/etc/test-float-parse/src/bin/short-decimals.rs b/src/etc/test-float-parse/src/bin/short-decimals.rs index 49084eb35e834..fac868e394429 100644 --- a/src/etc/test-float-parse/src/bin/short-decimals.rs +++ b/src/etc/test-float-parse/src/bin/short-decimals.rs @@ -10,8 +10,8 @@ fn main() { if i % 10 == 0 { continue; } - validate(&format!("{}e{}", i, e)); - validate(&format!("{}e-{}", i, e)); + validate(&format!("{i}e{e}")); + validate(&format!("{i}e-{e}")); } } } diff --git a/src/etc/test-float-parse/src/bin/subnorm.rs b/src/etc/test-float-parse/src/bin/subnorm.rs index ac88747eacd35..e028ad69efc91 100644 --- a/src/etc/test-float-parse/src/bin/subnorm.rs +++ b/src/etc/test-float-parse/src/bin/subnorm.rs @@ -4,8 +4,8 @@ use test_float_parse::validate; fn main() { for bits in 0u32..(1 << 21) { let single: f32 = unsafe { transmute(bits) }; - validate(&format!("{:e}", single)); + validate(&format!("{single:e}")); let double: f64 = unsafe { transmute(bits as u64) }; - validate(&format!("{:e}", double)); + validate(&format!("{double:e}")); } } diff --git a/src/etc/test-float-parse/src/bin/tiny-pow10.rs b/src/etc/test-float-parse/src/bin/tiny-pow10.rs index fb6ba16638044..936fde1e807ad 100644 --- a/src/etc/test-float-parse/src/bin/tiny-pow10.rs +++ b/src/etc/test-float-parse/src/bin/tiny-pow10.rs @@ -3,7 +3,7 @@ use test_float_parse::validate; fn main() { for e in 301..327 { for i in 0..100000 { - validate(&format!("{}e-{}", i, e)); + validate(&format!("{i}e-{e}")); } } } diff --git a/src/etc/test-float-parse/src/lib.rs b/src/etc/test-float-parse/src/lib.rs index 9cbad5486b485..0a57083e501f3 100644 --- a/src/etc/test-float-parse/src/lib.rs +++ b/src/etc/test-float-parse/src/lib.rs @@ -12,5 +12,5 @@ pub fn validate(text: &str) { let f64_bytes: u64 = unsafe { transmute(x) }; let x: f32 = text.parse().unwrap(); let f32_bytes: u32 = unsafe { transmute(x) }; - writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap(); + writeln!(&mut out, "{f64_bytes:016x} {f32_bytes:08x} {text}").unwrap(); } diff --git a/src/test/rustdoc-gui/src/test_docs/build.rs b/src/test/rustdoc-gui/src/test_docs/build.rs index 16c96ded9120c..31cf1105a9f05 100644 --- a/src/test/rustdoc-gui/src/test_docs/build.rs +++ b/src/test/rustdoc-gui/src/test_docs/build.rs @@ -7,7 +7,7 @@ fn main() -> std::io::Result<()> { let mut output = String::new(); for i in 0..2000 { - let line = format!("/// Some const A{0}\npub const A{0}: isize = 0;\n", i); + let line = format!("/// Some const A{i}\npub const A{i}: isize = 0;\n"); output.push_str(&*line); }; diff --git a/src/tools/build-manifest/src/checksum.rs b/src/tools/build-manifest/src/checksum.rs index c019c7a2f7aec..c18a9f354b78d 100644 --- a/src/tools/build-manifest/src/checksum.rs +++ b/src/tools/build-manifest/src/checksum.rs @@ -82,7 +82,7 @@ impl Checksums { Ok(hash) => { self.collected.lock().unwrap().insert(path.clone(), hash); } - Err(err) => eprintln!("error while fetching the hash for {}: {}", path.display(), err), + Err(err) => eprintln!("error while fetching the hash for {}: {err}", path.display()), }); println!("collected {} hashes in {:.2?}", files.len(), collection_start.elapsed()); diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index b0006cb90bdd6..2a28c1cb7655e 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -572,7 +572,7 @@ impl Builder { fn url(&self, path: &Path) -> String { let file_name = path.file_name().unwrap().to_str().unwrap(); - format!("{}/{}/{}", self.s3_address, self.date, file_name) + format!("{}/{}/{file_name}", self.s3_address, self.date) } fn write_channel_files(&mut self, channel_name: &str, manifest: &Manifest) { @@ -586,7 +586,7 @@ impl Builder { } fn write(&mut self, contents: &str, channel_name: &str, suffix: &str) { - let name = format!("channel-rust-{}{}", channel_name, suffix); + let name = format!("channel-rust-{channel_name}{suffix}"); self.shipped_files.insert(name.clone()); let dst = self.output.join(name); diff --git a/src/tools/build-manifest/src/versions.rs b/src/tools/build-manifest/src/versions.rs index 0186194a41f55..df5706a5231ef 100644 --- a/src/tools/build-manifest/src/versions.rs +++ b/src/tools/build-manifest/src/versions.rs @@ -180,9 +180,9 @@ impl Versions { }; if package.target_independent() { - Ok(format!("{}-{}.{}", component_name, version, extension)) + Ok(format!("{component_name}-{version}.{extension}")) } else { - Ok(format!("{}-{}-{}.{}", component_name, version, target, extension)) + Ok(format!("{component_name}-{version}-{target}.{extension}")) } } diff --git a/src/tools/bump-stage0/src/main.rs b/src/tools/bump-stage0/src/main.rs index aa346daf7e5f3..c04a4d354fd34 100644 --- a/src/tools/bump-stage0/src/main.rs +++ b/src/tools/bump-stage0/src/main.rs @@ -148,8 +148,8 @@ fn main() -> Result<(), Error> { fn fetch_manifest(config: &Config, channel: &str) -> Result { Ok(toml::from_slice(&http_get(&format!( - "{}/dist/channel-rust-{}.toml", - config.dist_server, channel + "{}/dist/channel-rust-{channel}.toml", + config.dist_server ))?)?) } diff --git a/src/tools/cargo b/src/tools/cargo index 3cdf1ab25dc4f..707d7a65976cb 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 3cdf1ab25dc4fe56f890e8c7330d53a23ad905d3 +Subproject commit 707d7a65976cb755d93d2ba8f396d8d957113d6a diff --git a/src/tools/cargotest/main.rs b/src/tools/cargotest/main.rs index 95fe98a683ffd..180f8953e7208 100644 --- a/src/tools/cargotest/main.rs +++ b/src/tools/cargotest/main.rs @@ -141,7 +141,7 @@ fn clone_repo(test: &Test, out_dir: &Path) -> PathBuf { .arg("fetch") .arg(test.repo) .arg("master") - .arg(&format!("--depth={}", depth)) + .arg(&format!("--depth={depth}")) .current_dir(&out_dir) .status() .unwrap(); @@ -184,13 +184,13 @@ fn run_cargo_test( command.arg("test"); if let Some(path) = manifest_path { - command.arg(format!("--manifest-path={}", path)); + command.arg(format!("--manifest-path={path}")); } if let Some(features) = features { command.arg("--no-default-features"); for feature in features { - command.arg(format!("--features={}", feature)); + command.arg(format!("--features={feature}")); } } diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index b9ac6c9f36418..06d2c12711a97 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -142,7 +142,7 @@ impl CompareMode { "chalk" => CompareMode::Chalk, "split-dwarf" => CompareMode::SplitDwarf, "split-dwarf-single" => CompareMode::SplitDwarfSingle, - x => panic!("unknown --compare-mode option: {}", x), + x => panic!("unknown --compare-mode option: {x}"), } } } @@ -466,7 +466,7 @@ impl TargetCfg { .output() { Ok(output) => output, - Err(e) => panic!("error: failed to get cfg info from {:?}: {e}", rustc_path), + Err(e) => panic!("error: failed to get cfg info from {rustc_path:?}: {e}"), }; if !output.status.success() { panic!( diff --git a/src/tools/compiletest/src/compute_diff.rs b/src/tools/compiletest/src/compute_diff.rs index 92c80c27de03b..475e408317864 100644 --- a/src/tools/compiletest/src/compute_diff.rs +++ b/src/tools/compiletest/src/compute_diff.rs @@ -90,15 +90,15 @@ pub(crate) fn write_diff(expected: &str, actual: &str, context_size: usize) -> S for line in result.lines { match line { DiffLine::Expected(e) => { - writeln!(output, "-\t{}", e).unwrap(); + writeln!(output, "-\t{e}").unwrap(); line_number += 1; } DiffLine::Context(c) => { - writeln!(output, "{}\t{}", line_number, c).unwrap(); + writeln!(output, "{line_number}\t{c}").unwrap(); line_number += 1; } DiffLine::Resulting(r) => { - writeln!(output, "+\t{}", r).unwrap(); + writeln!(output, "+\t{r}").unwrap(); } } } diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 6f85227500361..6b4e770460135 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -455,14 +455,14 @@ impl TestProps { } if let (Some(edition), false) = (&config.edition, has_edition) { - self.compile_flags.push(format!("--edition={}", edition)); + self.compile_flags.push(format!("--edition={edition}")); } } fn update_fail_mode(&mut self, ln: &str, config: &Config) { let check_ui = |mode: &str| { if config.mode != Mode::Ui { - panic!("`{}-fail` header is only supported in UI tests", mode); + panic!("`{mode}-fail` header is only supported in UI tests"); } }; if config.mode == Mode::Ui && config.parse_name_directive(ln, "compile-fail") { @@ -490,13 +490,13 @@ impl TestProps { fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) { let check_no_run = |s| { if config.mode != Mode::Ui && config.mode != Mode::Incremental { - panic!("`{}` header is only supported in UI and incremental tests", s); + panic!("`{s}` header is only supported in UI and incremental tests"); } if config.mode == Mode::Incremental && !revision.map_or(false, |r| r.starts_with("cfail")) && !self.revisions.iter().all(|r| r.starts_with("cfail")) { - panic!("`{}` header is only supported in `cfail` incremental tests", s); + panic!("`{s}` header is only supported in `cfail` incremental tests"); } }; let pass_mode = if config.parse_name_directive(ln, "check-pass") { @@ -548,7 +548,7 @@ pub fn line_directive<'line>( Some((Some(lncfg), ln[(close_brace + 1)..].trim_start())) } else { - panic!("malformed condition directive: expected `{}[foo]`, found `{}`", comment, ln) + panic!("malformed condition directive: expected `{comment}[foo]`, found `{ln}`") } } else { Some((None, ln)) @@ -600,7 +600,7 @@ impl Config { let mut duplicates: HashSet<_> = existing.iter().cloned().collect(); for revision in raw.split_whitespace().map(|r| r.to_string()) { if !duplicates.insert(revision.clone()) { - panic!("Duplicate revision: `{}` in line `{}`", revision, raw); + panic!("Duplicate revision: `{revision}` in line `{raw}`"); } existing.push(revision); } @@ -617,7 +617,7 @@ impl Config { let end = strs.pop().unwrap(); (strs.pop().unwrap(), end) } - n => panic!("Expected 1 or 2 strings, not {}", n), + n => panic!("Expected 1 or 2 strings, not {n}"), } } @@ -983,7 +983,7 @@ fn ignore_cdb(config: &Config, line: &str) -> bool { if let Some(actual_version) = config.cdb_version { if let Some(min_version) = line.strip_prefix("min-cdb-version:").map(str::trim) { let min_version = extract_cdb_version(min_version).unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", min_version); + panic!("couldn't parse version range: {min_version:?}"); }); // Ignore if actual version is smaller than the minimum @@ -999,7 +999,7 @@ fn ignore_gdb(config: &Config, line: &str) -> bool { if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) { let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version) .unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", rest); + panic!("couldn't parse version range: {rest:?}"); }); if start_ver != end_ver { @@ -1011,7 +1011,7 @@ fn ignore_gdb(config: &Config, line: &str) -> bool { } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) { let (min_version, max_version) = extract_version_range(rest, extract_gdb_version) .unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", rest); + panic!("couldn't parse version range: {rest:?}"); }); if max_version < min_version { @@ -1028,7 +1028,7 @@ fn ignore_lldb(config: &Config, line: &str) -> bool { if let Some(actual_version) = config.lldb_version { if let Some(min_version) = line.strip_prefix("min-lldb-version:").map(str::trim) { let min_version = min_version.parse().unwrap_or_else(|e| { - panic!("Unexpected format of LLDB version string: {}\n{:?}", min_version, e); + panic!("Unexpected format of LLDB version string: {min_version}\n{e:?}"); }); // Ignore if actual version is smaller the minimum required // version @@ -1054,7 +1054,7 @@ fn ignore_llvm(config: &Config, line: &str) -> bool { .find(|needed_component| !components.contains(needed_component)) { if env::var_os("COMPILETEST_NEEDS_ALL_LLVM_COMPONENTS").is_some() { - panic!("missing LLVM component: {}", missing_component); + panic!("missing LLVM component: {missing_component}"); } return true; } @@ -1074,7 +1074,7 @@ fn ignore_llvm(config: &Config, line: &str) -> bool { // Syntax is: "ignore-llvm-version: [- ]" let (v_min, v_max) = extract_version_range(rest, extract_llvm_version).unwrap_or_else(|| { - panic!("couldn't parse version range: {:?}", rest); + panic!("couldn't parse version range: {rest:?}"); }); if v_max < v_min { panic!("Malformed LLVM version range: max < min") diff --git a/src/tools/compiletest/src/json.rs b/src/tools/compiletest/src/json.rs index 10726b9842080..9fcaee60cb905 100644 --- a/src/tools/compiletest/src/json.rs +++ b/src/tools/compiletest/src/json.rs @@ -133,7 +133,7 @@ pub fn extract_rendered(output: &str) -> String { } } else { // preserve non-JSON lines, such as ICEs - Some(format!("{}\n", line)) + Some(format!("{line}\n")) } }) .collect() @@ -239,8 +239,8 @@ fn push_expected_errors( // FIXME(#33000) -- it'd be better to use a dedicated UI harness { format!( - "{}:{}: {}:{}: {}", - span.line_start, span.column_start, span.line_end, span.column_end, text + "{}:{}: {}:{}: {text}", + span.line_start, span.column_start, span.line_end, span.column_end ) } } diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index b48395035d4f0..51bfafe4dac28 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -153,7 +153,7 @@ pub fn parse_config(args: Vec) -> Config { let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 || args[1] == "-h" || args[1] == "--help" { - let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); + let message = format!("Usage: {argv0} [OPTIONS] [TESTNAME...]"); println!("{}", opts.usage(&message)); println!(); panic!() @@ -161,11 +161,11 @@ pub fn parse_config(args: Vec) -> Config { let matches = &match opts.parse(args_) { Ok(m) => m, - Err(f) => panic!("{:?}", f), + Err(f) => panic!("{f:?}"), }; if matches.opt_present("h") || matches.opt_present("help") { - let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); + let message = format!("Usage: {argv0} [OPTIONS] [TESTNAME...]"); println!("{}", opts.usage(&message)); println!(); panic!() @@ -174,7 +174,7 @@ pub fn parse_config(args: Vec) -> Config { fn opt_path(m: &getopts::Matches, nm: &str) -> PathBuf { match m.opt_str(nm) { Some(s) => PathBuf::from(&s), - None => panic!("no option (=path) found for {}", nm), + None => panic!("no option (=path) found for {nm}"), } } @@ -197,7 +197,7 @@ pub fn parse_config(args: Vec) -> Config { Some("auto") | None => ColorConfig::AutoColor, Some("always") => ColorConfig::AlwaysColor, Some("never") => ColorConfig::NeverColor, - Some(x) => panic!("argument for --color must be auto, always, or never, but found `{}`", x), + Some(x) => panic!("argument for --color must be auto, always, or never, but found `{x}`"), }; let llvm_version = matches.opt_str("llvm-version").as_deref().and_then(header::extract_llvm_version); @@ -242,13 +242,13 @@ pub fn parse_config(args: Vec) -> Config { filter_exact: matches.opt_present("exact"), force_pass_mode: matches.opt_str("pass").map(|mode| { mode.parse::() - .unwrap_or_else(|_| panic!("unknown `--pass` option `{}` given", mode)) + .unwrap_or_else(|_| panic!("unknown `--pass` option `{mode}` given")) }), run: matches.opt_str("run").and_then(|mode| match mode.as_str() { "auto" => None, "always" => Some(true), "never" => Some(false), - _ => panic!("unknown `--run` option `{}` given", mode), + _ => panic!("unknown `--run` option `{mode}` given"), }), logfile: matches.opt_str("logfile").map(|s| PathBuf::from(&s)), runtool: matches.opt_str("runtool"), @@ -317,7 +317,7 @@ pub fn log_config(config: &Config) { logv(c, format!("filter_exact: {}", config.filter_exact)); logv( c, - format!("force_pass_mode: {}", opt_str(&config.force_pass_mode.map(|m| format!("{}", m))),), + format!("force_pass_mode: {}", opt_str(&config.force_pass_mode.map(|m| format!("{m}"))),), ); logv(c, format!("runtool: {}", opt_str(&config.runtool))); logv(c, format!("host-rustcflags: {}", opt_str(&config.host_rustcflags))); @@ -358,7 +358,7 @@ pub fn run_tests(config: Config) { coverage_file_path.push("rustfix_missing_coverage.txt"); if coverage_file_path.exists() { if let Err(e) = fs::remove_file(&coverage_file_path) { - panic!("Could not delete {} due to {}", coverage_file_path.display(), e) + panic!("Could not delete {} due to {e}", coverage_file_path.display()) } } } @@ -409,7 +409,7 @@ pub fn run_tests(config: Config) { eprintln!( "Some tests failed in compiletest suite={}{} mode={} host={} target={}", config.suite, - config.compare_mode.map(|c| format!(" compare_mode={:?}", c)).unwrap_or_default(), + config.compare_mode.map(|c| format!(" compare_mode={c:?}")).unwrap_or_default(), config.mode, config.host, config.target @@ -424,7 +424,7 @@ pub fn run_tests(config: Config) { // // This should realistically "never" happen, so don't try to make // this a pretty error message. - panic!("I/O failure during tests: {:?}", e); + panic!("I/O failure during tests: {e:?}"); } } } @@ -771,7 +771,7 @@ fn make_test_name( let root_directory = config.src_base.parent().unwrap().parent().unwrap().parent().unwrap(); let path = testpaths.file.strip_prefix(root_directory).unwrap(); let debugger = match config.debugger { - Some(d) => format!("-{}", d), + Some(d) => format!("-{d}"), None => String::new(), }; let mode_suffix = match config.compare_mode { @@ -785,7 +785,7 @@ fn make_test_name( debugger, mode_suffix, path.display(), - revision.map_or("".to_string(), |rev| format!("#{}", rev)) + revision.map_or("".to_string(), |rev| format!("#{rev}")) )) } diff --git a/src/tools/compiletest/src/read2.rs b/src/tools/compiletest/src/read2.rs index 7640e65174428..424dd07ce418a 100644 --- a/src/tools/compiletest/src/read2.rs +++ b/src/tools/compiletest/src/read2.rs @@ -111,7 +111,7 @@ impl ProcOutput { match self { ProcOutput::Full { bytes, .. } => bytes, ProcOutput::Abbreviated { mut head, skipped, tail } => { - write!(&mut head, "\n\n<<<<<< SKIPPED {} BYTES >>>>>>\n\n", skipped).unwrap(); + write!(&mut head, "\n\n<<<<<< SKIPPED {skipped} BYTES >>>>>>\n\n").unwrap(); head.extend_from_slice(&tail); head } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 8f289876f7307..648a09a04a4d2 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -92,15 +92,15 @@ pub fn get_lib_name(lib: &str, dylib: bool) -> String { // In this case, the only path we can pass // with '--extern-meta' is the '.lib' file if !dylib { - return format!("lib{}.rlib", lib); + return format!("lib{lib}.rlib"); } if cfg!(windows) { - format!("{}.dll", lib) + format!("{lib}.dll") } else if cfg!(target_os = "macos") { - format!("lib{}.dylib", lib) + format!("lib{lib}.dylib") } else { - format!("lib{}.so", lib) + format!("lib{lib}.so") } } @@ -260,7 +260,7 @@ impl<'test> TestCx<'test> { Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => true, MirOpt if pm == Some(PassMode::Run) => true, Ui | MirOpt => false, - mode => panic!("unimplemented for mode {:?}", mode), + mode => panic!("unimplemented for mode {mode:?}"), }; if test_should_run { self.run_if_enabled() } else { WillExecute::No } } @@ -272,7 +272,7 @@ impl<'test> TestCx<'test> { fn should_run_successfully(&self, pm: Option) -> bool { match self.config.mode { Ui | MirOpt => pm == Some(PassMode::Run), - mode => panic!("unimplemented for mode {:?}", mode), + mode => panic!("unimplemented for mode {mode:?}"), } } @@ -292,7 +292,7 @@ impl<'test> TestCx<'test> { panic!("revision name must begin with rpass, rfail, or cfail"); } } - mode => panic!("unimplemented for mode {:?}", mode), + mode => panic!("unimplemented for mode {mode:?}"), } } @@ -463,7 +463,7 @@ impl<'test> TestCx<'test> { while round < rounds { logv( self.config, - format!("pretty-printing round {} revision {:?}", round, self.revision), + format!("pretty-printing round {round} revision {:?}", self.revision), ); let read_from = if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) }; @@ -552,7 +552,7 @@ impl<'test> TestCx<'test> { let mut rustc = Command::new(&self.config.rustc_path); rustc .arg(input) - .args(&["-Z", &format!("unpretty={}", pretty_type)]) + .args(&["-Z", &format!("unpretty={pretty_type}")]) .args(&["--target", &self.config.target]) .arg("-L") .arg(&aux_dir) @@ -623,7 +623,7 @@ impl<'test> TestCx<'test> { .arg("-Zno-codegen") .arg("--out-dir") .arg(&out_dir) - .arg(&format!("--target={}", target)) + .arg(&format!("--target={target}")) .arg("-L") .arg(&self.config.build_base) .arg("-L") @@ -718,7 +718,7 @@ impl<'test> TestCx<'test> { // Set breakpoints on every line that contains the string "#break" let source_file_name = self.testpaths.file.file_name().unwrap().to_string_lossy(); for line in &breakpoint_lines { - script_str.push_str(&format!("bp `{}:{}`\n", source_file_name, line)); + script_str.push_str(&format!("bp `{source_file_name}:{line}`\n")); } // Append the other `cdb-command:`s @@ -818,7 +818,7 @@ impl<'test> TestCx<'test> { // write debugger script let mut script_str = String::with_capacity(2048); script_str.push_str(&format!("set charset {}\n", Self::charset())); - script_str.push_str(&format!("set sysroot {}\n", tool_path)); + script_str.push_str(&format!("set sysroot {tool_path}\n")); script_str.push_str(&format!("file {}\n", exe_file.to_str().unwrap())); script_str.push_str("target remote :5039\n"); script_str.push_str(&format!( @@ -848,12 +848,12 @@ impl<'test> TestCx<'test> { .arg(&exe_file) .arg(&self.config.adb_test_dir) .status() - .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path)); + .unwrap_or_else(|_| panic!("failed to exec `{adb_path:?}`")); Command::new(adb_path) .args(&["forward", "tcp:5039", "tcp:5039"]) .status() - .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path)); + .unwrap_or_else(|_| panic!("failed to exec `{adb_path:?}`")); let adb_arg = format!( "export LD_LIBRARY_PATH={}; \ @@ -870,7 +870,7 @@ impl<'test> TestCx<'test> { .stdout(Stdio::piped()) .stderr(Stdio::inherit()) .spawn() - .unwrap_or_else(|_| panic!("failed to exec `{:?}`", adb_path)); + .unwrap_or_else(|_| panic!("failed to exec `{adb_path:?}`")); // Wait for the gdbserver to print out "Listening on port ..." // at which point we know that it's started and then we can @@ -895,12 +895,12 @@ impl<'test> TestCx<'test> { let Output { status, stdout, stderr } = Command::new(&gdb_path) .args(debugger_opts) .output() - .unwrap_or_else(|_| panic!("failed to exec `{:?}`", gdb_path)); + .unwrap_or_else(|_| panic!("failed to exec `{gdb_path:?}`")); let cmdline = { let mut gdb = Command::new(&format!("{}-gdb", self.config.target)); gdb.args(debugger_opts); let cmdline = self.make_cmdline(&gdb, ""); - logv(self.config, format!("executing {}", cmdline)); + logv(self.config, format!("executing {cmdline}")); cmdline }; @@ -926,7 +926,7 @@ impl<'test> TestCx<'test> { match self.config.gdb_version { Some(version) => { - println!("NOTE: compiletest thinks it is using GDB version {}", version); + println!("NOTE: compiletest thinks it is using GDB version {version}"); if version > extract_gdb_version("7.4").unwrap() { // Add the directory containing the pretty printers to @@ -1040,7 +1040,7 @@ impl<'test> TestCx<'test> { match self.config.lldb_version { Some(ref version) => { - println!("NOTE: compiletest thinks it is using LLDB version {}", version); + println!("NOTE: compiletest thinks it is using LLDB version {version}"); } _ => { println!( @@ -1112,7 +1112,7 @@ impl<'test> TestCx<'test> { script_str.push_str("--category Rust\n"); for type_regex in rust_type_regexes { script_str.push_str("type summary add -F lldb_lookup.summary_lookup -e -x -h "); - script_str.push_str(&format!("'{}' ", type_regex)); + script_str.push_str(&format!("'{type_regex}' ")); script_str.push_str("--category Rust\n"); } script_str.push_str("type category enable Rust\n"); @@ -1183,7 +1183,7 @@ impl<'test> TestCx<'test> { }; self.dump_output(&out, &err); - ProcRes { status, stdout: out, stderr: err, cmdline: format!("{:?}", cmd) } + ProcRes { status, stdout: out, stderr: err, cmdline: format!("{cmd:?}") } } fn cleanup_debug_info_options(&self, options: &Option) -> Option { @@ -1266,7 +1266,7 @@ impl<'test> TestCx<'test> { ); } else { for pattern in missing_patterns { - self.error(&format!("error pattern '{}' not found!", pattern)); + self.error(&format!("error pattern '{pattern}' not found!")); } self.fatal_proc_rec("multiple error patterns not found", proc_res); } @@ -1297,7 +1297,7 @@ impl<'test> TestCx<'test> { Ok(re) => re, Err(err) => { self.fatal_proc_rec( - &format!("invalid regex error pattern '{}': {:?}", pattern, err), + &format!("invalid regex error pattern '{pattern}': {err:?}"), proc_res, ); } @@ -1426,10 +1426,10 @@ impl<'test> TestCx<'test> { )); println!("status: {}\ncommand: {}", proc_res.status, proc_res.cmdline); if !unexpected.is_empty() { - println!("unexpected errors (from JSON output): {:#?}\n", unexpected); + println!("unexpected errors (from JSON output): {unexpected:#?}\n"); } if !not_found.is_empty() { - println!("not found errors (from test file): {:#?}\n", not_found); + println!("not found errors (from test file): {not_found:#?}\n"); } panic!(); } @@ -1550,7 +1550,7 @@ impl<'test> TestCx<'test> { } if let Some(ref linker) = self.config.linker { - rustdoc.arg(format!("-Clinker={}", linker)); + rustdoc.arg(format!("-Clinker={linker}")); } self.compose_and_run_compiler(rustdoc, None) @@ -1695,7 +1695,7 @@ impl<'test> TestCx<'test> { let is_dylib = self.build_auxiliary(&aux_path, &aux_dir); let lib_name = get_lib_name(&aux_path.trim_end_matches(".rs").replace('-', "_"), is_dylib); - rustc.arg("--extern").arg(format!("{}={}/{}", aux_name, aux_dir.display(), lib_name)); + rustc.arg("--extern").arg(format!("{aux_name}={}/{lib_name}", aux_dir.display())); } aux_dir @@ -1818,7 +1818,7 @@ impl<'test> TestCx<'test> { ) -> ProcRes { let cmdline = { let cmdline = self.make_cmdline(&command, lib_path); - logv(self.config, format!("executing {}", cmdline)); + logv(self.config, format!("executing {cmdline}")); cmdline }; @@ -1889,7 +1889,7 @@ impl<'test> TestCx<'test> { let target = if self.props.force_host { &*self.config.host } else { &*self.config.target }; - rustc.arg(&format!("--target={}", target)); + rustc.arg(&format!("--target={target}")); } self.set_revision_flags(&mut rustc); @@ -1963,7 +1963,7 @@ impl<'test> TestCx<'test> { "-Zmir-pretty-relative-line-numbers=yes", ]); if let Some(pass) = &self.props.mir_unit_test { - rustc.args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]); + rustc.args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{pass}")]); } else { rustc.arg("-Zmir-opt-level=4"); } @@ -2046,7 +2046,7 @@ impl<'test> TestCx<'test> { ); if !is_rustdoc { if let Some(ref linker) = self.config.linker { - rustc.arg(format!("-Clinker={}", linker)); + rustc.arg(format!("-Clinker={linker}")); } } } @@ -2142,7 +2142,7 @@ impl<'test> TestCx<'test> { // Linux and mac don't require adjusting the library search path if cfg!(unix) { - format!("{:?}", command) + format!("{command:?}") } else { // Build the LD_LIBRARY_PATH variable as it would be seen on the command line // for diagnostic purposes @@ -2150,15 +2150,15 @@ impl<'test> TestCx<'test> { format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path)) } - format!("{} {:?}", lib_path_cmd_prefix(libpath), command) + format!("{} {command:?}", lib_path_cmd_prefix(libpath)) } } fn dump_output(&self, out: &str, err: &str) { - let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() }; + let revision = if let Some(r) = self.revision { format!("{r}.") } else { String::new() }; - self.dump_output_file(out, &format!("{}out", revision)); - self.dump_output_file(err, &format!("{}err", revision)); + self.dump_output_file(out, &format!("{revision}out")); + self.dump_output_file(err, &format!("{revision}err")); self.maybe_dump_to_stdout(out, err); } @@ -2209,17 +2209,17 @@ impl<'test> TestCx<'test> { fn maybe_dump_to_stdout(&self, out: &str, err: &str) { if self.config.verbose { println!("------stdout------------------------------"); - println!("{}", out); + println!("{out}"); println!("------stderr------------------------------"); - println!("{}", err); + println!("{err}"); println!("------------------------------------------"); } } fn error(&self, err: &str) { match self.revision { - Some(rev) => println!("\nerror in revision `{}`: {}", rev, err), - None => println!("\nerror: {}", err), + Some(rev) => println!("\nerror in revision `{rev}`: {err}"), + None => println!("\nerror: {err}"), } } @@ -2297,9 +2297,9 @@ impl<'test> TestCx<'test> { let prefix_for_target = if self.config.target.contains("msvc") { "MSVC" } else { "NONMSVC" }; let prefixes = if let Some(rev) = self.revision { - format!("CHECK,{},{}", prefix_for_target, rev) + format!("CHECK,{prefix_for_target},{rev}") } else { - format!("CHECK,{}", prefix_for_target) + format!("CHECK,{prefix_for_target}") }; if self.config.llvm_version.unwrap_or(0) >= 130000 { filecheck.args(&["--allow-unused-prefixes", "--check-prefixes", &prefixes]); @@ -2480,7 +2480,7 @@ impl<'test> TestCx<'test> { if let Some(pager) = pager { let pager = pager.trim(); if self.config.verbose { - eprintln!("using pager {}", pager); + eprintln!("using pager {pager}"); } let output = Command::new(pager) // disable paging; we want this to be non-interactive @@ -2507,7 +2507,7 @@ impl<'test> TestCx<'test> { match diff.read_until(b'\n', &mut line) { Ok(0) => break, Ok(_) => {} - Err(e) => eprintln!("ERROR: {:?}", e), + Err(e) => eprintln!("ERROR: {e:?}"), } match String::from_utf8(line.clone()) { Ok(line) => { @@ -2627,7 +2627,7 @@ impl<'test> TestCx<'test> { ); for other_file in other_files { let mut path = self.testpaths.file.clone(); - path.set_file_name(&format!("{}.rs", other_file)); + path.set_file_name(&format!("{other_file}.rs")); files.insert( path.strip_prefix(&cwd).unwrap_or(&path).to_str().unwrap().replace('\\', "/"), self.get_lines(&path, None), @@ -2654,7 +2654,7 @@ impl<'test> TestCx<'test> { v.remove(pos); } else { self.fatal_proc_rec( - &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v), + &format!("Not found doc test: \"{s}\" in \"{path}\":{v:?}"), &res, ); } @@ -2662,7 +2662,7 @@ impl<'test> TestCx<'test> { } }) {} if tested == 0 { - self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res); + self.fatal_proc_rec(&format!("No test has been found... {files:?}"), &res); } else { for (entry, v) in &files { if !v.is_empty() { @@ -2736,7 +2736,7 @@ impl<'test> TestCx<'test> { println!("\nThese items should have been contained but were not:\n"); for item in &missing { - println!("{}", item); + println!("{item}"); } println!("\n"); @@ -2752,7 +2752,7 @@ impl<'test> TestCx<'test> { println!("\nThese items were contained but should not have been:\n"); for item in sorted { - println!("{}", item); + println!("{item}"); } println!("\n"); @@ -2785,7 +2785,7 @@ impl<'test> TestCx<'test> { fn str_to_mono_item(s: &str, cgu_has_crate_disambiguator: bool) -> MonoItem { let s = if s.starts_with(PREFIX) { (&s[PREFIX.len()..]).trim() } else { s.trim() }; - let full_string = format!("{}{}", PREFIX, s); + let full_string = format!("{PREFIX}{s}"); let parts: Vec<&str> = s.split(CGU_MARKER).map(str::trim).filter(|s| !s.is_empty()).collect(); @@ -2838,7 +2838,7 @@ impl<'test> TestCx<'test> { } let captures = - RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {}", cgu)); + RE.captures(cgu).unwrap_or_else(|| panic!("invalid cgu name encountered: {cgu}")); let mut new_name = cgu.to_owned(); @@ -2911,7 +2911,7 @@ impl<'test> TestCx<'test> { assert!(incremental_dir.exists(), "init_incremental_test failed to create incremental dir"); if self.config.verbose { - print!("revision={:?} props={:#?}", revision, self.props); + print!("revision={revision:?} props={:#?}", self.props); } if revision.starts_with("rpass") { @@ -3049,8 +3049,8 @@ impl<'test> TestCx<'test> { cmd.env("IS_MSVC", "1") .env("IS_WINDOWS", "1") .env("MSVC_LIB", format!("'{}' -nologo", lib.display())) - .env("CC", format!("'{}' {}", self.config.cc, cflags)) - .env("CXX", format!("'{}' {}", &self.config.cxx, cxxflags)); + .env("CC", format!("'{}' {cflags}", self.config.cc)) + .env("CXX", format!("'{}' {cxxflags}", &self.config.cxx)); } else { cmd.env("CC", format!("{} {}", self.config.cc, self.config.cflags)) .env("CXX", format!("{} {}", self.config.cxx, self.config.cxxflags)) @@ -3067,7 +3067,7 @@ impl<'test> TestCx<'test> { status: output.status, stdout: String::from_utf8_lossy(&output.stdout).into_owned(), stderr: String::from_utf8_lossy(&output.stderr).into_owned(), - cmdline: format!("{:?}", cmd), + cmdline: format!("{cmd:?}"), }; self.fatal_proc_rec("make failed", &res); } @@ -3265,8 +3265,8 @@ impl<'test> TestCx<'test> { .unwrap(); let fixed_code = apply_suggestions(&unfixed_code, &suggestions).unwrap_or_else(|e| { panic!( - "failed to apply suggestions for {:?} with rustfix: {}", - self.testpaths.file, e + "failed to apply suggestions for {:?} with rustfix: {e}", + self.testpaths.file ) }); @@ -3287,7 +3287,7 @@ impl<'test> TestCx<'test> { relative_path_to_file.display(), ); self.fatal_proc_rec( - &format!("{} errors occurred comparing output.", errors), + &format!("{errors} errors occurred comparing output."), &proc_res, ); } @@ -3303,7 +3303,7 @@ impl<'test> TestCx<'test> { }; if run_output_errors > 0 { self.fatal_proc_rec( - &format!("{} errors occurred comparing run output.", run_output_errors), + &format!("{run_output_errors} errors occurred comparing run output."), &proc_res, ); } @@ -3409,12 +3409,12 @@ impl<'test> TestCx<'test> { if self.config.bless { for e in - glob(&format!("{}/{}.*{}.mir", test_dir.display(), test_crate, bit_width)).unwrap() + glob(&format!("{}/{test_crate}.*{bit_width}.mir", test_dir.display())).unwrap() { std::fs::remove_file(e.unwrap()).unwrap(); } for e in - glob(&format!("{}/{}.*{}.diff", test_dir.display(), test_crate, bit_width)).unwrap() + glob(&format!("{}/{test_crate}.*{bit_width}.diff", test_dir.display())).unwrap() { std::fs::remove_file(e.unwrap()).unwrap(); } @@ -3432,9 +3432,9 @@ impl<'test> TestCx<'test> { if test_name.ends_with(".diff") { let trimmed = test_name.trim_end_matches(".diff"); - let test_against = format!("{}.after.mir", trimmed); - from_file = format!("{}.before.mir", trimmed); - expected_file = format!("{}{}.diff", trimmed, bit_width); + let test_against = format!("{trimmed}.after.mir"); + from_file = format!("{trimmed}.before.mir"); + expected_file = format!("{trimmed}{bit_width}.diff"); assert!( test_names.next().is_none(), "two mir pass names specified for MIR diff" @@ -3447,9 +3447,9 @@ impl<'test> TestCx<'test> { "three mir pass names specified for MIR diff" ); expected_file = - format!("{}{}.{}-{}.diff", test_name, bit_width, first_pass, second_pass); - let second_file = format!("{}.{}.mir", test_name, second_pass); - from_file = format!("{}.{}.mir", test_name, first_pass); + format!("{test_name}{bit_width}.{first_pass}-{second_pass}.diff"); + let second_file = format!("{test_name}.{second_pass}.mir"); + from_file = format!("{test_name}.{first_pass}.mir"); to_file = Some(second_file); } else { let ext_re = Regex::new(r#"(\.(mir|dot|html))$"#).unwrap(); @@ -3472,7 +3472,7 @@ impl<'test> TestCx<'test> { to_file = None; }; if !expected_file.starts_with(&test_crate) { - expected_file = format!("{}.{}", test_crate, expected_file); + expected_file = format!("{test_crate}.{expected_file}"); } let expected_file = test_dir.join(expected_file); @@ -3545,9 +3545,9 @@ impl<'test> TestCx<'test> { for result in diff::lines(&before, &after) { use std::fmt::Write; match result { - diff::Result::Left(s) => writeln!(dumped_string, "- {}", s).unwrap(), - diff::Result::Right(s) => writeln!(dumped_string, "+ {}", s).unwrap(), - diff::Result::Both(s, _) => writeln!(dumped_string, " {}", s).unwrap(), + diff::Result::Left(s) => writeln!(dumped_string, "- {s}").unwrap(), + diff::Result::Right(s) => writeln!(dumped_string, "+ {s}").unwrap(), + diff::Result::Both(s, _) => writeln!(dumped_string, " {s}").unwrap(), } } dumped_string @@ -3758,7 +3758,7 @@ impl<'test> TestCx<'test> { fn load_expected_output_from_path(&self, path: &Path) -> Result { fs::read_to_string(path).map_err(|err| { - format!("failed to load expected output from `{}`: {}", path.display(), err) + format!("failed to load expected output from `{}`: {err}", path.display()) }) } @@ -3768,7 +3768,7 @@ impl<'test> TestCx<'test> { return; } if let Err(e) = fs::remove_file(file) { - self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,)); + self.fatal(&format!("failed to delete `{}`: {e}", file.display(),)); } } @@ -3779,9 +3779,9 @@ impl<'test> TestCx<'test> { if !self.config.bless { if expected.is_empty() { - println!("normalized {}:\n{}\n", kind, actual); + println!("normalized {kind}:\n{actual}\n"); } else { - println!("diff of {}:\n", kind); + println!("diff of {kind}:\n"); print!("{}", write_diff(expected, actual, 3)); } } @@ -3823,9 +3823,9 @@ impl<'test> TestCx<'test> { } } - println!("\nThe actual {0} differed from the expected {0}.", kind); + println!("\nThe actual {kind} differed from the expected {kind}."); for output_file in files { - println!("Actual {} saved to {}", kind, output_file.display()); + println!("Actual {kind} saved to {}", output_file.display()); } if self.config.bless { 0 } else { 1 } } @@ -3866,7 +3866,7 @@ impl<'test> TestCx<'test> { // We do this wether we bless or not (_, true, false) => { self.fatal_proc_rec( - &format!("`{}` should not have different output from base test!", kind), + &format!("`{kind}` should not have different output from base test!"), proc_res, ); } @@ -3928,7 +3928,7 @@ impl ProcRes { pub fn fatal(&self, err: Option<&str>, on_failure: impl FnOnce()) -> ! { if let Some(e) = err { - println!("\nerror: {}", e); + println!("\nerror: {e}"); } self.print_info(); on_failure(); diff --git a/src/tools/compiletest/src/runtest/debugger.rs b/src/tools/compiletest/src/runtest/debugger.rs index 379ff0bab408a..2810f10cd6aab 100644 --- a/src/tools/compiletest/src/runtest/debugger.rs +++ b/src/tools/compiletest/src/runtest/debugger.rs @@ -21,7 +21,7 @@ impl DebuggerCommands { ) -> Result { let directives = debugger_prefixes .iter() - .map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix))) + .map(|prefix| (format!("{prefix}-command"), format!("{prefix}-check"))) .collect::>(); let mut breakpoint_lines = vec![]; @@ -55,7 +55,7 @@ impl DebuggerCommands { .map(|cmd| check_lines.push(cmd)); } } - Err(e) => return Err(format!("Error while parsing debugger commands: {}", e)), + Err(e) => return Err(format!("Error while parsing debugger commands: {e}")), } } diff --git a/src/tools/compiletest/src/util.rs b/src/tools/compiletest/src/util.rs index e5ff0906be8a5..48dfeb5a49010 100644 --- a/src/tools/compiletest/src/util.rs +++ b/src/tools/compiletest/src/util.rs @@ -73,7 +73,7 @@ pub fn make_new_path(path: &str) -> String { // Windows just uses PATH as the library search path, so we have to // maintain the current value while adding our own match env::var(lib_path_env_var()) { - Ok(curr) => format!("{}{}{}", path, path_div(), curr), + Ok(curr) => format!("{path}{}{curr}", path_div()), Err(..) => path.to_owned(), } } @@ -88,7 +88,7 @@ fn path_div() -> &'static str { pub fn logv(config: &Config, s: String) { debug!("{}", s); if config.verbose { - println!("{}", s); + println!("{s}"); } } diff --git a/src/tools/expand-yaml-anchors/src/main.rs b/src/tools/expand-yaml-anchors/src/main.rs index 8992d165d5d50..70af05c285728 100644 --- a/src/tools/expand-yaml-anchors/src/main.rs +++ b/src/tools/expand-yaml-anchors/src/main.rs @@ -150,11 +150,11 @@ fn filter_document(document: Yaml) -> Yaml { fn main() { if let Err(err) = App::from_args().and_then(|app| app.run()) { - eprintln!("error: {}", err); + eprintln!("error: {err}"); let mut source = err.as_ref() as &dyn Error; while let Some(err) = source.source() { - eprintln!("caused by: {}", err); + eprintln!("caused by: {err}"); source = err; } diff --git a/src/tools/html-checker/main.rs b/src/tools/html-checker/main.rs index 9b4d2c5259806..a600dcda47bce 100644 --- a/src/tools/html-checker/main.rs +++ b/src/tools/html-checker/main.rs @@ -46,7 +46,7 @@ fn check_html_file(file: &Path) -> usize { file.display(), status.code().unwrap_or(-1) ); - eprintln!("{}", stderr); + eprintln!("{stderr}"); stderr.lines().count() } } @@ -115,9 +115,9 @@ fn main() -> Result<(), String> { println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); - println!("Done! Read {} files...", files_read); + println!("Done! Read {files_read} files..."); if errors > 0 { - Err(format!("HTML check failed: {} errors", errors)) + Err(format!("HTML check failed: {errors} errors")) } else { println!("No error found!"); Ok(()) diff --git a/src/tools/jsondocck/src/config.rs b/src/tools/jsondocck/src/config.rs index 9b3ba3f3fbe39..ee4d3e7d01de9 100644 --- a/src/tools/jsondocck/src/config.rs +++ b/src/tools/jsondocck/src/config.rs @@ -17,7 +17,7 @@ pub fn parse_config(args: Vec) -> Config { let (argv0, args_) = args.split_first().unwrap(); if args.len() == 1 { - let message = format!("Usage: {}