style: simplify string formatting for readability (#6316)

This commit is contained in:
Hamir Mahal 2024-09-24 20:40:53 -07:00 committed by GitHub
parent fc2fd95a98
commit 8e787eb70a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 59 additions and 71 deletions

View File

@ -39,7 +39,7 @@ impl DeviceState {
let adapter_info = adapter.get_info(); let adapter_info = adapter.get_info();
eprintln!("{:?}", adapter_info); eprintln!("{adapter_info:?}");
let (device, queue) = block_on(adapter.request_device( let (device, queue) = block_on(adapter.request_device(
&wgpu::DeviceDescriptor { &wgpu::DeviceDescriptor {

View File

@ -40,7 +40,7 @@ impl Inputs {
_ => continue, _ => continue,
}, },
Err(e) => { Err(e) => {
eprintln!("Skipping file: {:?}", e); eprintln!("Skipping file: {e:?}");
continue; continue;
} }
} }

View File

@ -201,7 +201,7 @@ fn print_unknown_example(_result: Option<String>) {}
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
fn print_unknown_example(result: Option<String>) { fn print_unknown_example(result: Option<String>) {
if let Some(example) = result { if let Some(example) = result {
println!("Unknown example: {}", example); println!("Unknown example: {example}");
} else { } else {
println!("Please specify an example as the first argument!"); println!("Please specify an example as the first argument!");
} }

View File

@ -227,7 +227,7 @@ async fn run() {
let queries = submit_render_and_compute_pass_with_queries(&device, &queue); let queries = submit_render_and_compute_pass_with_queries(&device, &queue);
let raw_results = queries.wait_for_results(&device); let raw_results = queries.wait_for_results(&device);
println!("Raw timestamp buffer contents: {:?}", raw_results); println!("Raw timestamp buffer contents: {raw_results:?}");
QueryResults::from_raw_results(raw_results, timestamps_inside_passes).print(&queue); QueryResults::from_raw_results(raw_results, timestamps_inside_passes).print(&queue);
} }

View File

@ -853,7 +853,7 @@ fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> {
Ok(parsed) => parsed, Ok(parsed) => parsed,
Err(error) => { Err(error) => {
invalid.push(input_path.clone()); invalid.push(input_path.clone());
eprintln!("Error validating {}:", input_path); eprintln!("Error validating {input_path}:");
eprintln!("{error}"); eprintln!("{error}");
continue; continue;
} }
@ -866,7 +866,7 @@ fn bulk_validate(args: Args, params: &Parameters) -> anyhow::Result<()> {
if let Err(error) = validator.validate(&module) { if let Err(error) = validator.validate(&module) {
invalid.push(input_path.clone()); invalid.push(input_path.clone());
eprintln!("Error validating {}:", input_path); eprintln!("Error validating {input_path}:");
if let Some(input) = &input_text { if let Some(input) = &input_text {
let filename = path.file_name().and_then(std::ffi::OsStr::to_str); let filename = path.file_name().and_then(std::ffi::OsStr::to_str);
emit_annotated_error(&error, filename.unwrap_or("input"), input); emit_annotated_error(&error, filename.unwrap_or("input"), input);

View File

@ -698,7 +698,7 @@ fn write_function_expressions(
E::RayQueryGetIntersection { query, committed } => { E::RayQueryGetIntersection { query, committed } => {
edges.insert("", query); edges.insert("", query);
let ty = if committed { "Committed" } else { "Candidate" }; let ty = if committed { "Committed" } else { "Candidate" };
(format!("rayQueryGet{}Intersection", ty).into(), 4) (format!("rayQueryGet{ty}Intersection").into(), 4)
} }
E::SubgroupBallotResult => ("SubgroupBallotResult".into(), 4), E::SubgroupBallotResult => ("SubgroupBallotResult".into(), 4),
E::SubgroupOperationResult { .. } => ("SubgroupOperationResult".into(), 4), E::SubgroupOperationResult { .. } => ("SubgroupOperationResult".into(), 4),

View File

@ -2645,15 +2645,15 @@ impl<'a, W: Write> Writer<'a, W> {
match literal { match literal {
// Floats are written using `Debug` instead of `Display` because it always appends the // Floats are written using `Debug` instead of `Display` because it always appends the
// decimal part even it's zero which is needed for a valid glsl float constant // decimal part even it's zero which is needed for a valid glsl float constant
crate::Literal::F64(value) => write!(self.out, "{:?}LF", value)?, crate::Literal::F64(value) => write!(self.out, "{value:?}LF")?,
crate::Literal::F32(value) => write!(self.out, "{:?}", value)?, crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
// Unsigned integers need a `u` at the end // Unsigned integers need a `u` at the end
// //
// While `core` doesn't necessarily need it, it's allowed and since `es` needs it we // While `core` doesn't necessarily need it, it's allowed and since `es` needs it we
// always write it as the extra branch wouldn't have any benefit in readability // always write it as the extra branch wouldn't have any benefit in readability
crate::Literal::U32(value) => write!(self.out, "{}u", value)?, crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => write!(self.out, "{}", value)?, crate::Literal::I32(value) => write!(self.out, "{value}")?,
crate::Literal::Bool(value) => write!(self.out, "{}", value)?, crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::I64(_) => { crate::Literal::I64(_) => {
return Err(Error::Custom("GLSL has no 64-bit integer type".into())); return Err(Error::Custom("GLSL has no 64-bit integer type".into()));
} }
@ -4614,7 +4614,7 @@ impl<'a, W: Write> Writer<'a, W> {
for i in 0..count.get() { for i in 0..count.get() {
// Add the array accessor and recurse. // Add the array accessor and recurse.
segments.push(format!("[{}]", i)); segments.push(format!("[{i}]"));
self.collect_push_constant_items(base, segments, layouter, offset, items); self.collect_push_constant_items(base, segments, layouter, offset, items);
segments.pop(); segments.pop();
} }

View File

@ -1046,8 +1046,7 @@ impl<'a, W: Write> super::Writer<'a, W> {
} }
ref other => { ref other => {
return Err(super::Error::Unimplemented(format!( return Err(super::Error::Unimplemented(format!(
"Array length of base {:?}", "Array length of base {other:?}"
other
))) )))
} }
}; };

View File

@ -350,7 +350,7 @@ impl<W: fmt::Write> super::Writer<'_, W> {
self.write_store_value(module, &value, func_ctx)?; self.write_store_value(module, &value, func_ctx)?;
writeln!(self.out, "));")?; writeln!(self.out, "));")?;
} else { } else {
write!(self.out, "{}{}.Store(", level, var_name)?; write!(self.out, "{level}{var_name}.Store(")?;
self.write_storage_address(module, &chain, func_ctx)?; self.write_storage_address(module, &chain, func_ctx)?;
write!(self.out, ", ")?; write!(self.out, ", ")?;
self.write_store_value(module, &value, func_ctx)?; self.write_store_value(module, &value, func_ctx)?;

View File

@ -965,7 +965,7 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
let constant = &module.constants[handle]; let constant = &module.constants[handle];
self.write_type(module, constant.ty)?; self.write_type(module, constant.ty)?;
let name = &self.names[&NameKey::Constant(handle)]; let name = &self.names[&NameKey::Constant(handle)];
write!(self.out, " {}", name)?; write!(self.out, " {name}")?;
// Write size for array type // Write size for array type
if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner { if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner {
self.write_array_size(module, base, size)?; self.write_array_size(module, base, size)?;
@ -2383,11 +2383,11 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
// decimal part even it's zero // decimal part even it's zero
crate::Literal::F64(value) => write!(self.out, "{value:?}L")?, crate::Literal::F64(value) => write!(self.out, "{value:?}L")?,
crate::Literal::F32(value) => write!(self.out, "{value:?}")?, crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
crate::Literal::U32(value) => write!(self.out, "{}u", value)?, crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => write!(self.out, "{}", value)?, crate::Literal::I32(value) => write!(self.out, "{value}")?,
crate::Literal::U64(value) => write!(self.out, "{}uL", value)?, crate::Literal::U64(value) => write!(self.out, "{value}uL")?,
crate::Literal::I64(value) => write!(self.out, "{}L", value)?, crate::Literal::I64(value) => write!(self.out, "{value}L")?,
crate::Literal::Bool(value) => write!(self.out, "{}", value)?, crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => { crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
return Err(Error::Custom( return Err(Error::Custom(
"Abstract types should not appear in IR presented to backends".into(), "Abstract types should not appear in IR presented to backends".into(),

View File

@ -437,8 +437,7 @@ impl Options {
}) })
} }
LocationMode::Uniform => Err(Error::GenericValidation(format!( LocationMode::Uniform => Err(Error::GenericValidation(format!(
"Unexpected Binding::Location({}) for the Uniform mode", "Unexpected Binding::Location({location}) for the Uniform mode"
location
))), ))),
}, },
} }

View File

@ -3820,12 +3820,11 @@ impl<W: Write> Writer<W> {
writeln!(self.out)?; writeln!(self.out)?;
writeln!( writeln!(
self.out, self.out,
"{} {defined_func_name}({arg_type_name} arg) {{ "{struct_name} {defined_func_name}({arg_type_name} arg) {{
{other_type_name} other; {other_type_name} other;
{arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other); {arg_type_name} fract = {NAMESPACE}::{called_func_name}(arg, other);
return {}{{ fract, other }}; return {struct_name}{{ fract, other }};
}}", }}"
struct_name, struct_name
)?; )?;
} }
&crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} &crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {}

View File

@ -1221,31 +1221,31 @@ impl<W: Write> Writer<W> {
match expressions[expr] { match expressions[expr] {
Expression::Literal(literal) => match literal { Expression::Literal(literal) => match literal {
crate::Literal::F32(value) => write!(self.out, "{}f", value)?, crate::Literal::F32(value) => write!(self.out, "{value}f")?,
crate::Literal::U32(value) => write!(self.out, "{}u", value)?, crate::Literal::U32(value) => write!(self.out, "{value}u")?,
crate::Literal::I32(value) => { crate::Literal::I32(value) => {
// `-2147483648i` is not valid WGSL. The most negative `i32` // `-2147483648i` is not valid WGSL. The most negative `i32`
// value can only be expressed in WGSL using AbstractInt and // value can only be expressed in WGSL using AbstractInt and
// a unary negation operator. // a unary negation operator.
if value == i32::MIN { if value == i32::MIN {
write!(self.out, "i32({})", value)?; write!(self.out, "i32({value})")?;
} else { } else {
write!(self.out, "{}i", value)?; write!(self.out, "{value}i")?;
} }
} }
crate::Literal::Bool(value) => write!(self.out, "{}", value)?, crate::Literal::Bool(value) => write!(self.out, "{value}")?,
crate::Literal::F64(value) => write!(self.out, "{:?}lf", value)?, crate::Literal::F64(value) => write!(self.out, "{value:?}lf")?,
crate::Literal::I64(value) => { crate::Literal::I64(value) => {
// `-9223372036854775808li` is not valid WGSL. The most negative `i64` // `-9223372036854775808li` is not valid WGSL. The most negative `i64`
// value can only be expressed in WGSL using AbstractInt and // value can only be expressed in WGSL using AbstractInt and
// a unary negation operator. // a unary negation operator.
if value == i64::MIN { if value == i64::MIN {
write!(self.out, "i64({})", value)?; write!(self.out, "i64({value})")?;
} else { } else {
write!(self.out, "{}li", value)?; write!(self.out, "{value}li")?;
} }
} }
crate::Literal::U64(value) => write!(self.out, "{:?}lu", value)?, crate::Literal::U64(value) => write!(self.out, "{value:?}lu")?,
crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => { crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
return Err(Error::Custom( return Err(Error::Custom(
"Abstract types should not appear in IR presented to backends".into(), "Abstract types should not appear in IR presented to backends".into(),

View File

@ -790,11 +790,11 @@ impl<'a> Error<'a> {
Error::ConcretizationFailed(ref error) => { Error::ConcretizationFailed(ref error) => {
let ConcretizationFailedError { expr_span, ref expr_type, ref scalar, ref inner } = **error; let ConcretizationFailedError { expr_span, ref expr_type, ref scalar, ref inner } = **error;
ParseError { ParseError {
message: format!("failed to convert expression to a concrete type: {}", inner), message: format!("failed to convert expression to a concrete type: {inner}"),
labels: vec![ labels: vec![
( (
expr_span, expr_span,
format!("this expression has type {}", expr_type).into(), format!("this expression has type {expr_type}").into(),
) )
], ],
notes: vec![ notes: vec![

View File

@ -91,7 +91,7 @@ fn main() {
Some(queue_id), Some(queue_id),
); );
if let Err(e) = res { if let Err(e) = res {
panic!("{:?}", e); panic!("{e:?}");
} }
(device_id, queue_id) (device_id, queue_id)
} }

View File

@ -237,7 +237,7 @@ impl GlobalPlay for wgc::global::Global {
let module = ron::de::from_str(&code).unwrap(); let module = ron::de::from_str(&code).unwrap();
wgc::pipeline::ShaderModuleSource::Naga(module) wgc::pipeline::ShaderModuleSource::Naga(module)
} else { } else {
panic!("Unknown shader {}", data); panic!("Unknown shader {data}");
}; };
let (_, error) = self.device_create_shader_module(device, &desc, source, Some(id)); let (_, error) = self.device_create_shader_module(device, &desc, source, Some(id));
if let Some(e) = error { if let Some(e) = error {

View File

@ -58,7 +58,7 @@ struct Test<'a> {
fn map_callback(status: Result<(), wgc::resource::BufferAccessError>) { fn map_callback(status: Result<(), wgc::resource::BufferAccessError>) {
if let Err(e) = status { if let Err(e) = status {
panic!("Buffer map error: {}", e); panic!("Buffer map error: {e}");
} }
} }
@ -88,7 +88,7 @@ impl Test<'_> {
.iter() .iter()
.map(|feature| { .map(|feature| {
wgt::Features::from_name(feature) wgt::Features::from_name(feature)
.unwrap_or_else(|| panic!("Invalid feature flag {}", feature)) .unwrap_or_else(|| panic!("Invalid feature flag {feature}"))
}) })
.fold(wgt::Features::empty(), |a, b| a | b); .fold(wgt::Features::empty(), |a, b| a | b);
Test { Test {
@ -120,7 +120,7 @@ impl Test<'_> {
Some(queue_id), Some(queue_id),
); );
if let Err(e) = res { if let Err(e) = res {
panic!("{:?}", e); panic!("{e:?}");
} }
let mut command_buffer_id_manager = wgc::identity::IdentityManager::new(); let mut command_buffer_id_manager = wgc::identity::IdentityManager::new();
@ -186,8 +186,7 @@ impl Test<'_> {
if &expected_data[..] != contents { if &expected_data[..] != contents {
panic!( panic!(
"Test expectation is not met!\nBuffer content was:\n{:?}\nbut expected:\n{:?}", "Test expectation is not met!\nBuffer content was:\n{contents:?}\nbut expected:\n{expected_data:?}"
contents, expected_data
); );
} }
} }
@ -209,7 +208,7 @@ const BACKENDS: &[wgt::Backend] = &[
impl Corpus { impl Corpus {
fn run_from(path: PathBuf) { fn run_from(path: PathBuf) {
println!("Corpus {:?}", path); println!("Corpus {path:?}");
let dir = path.parent().unwrap(); let dir = path.parent().unwrap();
let corpus: Corpus = ron::de::from_reader(File::open(&path).unwrap()).unwrap(); let corpus: Corpus = ron::de::from_reader(File::open(&path).unwrap()).unwrap();
@ -219,7 +218,7 @@ impl Corpus {
} }
let mut test_num = 0; let mut test_num = 0;
for test_path in &corpus.tests { for test_path in &corpus.tests {
println!("\t\tTest '{:?}'", test_path); println!("\t\tTest '{test_path:?}'");
let global = wgc::global::Global::new( let global = wgc::global::Global::new(
"test", "test",
@ -243,7 +242,7 @@ impl Corpus {
Err(_) => continue, Err(_) => continue,
}; };
println!("\tBackend {:?}", backend); println!("\tBackend {backend:?}");
let supported_features = global.adapter_features(adapter); let supported_features = global.adapter_features(adapter);
let downlevel_caps = global.adapter_downlevel_capabilities(adapter); let downlevel_caps = global.adapter_downlevel_capabilities(adapter);

View File

@ -188,11 +188,10 @@ pub async fn compare_image_output(
sanitize_for_path(&adapter_info.driver) sanitize_for_path(&adapter_info.driver)
); );
// Determine the paths to write out the various intermediate files // Determine the paths to write out the various intermediate files
let actual_path = Path::new(&path).with_file_name( let actual_path = Path::new(&path)
OsString::from_str(&format!("{}-{}-actual.png", file_stem, renderer)).unwrap(), .with_file_name(OsString::from_str(&format!("{file_stem}-{renderer}-actual.png")).unwrap());
);
let difference_path = Path::new(&path).with_file_name( let difference_path = Path::new(&path).with_file_name(
OsString::from_str(&format!("{}-{}-difference.png", file_stem, renderer,)).unwrap(), OsString::from_str(&format!("{file_stem}-{renderer}-difference.png",)).unwrap(),
); );
let mut all_passed; let mut all_passed;

View File

@ -151,7 +151,7 @@ impl TestInfo {
let names: ArrayVec<_, 4> = reasons.iter_names().map(|(name, _)| name).collect(); let names: ArrayVec<_, 4> = reasons.iter_names().map(|(name, _)| name).collect();
let names_text = names.join(" | "); let names_text = names.join(" | ");
format!("Skipped Failure: {}", names_text) format!("Skipped Failure: {names_text}")
} else if !unsupported_reasons.is_empty() { } else if !unsupported_reasons.is_empty() {
skip = true; skip = true;
format!("Unsupported: {}", unsupported_reasons.join(" | ")) format!("Unsupported: {}", unsupported_reasons.join(" | "))

View File

@ -123,10 +123,10 @@ static SUBGROUP_OPERATIONS: GpuTestConfiguration = GpuTestConfiguration::new()
.enumerate() .enumerate()
.filter(|(_, (r, e))| *r != e) .filter(|(_, (r, e))| *r != e)
{ {
write!(&mut msg, "thread {} failed tests:", thread).unwrap(); write!(&mut msg, "thread {thread} failed tests:").unwrap();
let difference = result ^ expected; let difference = result ^ expected;
for i in (0..u32::BITS).filter(|i| (difference & (1 << i)) != 0) { for i in (0..u32::BITS).filter(|i| (difference & (1 << i)) != 0) {
write!(&mut msg, " {},", i).unwrap(); write!(&mut msg, " {i},").unwrap();
} }
writeln!(&mut msg).unwrap(); writeln!(&mut msg).unwrap();
} }

View File

@ -352,10 +352,7 @@ async fn vertex_formats_common(ctx: TestingContext, tests: &[Test<'_>]) {
let mut deltas = data.iter().zip(expected.iter()).map(|(d, e)| (d - e).abs()); let mut deltas = data.iter().zip(expected.iter()).map(|(d, e)| (d - e).abs());
if deltas.any(|x| x > EPSILON) { if deltas.any(|x| x > EPSILON) {
eprintln!( eprintln!("Failed: Got: {data:?} Expected: {expected:?} - {case_name}",);
"Failed: Got: {:?} Expected: {:?} - {case_name}",
data, expected,
);
failed = true; failed = true;
continue; continue;
} }

View File

@ -471,10 +471,7 @@ async fn vertex_index_common(ctx: TestingContext) {
test.case, test.id_source, test.draw_call_kind, test.encoder_kind test.case, test.id_source, test.draw_call_kind, test.encoder_kind
); );
if data != expected { if data != expected {
eprintln!( eprintln!("Failed: Got: {data:?} Expected: {expected:?} - {case_name}",);
"Failed: Got: {:?} Expected: {:?} - {case_name}",
data, expected,
);
failed = true; failed = true;
} else { } else {
eprintln!("Passed: {case_name}"); eprintln!("Passed: {case_name}");

View File

@ -2538,8 +2538,7 @@ impl super::DeviceShared {
} }
None => { None => {
crate::hal_usage_error(format!( crate::hal_usage_error(format!(
"no signals reached value {}", "no signals reached value {wait_value}"
wait_value
)); ));
} }
} }

View File

@ -230,7 +230,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize
for format in TEXTURE_FORMAT_LIST { for format in TEXTURE_FORMAT_LIST {
let features = texture_format_features[&format]; let features = texture_format_features[&format];
let format_name = texture::texture_format_name(format); let format_name = texture::texture_format_name(format);
write!(output, "\t\t{format_name:>0$}", max_format_name_size)?; write!(output, "\t\t{format_name:>max_format_name_size$}")?;
for bit in wgpu::TextureUsages::all().iter() { for bit in wgpu::TextureUsages::all().iter() {
write!(output, "")?; write!(output, "")?;
if features.allowed_usages.contains(bit) { if features.allowed_usages.contains(bit) {
@ -259,7 +259,7 @@ fn print_adapter(output: &mut impl io::Write, report: &AdapterReport, idx: usize
let features = texture_format_features[&format]; let features = texture_format_features[&format];
let format_name = texture::texture_format_name(format); let format_name = texture::texture_format_name(format);
write!(output, "\t\t{format_name:>0$}", max_format_name_size)?; write!(output, "\t\t{format_name:>max_format_name_size$}")?;
for bit in wgpu::TextureFormatFeatureFlags::all().iter() { for bit in wgpu::TextureFormatFeatureFlags::all().iter() {
write!(output, "")?; write!(output, "")?;
if features.flags.contains(bit) { if features.flags.contains(bit) {

View File

@ -14,8 +14,8 @@ pub fn gpu_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
let ident_str = ident.to_string(); let ident_str = ident.to_string();
let ident_lower = ident_str.to_snake_case(); let ident_lower = ident_str.to_snake_case();
let register_test_name = Ident::new(&format!("{}_initializer", ident_lower), ident.span()); let register_test_name = Ident::new(&format!("{ident_lower}_initializer"), ident.span());
let test_name_webgl = Ident::new(&format!("{}_webgl", ident_lower), ident.span()); let test_name_webgl = Ident::new(&format!("{ident_lower}_webgl"), ident.span());
quote! { quote! {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]

View File

@ -359,7 +359,7 @@ impl ContextWgpuCore {
print_tree(&mut output, &mut level, err); print_tree(&mut output, &mut level, err);
format!("Validation Error\n\nCaused by:\n{}", output) format!("Validation Error\n\nCaused by:\n{output}")
} }
} }