auto clippy fixes

This commit is contained in:
Folkert 2023-06-26 20:42:50 +02:00
parent 72c85efc83
commit ef39bad7c6
No known key found for this signature in database
GPG Key ID: 1F17F6FFD112B97C
146 changed files with 750 additions and 1005 deletions

View File

@ -59,7 +59,7 @@ impl From<ModuleError> for ASTError {
impl From<(Region, Loc<Ident>)> for ASTError { impl From<(Region, Loc<Ident>)> for ASTError {
fn from(ident_exists_err: (Region, Loc<Ident>)) -> Self { fn from(ident_exists_err: (Region, Loc<Ident>)) -> Self {
Self::IdentExistsError { Self::IdentExistsError {
msg: format!("{:?}", ident_exists_err), msg: format!("{ident_exists_err:?}"),
} }
} }
} }
@ -67,7 +67,7 @@ impl From<(Region, Loc<Ident>)> for ASTError {
impl<'a> From<SyntaxError<'a>> for ASTError { impl<'a> From<SyntaxError<'a>> for ASTError {
fn from(syntax_err: SyntaxError) -> Self { fn from(syntax_err: SyntaxError) -> Self {
Self::SyntaxErrorNoBacktrace { Self::SyntaxErrorNoBacktrace {
msg: format!("{:?}", syntax_err), msg: format!("{syntax_err:?}"),
} }
} }
} }

View File

@ -94,8 +94,7 @@ pub fn aliases() -> MutMap<Symbol, BuiltinAlias> {
let mut add_alias = |symbol, alias| { let mut add_alias = |symbol, alias| {
debug_assert!( debug_assert!(
!aliases.contains_key(&symbol), !aliases.contains_key(&symbol),
"Duplicate alias definition for {:?}", "Duplicate alias definition for {symbol:?}"
symbol
); );
// TODO instead of using Region::zero for all of these, // TODO instead of using Region::zero for all of these,

View File

@ -2065,7 +2065,7 @@ pub mod test_constrain {
assert_eq!(actual_str, expected_str); assert_eq!(actual_str, expected_str);
} }
Err(e) => panic!("syntax error {:?}", e), Err(e) => panic!("syntax error {e:?}"),
} }
} }

View File

@ -130,7 +130,7 @@ fn expr2_to_string_helper(
); );
} }
Expr2::Call { .. } => { Expr2::Call { .. } => {
let _ = write!(out_string, "Call({:?})", expr2); let _ = write!(out_string, "Call({expr2:?})");
} }
Expr2::Closure { args, .. } => { Expr2::Closure { args, .. } => {
out_string.push_str("Closure:\n"); out_string.push_str("Closure:\n");
@ -148,7 +148,7 @@ fn expr2_to_string_helper(
} }
} }
&Expr2::Var { .. } => { &Expr2::Var { .. } => {
let _ = write!(out_string, "{:?}", expr2); let _ = write!(out_string, "{expr2:?}");
} }
Expr2::RuntimeError { .. } => { Expr2::RuntimeError { .. } => {
out_string.push_str("RuntimeError\n"); out_string.push_str("RuntimeError\n");

View File

@ -671,27 +671,19 @@ pub fn expr_to_expr2<'a>(
// operator desugaring should have removed them! // operator desugaring should have removed them!
bad_expr @ SpaceBefore(_, _) => { bad_expr @ SpaceBefore(_, _) => {
panic!( panic!(
"A SpaceBefore did not get removed during operator desugaring somehow: {:#?}", "A SpaceBefore did not get removed during operator desugaring somehow: {bad_expr:#?}"
bad_expr
); );
} }
bad_expr @ SpaceAfter(_, _) => { bad_expr @ SpaceAfter(_, _) => {
panic!( panic!(
"A SpaceAfter did not get removed during operator desugaring somehow: {:#?}", "A SpaceAfter did not get removed during operator desugaring somehow: {bad_expr:#?}"
bad_expr
); );
} }
bad_expr @ BinOps { .. } => { bad_expr @ BinOps { .. } => {
panic!( panic!("A binary operator chain did not get desugared somehow: {bad_expr:#?}");
"A binary operator chain did not get desugared somehow: {:#?}",
bad_expr
);
} }
bad_expr @ UnaryOp(_, _) => { bad_expr @ UnaryOp(_, _) => {
panic!( panic!("A unary operator did not get desugared somehow: {bad_expr:#?}");
"A unary operator did not get desugared somehow: {:#?}",
bad_expr
);
} }
rest => todo!("not yet implemented {:?}", rest), rest => todo!("not yet implemented {:?}", rest),

View File

@ -227,7 +227,7 @@ pub fn update_str_expr(
Expr2::Str(old_pool_str) => Either::OldPoolStr(*old_pool_str), Expr2::Str(old_pool_str) => Either::OldPoolStr(*old_pool_str),
other => UnexpectedASTNodeSnafu { other => UnexpectedASTNodeSnafu {
required_node_type: "SmallStr or Str", required_node_type: "SmallStr or Str",
encountered_node_type: format!("{:?}", other), encountered_node_type: format!("{other:?}"),
} }
.fail()?, .fail()?,
}; };

View File

@ -102,8 +102,7 @@ impl<'a> Env<'a> {
) -> Result<Symbol, RuntimeError> { ) -> Result<Symbol, RuntimeError> {
debug_assert!( debug_assert!(
!module_name.is_empty(), !module_name.is_empty(),
"Called env.qualified_lookup with an unqualified ident: {:?}", "Called env.qualified_lookup with an unqualified ident: {ident:?}"
ident
); );
let module_name: ModuleName = module_name.into(); let module_name: ModuleName = module_name.into();

View File

@ -25,14 +25,8 @@ pub fn load_module(
match loaded { match loaded {
Ok(x) => x, Ok(x) => x,
Err(roc_load::LoadingProblem::FormattedReport(report)) => { Err(roc_load::LoadingProblem::FormattedReport(report)) => {
panic!( panic!("Failed to load module from src_file: {src_file:?}. Report: {report}");
"Failed to load module from src_file: {:?}. Report: {}",
src_file, report
);
} }
Err(e) => panic!( Err(e) => panic!("Failed to load module from src_file {src_file:?}: {e:?}"),
"Failed to load module from src_file {:?}: {:?}",
src_file, e
),
} }
} }

View File

@ -93,18 +93,18 @@ pub fn format(files: std::vec::Vec<PathBuf>, mode: FormatMode) -> Result<(), Str
// the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same. // the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same.
// I don't have the patience to debug this right now, so let's leave it for another day... // I don't have the patience to debug this right now, so let's leave it for another day...
// TODO: fix PartialEq impl on ast types // TODO: fix PartialEq impl on ast types
if format!("{:?}", ast_normalized) != format!("{:?}", reparsed_ast_normalized) { if format!("{ast_normalized:?}") != format!("{reparsed_ast_normalized:?}") {
let mut fail_file = file.clone(); let mut fail_file = file.clone();
fail_file.set_extension("roc-format-failed"); fail_file.set_extension("roc-format-failed");
std::fs::write(&fail_file, buf.as_str()).unwrap(); std::fs::write(&fail_file, buf.as_str()).unwrap();
let mut before_file = file.clone(); let mut before_file = file.clone();
before_file.set_extension("roc-format-failed-ast-before"); before_file.set_extension("roc-format-failed-ast-before");
std::fs::write(&before_file, format!("{:#?}\n", ast_normalized)).unwrap(); std::fs::write(&before_file, format!("{ast_normalized:#?}\n")).unwrap();
let mut after_file = file.clone(); let mut after_file = file.clone();
after_file.set_extension("roc-format-failed-ast-after"); after_file.set_extension("roc-format-failed-ast-after");
std::fs::write(&after_file, format!("{:#?}\n", reparsed_ast_normalized)).unwrap(); std::fs::write(&after_file, format!("{reparsed_ast_normalized:#?}\n")).unwrap();
internal_error!( internal_error!(
"Formatting bug; formatting didn't reparse as the same tree\n\n\ "Formatting bug; formatting didn't reparse as the same tree\n\n\

View File

@ -416,12 +416,10 @@ pub fn test(matches: &ArgMatches, triple: Triple) -> io::Result<i32> {
match matches.value_source(ROC_FILE) { match matches.value_source(ROC_FILE) {
Some(ValueSource::DefaultValue) => { Some(ValueSource::DefaultValue) => {
eprintln!( eprintln!(
"\nThe current directory ({}) does not contain a {} file to use as a default.\n\nYou can run `roc help` for more information on how to provide a .roc file.\n", "\nThe current directory ({current_dir_string}) does not contain a {DEFAULT_ROC_FILENAME} file to use as a default.\n\nYou can run `roc help` for more information on how to provide a .roc file.\n"
current_dir_string,
DEFAULT_ROC_FILENAME
) )
} }
_ => eprintln!("\nThis file was not found: {}\n\nYou can run `roc help` for more information on how to provide a .roc file.\n", expected_file_path_string), _ => eprintln!("\nThis file was not found: {expected_file_path_string}\n\nYou can run `roc help` for more information on how to provide a .roc file.\n"),
} }
process::exit(1); process::exit(1);
@ -565,16 +563,13 @@ pub fn build(
match matches.value_source(ROC_FILE) { match matches.value_source(ROC_FILE) {
Some(ValueSource::DefaultValue) => { Some(ValueSource::DefaultValue) => {
eprintln!( eprintln!(
"\nThe current directory ({}) does not contain a {} file to use as a default.\n\nYou can run `roc help` for more information on how to provide a .roc file.\n", "\nThe current directory ({current_dir_string}) does not contain a {DEFAULT_ROC_FILENAME} file to use as a default.\n\nYou can run `roc help` for more information on how to provide a .roc file.\n"
current_dir_string,
DEFAULT_ROC_FILENAME
) )
} }
_ => { _ => {
let mut error_lines = Vec::new(); let mut error_lines = Vec::new();
error_lines.push(format!( error_lines.push(format!(
"This file was not found: {}", "This file was not found: {expected_file_path_string}"
expected_file_path_string
)); ));
// Add some additional hints if run as `roc [FILENAME]`. // Add some additional hints if run as `roc [FILENAME]`.
if matches.subcommand().is_none() { if matches.subcommand().is_none() {
@ -584,8 +579,7 @@ pub fn build(
nearest_match(possible_typo, subcommands) nearest_match(possible_typo, subcommands)
{ {
error_lines.push(format!( error_lines.push(format!(
"Did you mean to use the {} subcommand?", "Did you mean to use the {nearest_command} subcommand?"
nearest_command
)); ));
} }
} }
@ -1144,7 +1138,7 @@ fn roc_run_executable_file_path(binary_bytes: &[u8]) -> std::io::Result<Executab
); );
} }
let path = PathBuf::from(format!("/proc/self/fd/{}", fd)); let path = PathBuf::from(format!("/proc/self/fd/{fd}"));
std::fs::write(&path, binary_bytes)?; std::fs::write(&path, binary_bytes)?;
@ -1351,7 +1345,7 @@ impl std::str::FromStr for Target {
"linux64" => Ok(Target::Linux64), "linux64" => Ok(Target::Linux64),
"windows64" => Ok(Target::Windows64), "windows64" => Ok(Target::Windows64),
"wasm32" => Ok(Target::Wasm32), "wasm32" => Ok(Target::Wasm32),
_ => Err(format!("Roc does not know how to compile to {}", string)), _ => Err(format!("Roc does not know how to compile to {string}")),
} }
} }
} }

View File

@ -200,12 +200,12 @@ fn main() -> io::Result<()> {
} }
Err(LoadingProblem::FormattedReport(report)) => { Err(LoadingProblem::FormattedReport(report)) => {
print!("{}", report); print!("{report}");
Ok(1) Ok(1)
} }
Err(other) => { Err(other) => {
panic!("build_file failed with error:\n{:?}", other); panic!("build_file failed with error:\n{other:?}");
} }
} }
} }
@ -272,7 +272,7 @@ fn main() -> io::Result<()> {
let format_exit_code = match format(roc_files, format_mode) { let format_exit_code = match format(roc_files, format_mode) {
Ok(_) => 0, Ok(_) => 0,
Err(message) => { Err(message) => {
eprintln!("{}", message); eprintln!("{message}");
1 1
} }
}; };

View File

@ -90,7 +90,7 @@ mod cli_run {
// e.g. "1 error and 0 warnings found in 123 ms." // e.g. "1 error and 0 warnings found in 123 ms."
let (before_first_digit, _) = err.split_at(err.rfind("found in ").unwrap()); let (before_first_digit, _) = err.split_at(err.rfind("found in ").unwrap());
let err = format!("{}found in <ignored for test> ms.", before_first_digit); let err = format!("{before_first_digit}found in <ignored for test> ms.");
// make paths consistent // make paths consistent
let err = err.replace('\\', "/"); let err = err.replace('\\', "/");
@ -230,7 +230,7 @@ mod cli_run {
what: _, what: _,
xwhat, xwhat,
} = error; } = error;
println!("Valgrind Error: {}\n", kind); println!("Valgrind Error: {kind}\n");
if let Some(ValgrindErrorXWhat { if let Some(ValgrindErrorXWhat {
text, text,
@ -238,14 +238,14 @@ mod cli_run {
leakedblocks: _, leakedblocks: _,
}) = xwhat }) = xwhat
{ {
println!(" {}", text); println!(" {text}");
} }
} }
panic!("Valgrind reported memory errors"); panic!("Valgrind reported memory errors");
} }
} else { } else {
let exit_code = match valgrind_out.status.code() { let exit_code = match valgrind_out.status.code() {
Some(code) => format!("exit code {}", code), Some(code) => format!("exit code {code}"),
None => "no exit code".to_string(), None => "no exit code".to_string(),
}; };
@ -301,7 +301,7 @@ mod cli_run {
// e.g. "1 failed and 0 passed in 123 ms." // e.g. "1 failed and 0 passed in 123 ms."
if let Some(split) = actual.rfind("passed in ") { if let Some(split) = actual.rfind("passed in ") {
let (before_first_digit, _) = actual.split_at(split); let (before_first_digit, _) = actual.split_at(split);
actual = format!("{}passed in <ignored for test> ms.", before_first_digit); actual = format!("{before_first_digit}passed in <ignored for test> ms.");
} }
let self_path = file.display().to_string(); let self_path = file.display().to_string();
@ -397,8 +397,7 @@ mod cli_run {
"swiftui" | "rocLovesSwift" => { "swiftui" | "rocLovesSwift" => {
if cfg!(not(target_os = "macos")) { if cfg!(not(target_os = "macos")) {
eprintln!( eprintln!(
"WARNING: skipping testing example {} because it only works on MacOS.", "WARNING: skipping testing example {roc_filename} because it only works on MacOS."
roc_filename
); );
return; return;
} else { } else {
@ -409,8 +408,7 @@ mod cli_run {
"rocLovesWebAssembly" => { "rocLovesWebAssembly" => {
// this is a web assembly example, but we don't test with JS at the moment // this is a web assembly example, but we don't test with JS at the moment
eprintln!( eprintln!(
"WARNING: skipping testing example {} because it only works in a browser!", "WARNING: skipping testing example {roc_filename} because it only works in a browser!"
roc_filename
); );
return; return;
} }
@ -965,16 +963,14 @@ mod cli_run {
match roc_filename { match roc_filename {
"QuicksortApp.roc" => { "QuicksortApp.roc" => {
eprintln!( eprintln!(
"WARNING: skipping testing benchmark {} because the test is broken right now!", "WARNING: skipping testing benchmark {roc_filename} because the test is broken right now!"
roc_filename
); );
return; return;
} }
"TestAStar.roc" => { "TestAStar.roc" => {
if cfg!(feature = "wasm32-cli-run") { if cfg!(feature = "wasm32-cli-run") {
eprintln!( eprintln!(
"WARNING: skipping testing benchmark {} because it currently does not work on wasm32 due to dictionaries.", "WARNING: skipping testing benchmark {roc_filename} because it currently does not work on wasm32 due to dictionaries."
roc_filename
); );
return; return;
} }

View File

@ -30,7 +30,7 @@ mod editor_launch_test {
// The editor expects to be run from the root of the repo, so it can find the cli-platform to init a new project folder. // The editor expects to be run from the root of the repo, so it can find the cli-platform to init a new project folder.
env::set_current_dir(&root_dir) env::set_current_dir(&root_dir)
.unwrap_or_else(|_| panic!("Failed to set current dir to {:?}", root_dir)); .unwrap_or_else(|_| panic!("Failed to set current dir to {root_dir:?}"));
let roc_binary_path = build_roc_bin(&["--features", "editor"]); let roc_binary_path = build_roc_bin(&["--features", "editor"]);

View File

@ -25,8 +25,7 @@ fn exec_bench_w_input<T: Measurement>(
assert!( assert!(
compile_out.status.success(), compile_out.status.success(),
"build ended with bad status {:?}", "build ended with bad status {compile_out:?}"
compile_out
); );
check_cmd_output(file, stdin_str, executable_filename, expected_ending); check_cmd_output(file, stdin_str, executable_filename, expected_ending);
@ -58,10 +57,7 @@ fn check_cmd_output(
}; };
if !&out.stdout.ends_with(expected_ending) { if !&out.stdout.ends_with(expected_ending) {
panic!( panic!("expected output to end with {expected_ending:?} but instead got {out:#?}");
"expected output to end with {:?} but instead got {:#?}",
expected_ending, out
);
} }
assert!(out.status.success()); assert!(out.status.success());
} }
@ -96,7 +92,7 @@ fn bench_cmd<T: Measurement>(
} }
if let Some(bench_group) = bench_group_opt { if let Some(bench_group) = bench_group_opt {
bench_group.bench_function(&format!("Benchmarking {:?}", executable_filename), |b| { bench_group.bench_function(&format!("Benchmarking {executable_filename:?}"), |b| {
b.iter(|| run_cmd(black_box(&cmd_str), black_box([stdin_str]), &[], [])) b.iter(|| run_cmd(black_box(&cmd_str), black_box([stdin_str]), &[], []))
}); });
} else { } else {

View File

@ -216,7 +216,7 @@ pub fn build_roc_bin(extra_args: &[&str]) -> PathBuf {
cargo_cmd.current_dir(root_project_dir).args(&args); cargo_cmd.current_dir(root_project_dir).args(&args);
let cargo_cmd_str = format!("{:?}", cargo_cmd); let cargo_cmd_str = format!("{cargo_cmd:?}");
let cargo_output = cargo_cmd.output().unwrap(); let cargo_output = cargo_cmd.output().unwrap();
@ -255,7 +255,7 @@ pub fn run_cmd<'a, I: IntoIterator<Item = &'a str>, E: IntoIterator<Item = (&'a
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::piped()) .stderr(Stdio::piped())
.spawn() .spawn()
.unwrap_or_else(|_| panic!("failed to execute cmd `{}` in CLI test", cmd_name)); .unwrap_or_else(|_| panic!("failed to execute cmd `{cmd_name}` in CLI test"));
{ {
let stdin = child.stdin.as_mut().expect("Failed to open stdin"); let stdin = child.stdin.as_mut().expect("Failed to open stdin");
@ -269,7 +269,7 @@ pub fn run_cmd<'a, I: IntoIterator<Item = &'a str>, E: IntoIterator<Item = (&'a
let output = child let output = child
.wait_with_output() .wait_with_output()
.unwrap_or_else(|_| panic!("failed to execute cmd `{}` in CLI test", cmd_name)); .unwrap_or_else(|_| panic!("failed to execute cmd `{cmd_name}` in CLI test"));
Out { Out {
cmd_str, cmd_str,

View File

@ -376,7 +376,7 @@ pub fn tree_as_string(root_node_id: MarkNodeId, mark_node_pool: &SlowPool) -> St
let node = mark_node_pool.get(root_node_id); let node = mark_node_pool.get(root_node_id);
writeln!(full_string, "{} mn_id {}\n", node, root_node_id).unwrap(); writeln!(full_string, "{node} mn_id {root_node_id}\n").unwrap();
tree_as_string_helper(node, 1, &mut full_string, mark_node_pool); tree_as_string_helper(node, 1, &mut full_string, mark_node_pool);
@ -399,7 +399,7 @@ fn tree_as_string_helper(
.join("") .join("")
.to_owned(); .to_owned();
writeln!(full_str, "{} mn_id {}", child_str, child_id).unwrap(); writeln!(full_str, "{child_str} mn_id {child_id}").unwrap();
tree_string.push_str(&full_str); tree_string.push_str(&full_str);

View File

@ -56,7 +56,7 @@ pub type MarkResult<T, E = MarkError> = std::result::Result<T, E>;
impl From<UtilError> for MarkError { impl From<UtilError> for MarkError {
fn from(util_err: UtilError) -> Self { fn from(util_err: UtilError) -> Self {
let msg = format!("{}", util_err); let msg = format!("{util_err}");
// hack to handle MarkError derive // hack to handle MarkError derive
let dummy_res: Result<(), NoneError> = Err(NoneError {}); let dummy_res: Result<(), NoneError> = Err(NoneError {});

View File

@ -39,8 +39,8 @@ impl SlowPool {
for (mark_node_id, node) in self.nodes.iter().enumerate() { for (mark_node_id, node) in self.nodes.iter().enumerate() {
let ast_node_id_str = match mark_id_ast_id_map.get(mark_node_id) { let ast_node_id_str = match mark_id_ast_id_map.get(mark_node_id) {
Ok(ast_id) => format!("{:?}", ast_id), Ok(ast_id) => format!("{ast_id:?}"),
Err(err) => format!("{:?}", err), Err(err) => format!("{err:?}"),
}; };
let ast_node_id: String = ast_node_id_str let ast_node_id: String = ast_node_id_str
.chars() .chars()
@ -52,7 +52,7 @@ impl SlowPool {
let node_children = node.get_children_ids(); let node_children = node.get_children_ids();
if !node_children.is_empty() { if !node_children.is_empty() {
child_str = format!("children: {:?}", node_children); child_str = format!("children: {node_children:?}");
} }
write!( write!(

View File

@ -117,7 +117,7 @@ where
} }
if debug() { if debug() {
for (i, c) in (format!("{:?}", symbol)).chars().take(25).enumerate() { for (i, c) in (format!("{symbol:?}")).chars().take(25).enumerate() {
name_bytes[25 + i] = c as u8; name_bytes[25 + i] = c as u8;
} }
} }
@ -131,7 +131,7 @@ fn bytes_as_ascii(bytes: &[u8]) -> String {
let mut buf = String::new(); let mut buf = String::new();
for byte in bytes { for byte in bytes {
write!(buf, "{:02X}", byte).unwrap(); write!(buf, "{byte:02X}").unwrap();
} }
buf buf

View File

@ -161,7 +161,7 @@ pub fn build_zig_host_native(
zig_cmd.args([ zig_cmd.args([
zig_host_src, zig_host_src,
&format!("-femit-bin={}", emit_bin), &format!("-femit-bin={emit_bin}"),
"--pkg-begin", "--pkg-begin",
"glue", "glue",
find_zig_glue_path().to_str().unwrap(), find_zig_glue_path().to_str().unwrap(),
@ -399,7 +399,7 @@ pub fn build_swift_host_native(
match arch { match arch {
Architecture::Aarch64(_) => command.arg("-arm64"), Architecture::Aarch64(_) => command.arg("-arm64"),
_ => command.arg(format!("-{}", arch)), _ => command.arg(format!("-{arch}")),
}; };
command command
@ -928,7 +928,7 @@ fn link_linux(
.map(|segments| segments.join("/")) .map(|segments| segments.join("/"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join("\n"); .join("\n");
eprintln!("We looked in the following directories:\n{}", dirs); eprintln!("We looked in the following directories:\n{dirs}");
process::exit(1); process::exit(1);
} }
}; };
@ -1085,8 +1085,8 @@ fn link_macos(
let sdk_path = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"; let sdk_path = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib";
if Path::new(sdk_path).exists() { if Path::new(sdk_path).exists() {
ld_command.arg(format!("-L{}", sdk_path)); ld_command.arg(format!("-L{sdk_path}"));
ld_command.arg(format!("-L{}/swift", sdk_path)); ld_command.arg(format!("-L{sdk_path}/swift"));
}; };
let roc_link_flags = match env::var("ROC_LINK_FLAGS") { let roc_link_flags = match env::var("ROC_LINK_FLAGS") {
@ -1288,9 +1288,7 @@ pub fn llvm_module_to_dylib(
assert!( assert!(
exit_status.success(), exit_status.success(),
"\n___________\nLinking command failed with status {:?}:\n\n {:?}\n___________\n", "\n___________\nLinking command failed with status {exit_status:?}:\n\n {child:?}\n___________\n"
exit_status,
child
); );
// Load the dylib // Load the dylib

View File

@ -320,10 +320,10 @@ fn gen_from_mono_module_llvm<'a>(
if !unrecognized.is_empty() { if !unrecognized.is_empty() {
let out = unrecognized let out = unrecognized
.iter() .iter()
.map(|x| format!("{:?}", x)) .map(|x| format!("{x:?}"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "); .join(", ");
eprintln!("Unrecognized sanitizer: {}\nSupported options are \"address\", \"memory\", \"thread\", \"cargo-fuzz\", and \"afl.rs\".", out); eprintln!("Unrecognized sanitizer: {out}\nSupported options are \"address\", \"memory\", \"thread\", \"cargo-fuzz\", and \"afl.rs\".");
eprintln!("Note: \"cargo-fuzz\" and \"afl.rs\" both enable sanitizer coverage for fuzzing. They just use different parameters to match the respective libraries.") eprintln!("Note: \"cargo-fuzz\" and \"afl.rs\" both enable sanitizer coverage for fuzzing. They just use different parameters to match the respective libraries.")
} }
@ -340,7 +340,7 @@ fn gen_from_mono_module_llvm<'a>(
} }
let opt = opt.output().unwrap(); let opt = opt.output().unwrap();
assert!(opt.stderr.is_empty(), "{:#?}", opt); assert!(opt.stderr.is_empty(), "{opt:#?}");
// write the .o file. Note that this builds the .o for the local machine, // write the .o file. Note that this builds the .o for the local machine,
// and ignores the `target_machine` entirely. // and ignores the `target_machine` entirely.
@ -358,7 +358,7 @@ fn gen_from_mono_module_llvm<'a>(
.output() .output()
.unwrap(); .unwrap();
assert!(bc_to_object.status.success(), "{:#?}", bc_to_object); assert!(bc_to_object.status.success(), "{bc_to_object:#?}");
MemoryBuffer::create_from_file(&app_o_file).expect("memory buffer creation works") MemoryBuffer::create_from_file(&app_o_file).expect("memory buffer creation works")
} else if emit_debug_info { } else if emit_debug_info {
@ -414,7 +414,7 @@ fn gen_from_mono_module_llvm<'a>(
.output() .output()
.unwrap(); .unwrap();
assert!(ll_to_object.stderr.is_empty(), "{:#?}", ll_to_object); assert!(ll_to_object.stderr.is_empty(), "{ll_to_object:#?}");
} }
_ => unreachable!(), _ => unreachable!(),
} }
@ -716,13 +716,13 @@ pub fn handle_error_module(
pub fn handle_loading_problem(problem: LoadingProblem) -> std::io::Result<i32> { pub fn handle_loading_problem(problem: LoadingProblem) -> std::io::Result<i32> {
match problem { match problem {
LoadingProblem::FormattedReport(report) => { LoadingProblem::FormattedReport(report) => {
print!("{}", report); print!("{report}");
Ok(1) Ok(1)
} }
_ => { _ => {
// TODO: tighten up the types here, we should always end up with a // TODO: tighten up the types here, we should always end up with a
// formatted report from load. // formatted report from load.
print!("Failed with error: {:?}", problem); print!("Failed with error: {problem:?}");
Ok(1) Ok(1)
} }
} }
@ -889,7 +889,7 @@ fn build_loaded_file<'a>(
buf.push('\n'); buf.push('\n');
use std::fmt::Write; use std::fmt::Write;
write!(buf, "{}", module_timing).unwrap(); write!(buf, "{module_timing}").unwrap();
if it.peek().is_some() { if it.peek().is_some() {
buf.push('\n'); buf.push('\n');
@ -914,10 +914,7 @@ fn build_loaded_file<'a>(
.expect("Failed to (re)build platform."); .expect("Failed to (re)build platform.");
if emit_timings && !is_platform_prebuilt { if emit_timings && !is_platform_prebuilt {
println!( println!("Finished rebuilding the platform in {rebuild_duration} ms\n");
"Finished rebuilding the platform in {} ms\n",
rebuild_duration
);
} }
Some(HostRebuildTiming::BeforeApp(rebuild_duration)) Some(HostRebuildTiming::BeforeApp(rebuild_duration))
@ -957,8 +954,7 @@ fn build_loaded_file<'a>(
if emit_timings { if emit_timings {
println!( println!(
"\n\nCompilation finished!\n\nHere's how long each module took to compile:\n\n{}", "\n\nCompilation finished!\n\nHere's how long each module took to compile:\n\n{buf}"
buf
); );
println!( println!(
@ -972,10 +968,7 @@ fn build_loaded_file<'a>(
let rebuild_duration = thread.join().expect("Failed to (re)build platform."); let rebuild_duration = thread.join().expect("Failed to (re)build platform.");
if emit_timings && !is_platform_prebuilt { if emit_timings && !is_platform_prebuilt {
println!( println!("Finished rebuilding the platform in {rebuild_duration} ms\n");
"Finished rebuilding the platform in {} ms\n",
rebuild_duration
);
} }
} }
@ -1007,7 +1000,7 @@ fn build_loaded_file<'a>(
}; };
let app_o_file = tempfile::Builder::new() let app_o_file = tempfile::Builder::new()
.prefix("roc_app") .prefix("roc_app")
.suffix(&format!(".{}", extension)) .suffix(&format!(".{extension}"))
.tempfile() .tempfile()
.map_err(|err| todo!("TODO Gracefully handle tempfile creation error {:?}", err))?; .map_err(|err| todo!("TODO Gracefully handle tempfile creation error {:?}", err))?;
let app_o_file = app_o_file.path(); let app_o_file = app_o_file.path();
@ -1257,8 +1250,7 @@ pub fn check_file<'a>(
if emit_timings { if emit_timings {
println!( println!(
"\n\nCompilation finished!\n\nHere's how long each module took to compile:\n\n{}", "\n\nCompilation finished!\n\nHere's how long each module took to compile:\n\n{buf}"
buf
); );
println!("Finished checking in {} ms\n", compilation_end.as_millis(),); println!("Finished checking in {} ms\n", compilation_end.as_millis(),);

View File

@ -61,12 +61,12 @@ fn generate_bc_file(bitcode_path: &Path, zig_object: &str, file_name: &str) {
ll_path.set_extension("ll"); ll_path.set_extension("ll");
let dest_ir_host = ll_path.to_str().expect("Invalid dest ir path"); let dest_ir_host = ll_path.to_str().expect("Invalid dest ir path");
println!("Compiling host ir to: {}", dest_ir_host); println!("Compiling host ir to: {dest_ir_host}");
let mut bc_path = bitcode_path.join(file_name); let mut bc_path = bitcode_path.join(file_name);
bc_path.set_extension("bc"); bc_path.set_extension("bc");
let dest_bc_64bit = bc_path.to_str().expect("Invalid dest bc path"); let dest_bc_64bit = bc_path.to_str().expect("Invalid dest bc path");
println!("Compiling 64-bit bitcode to: {}", dest_bc_64bit); println!("Compiling 64-bit bitcode to: {dest_bc_64bit}");
// workaround for github.com/ziglang/zig/issues/9711 // workaround for github.com/ziglang/zig/issues/9711
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -104,7 +104,7 @@ fn run_command(mut command: Command, flaky_fail_counter: usize) {
false => { false => {
let error_str = match str::from_utf8(&output.stderr) { let error_str = match str::from_utf8(&output.stderr) {
Ok(stderr) => stderr.to_string(), Ok(stderr) => stderr.to_string(),
Err(_) => format!("Failed to run \"{}\"", command_str), Err(_) => format!("Failed to run \"{command_str}\""),
}; };
// Flaky test errors that only occur sometimes on MacOS ci server. // Flaky test errors that only occur sometimes on MacOS ci server.

View File

@ -66,7 +66,7 @@ fn generate_object_file(bitcode_path: &Path, zig_object: &str, object_file_name:
let src_obj_path = bitcode_path.join(object_file_name); let src_obj_path = bitcode_path.join(object_file_name);
let src_obj = src_obj_path.to_str().expect("Invalid src object path"); let src_obj = src_obj_path.to_str().expect("Invalid src object path");
println!("Compiling zig object `{}` to: {}", zig_object, src_obj); println!("Compiling zig object `{zig_object}` to: {src_obj}");
if !DEBUG { if !DEBUG {
let mut zig_cmd = zig(); let mut zig_cmd = zig();
@ -77,7 +77,7 @@ fn generate_object_file(bitcode_path: &Path, zig_object: &str, object_file_name:
run_command(zig_cmd, 0); run_command(zig_cmd, 0);
println!("Moving zig object `{}` to: {}", zig_object, dest_obj); println!("Moving zig object `{zig_object}` to: {dest_obj}");
// we store this .o file in rust's `target` folder (for wasm we need to leave a copy here too) // we store this .o file in rust's `target` folder (for wasm we need to leave a copy here too)
fs::copy(src_obj, dest_obj).unwrap_or_else(|err| { fs::copy(src_obj, dest_obj).unwrap_or_else(|err| {
@ -167,7 +167,7 @@ fn run_command(mut command: Command, flaky_fail_counter: usize) {
false => { false => {
let error_str = match str::from_utf8(&output.stderr) { let error_str = match str::from_utf8(&output.stderr) {
Ok(stderr) => stderr.to_string(), Ok(stderr) => stderr.to_string(),
Err(_) => format!("Failed to run \"{}\"", command_str), Err(_) => format!("Failed to run \"{command_str}\""),
}; };
// Flaky test errors that only occur sometimes on MacOS ci server. // Flaky test errors that only occur sometimes on MacOS ci server.

View File

@ -469,8 +469,7 @@ impl IAbilitiesStore<Resolved> {
debug_assert!( debug_assert!(
old_specialization.is_none(), old_specialization.is_none(),
"Existing resolution: {:?}", "Existing resolution: {old_specialization:?}"
old_specialization
); );
} }

View File

@ -196,7 +196,7 @@ impl Constraints {
let mut buf = String::new(); let mut buf = String::new();
writeln!(buf, "Constraints statistics for module {:?}:", module_id)?; writeln!(buf, "Constraints statistics for module {module_id:?}:")?;
writeln!(buf, " constraints length: {}:", self.constraints.len())?; writeln!(buf, " constraints length: {}:", self.constraints.len())?;
writeln!( writeln!(
@ -853,16 +853,16 @@ impl std::fmt::Debug for Constraint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::Eq(Eq(arg0, arg1, arg2, arg3)) => { Self::Eq(Eq(arg0, arg1, arg2, arg3)) => {
write!(f, "Eq({:?}, {:?}, {:?}, {:?})", arg0, arg1, arg2, arg3) write!(f, "Eq({arg0:?}, {arg1:?}, {arg2:?}, {arg3:?})")
} }
Self::Store(arg0, arg1, arg2, arg3) => { Self::Store(arg0, arg1, arg2, arg3) => {
write!(f, "Store({:?}, {:?}, {:?}, {:?})", arg0, arg1, arg2, arg3) write!(f, "Store({arg0:?}, {arg1:?}, {arg2:?}, {arg3:?})")
} }
Self::Lookup(arg0, arg1, arg2) => { Self::Lookup(arg0, arg1, arg2) => {
write!(f, "Lookup({:?}, {:?}, {:?})", arg0, arg1, arg2) write!(f, "Lookup({arg0:?}, {arg1:?}, {arg2:?})")
} }
Self::Pattern(arg0, arg1, arg2, arg3) => { Self::Pattern(arg0, arg1, arg2, arg3) => {
write!(f, "Pattern({:?}, {:?}, {:?}, {:?})", arg0, arg1, arg2, arg3) write!(f, "Pattern({arg0:?}, {arg1:?}, {arg2:?}, {arg3:?})")
} }
Self::True => write!(f, "True"), Self::True => write!(f, "True"),
Self::SaveTheEnvironment => write!(f, "SaveTheEnvironment"), Self::SaveTheEnvironment => write!(f, "SaveTheEnvironment"),
@ -871,27 +871,19 @@ impl std::fmt::Debug for Constraint {
Self::IsOpenType(arg0) => f.debug_tuple("IsOpenType").field(arg0).finish(), Self::IsOpenType(arg0) => f.debug_tuple("IsOpenType").field(arg0).finish(),
Self::IncludesTag(arg0) => f.debug_tuple("IncludesTag").field(arg0).finish(), Self::IncludesTag(arg0) => f.debug_tuple("IncludesTag").field(arg0).finish(),
Self::PatternPresence(arg0, arg1, arg2, arg3) => { Self::PatternPresence(arg0, arg1, arg2, arg3) => {
write!( write!(f, "PatternPresence({arg0:?}, {arg1:?}, {arg2:?}, {arg3:?})")
f,
"PatternPresence({:?}, {:?}, {:?}, {:?})",
arg0, arg1, arg2, arg3
)
} }
Self::Exhaustive(arg0, arg1, arg2, arg3) => { Self::Exhaustive(arg0, arg1, arg2, arg3) => {
write!( write!(f, "Exhaustive({arg0:?}, {arg1:?}, {arg2:?}, {arg3:?})")
f,
"Exhaustive({:?}, {:?}, {:?}, {:?})",
arg0, arg1, arg2, arg3
)
} }
Self::Resolve(arg0) => { Self::Resolve(arg0) => {
write!(f, "Resolve({:?})", arg0) write!(f, "Resolve({arg0:?})")
} }
Self::CheckCycle(arg0, arg1) => { Self::CheckCycle(arg0, arg1) => {
write!(f, "CheckCycle({:?}, {:?})", arg0, arg1) write!(f, "CheckCycle({arg0:?}, {arg1:?})")
} }
Self::IngestedFile(arg0, arg1, arg2) => { Self::IngestedFile(arg0, arg1, arg2) => {
write!(f, "IngestedFile({:?}, {:?}, {:?})", arg0, arg1, arg2) write!(f, "IngestedFile({arg0:?}, {arg1:?}, {arg2:?})")
} }
} }
} }

View File

@ -24,7 +24,7 @@ trait CopyEnv {
if descriptor.copy.into_variable().is_some() { if descriptor.copy.into_variable().is_some() {
descriptor.copy = OptVariable::NONE; descriptor.copy = OptVariable::NONE;
} else { } else {
debug_assert!(false, "{:?} marked as copied but it wasn't", var); debug_assert!(false, "{var:?} marked as copied but it wasn't");
} }
}) })
} }
@ -1320,7 +1320,7 @@ mod test {
FlexVar(Some(name)) => { FlexVar(Some(name)) => {
assert_eq!(subs[*name].as_str(), "a"); assert_eq!(subs[*name].as_str(), "a");
} }
it => panic!("{:?}", it), it => panic!("{it:?}"),
} }
assert_eq!(var, variant_var); assert_eq!(var, variant_var);
assert!(matches!( assert!(matches!(
@ -1337,7 +1337,7 @@ mod test {
FlexVar(Some(name)) => { FlexVar(Some(name)) => {
assert_eq!(subs[*name].as_str(), "b"); assert_eq!(subs[*name].as_str(), "b");
} }
it => panic!("{:?}", it), it => panic!("{it:?}"),
} }
match arg.value { match arg.value {
@ -1355,10 +1355,10 @@ mod test {
assert_eq!(name.0.as_str(), "G"); assert_eq!(name.0.as_str(), "G");
assert_eq!(arguments.len(), 0); assert_eq!(arguments.len(), 0);
} }
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
@ -1403,7 +1403,7 @@ mod test {
FlexVar(Some(name)) => { FlexVar(Some(name)) => {
assert_eq!(target[*name].as_str(), "a"); assert_eq!(target[*name].as_str(), "a");
} }
it => panic!("{:?}", it), it => panic!("{it:?}"),
} }
assert_eq!(var, variant_var); assert_eq!(var, variant_var);
assert!(matches!( assert!(matches!(
@ -1418,7 +1418,7 @@ mod test {
FlexVar(Some(name)) => { FlexVar(Some(name)) => {
assert_eq!(target[*name].as_str(), "b"); assert_eq!(target[*name].as_str(), "b");
} }
it => panic!("{:?}", it), it => panic!("{it:?}"),
} }
match arg.value { match arg.value {
@ -1436,10 +1436,10 @@ mod test {
assert_eq!(name.0.as_str(), "G"); assert_eq!(name.0.as_str(), "G");
assert_eq!(arguments.len(), 0); assert_eq!(arguments.len(), 0);
} }
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }
e => panic!("{:?}", e), e => panic!("{e:?}"),
} }
} }

View File

@ -1069,8 +1069,7 @@ fn canonicalize_value_defs<'a>(
debug_assert_eq!(env.home, s.module_id()); debug_assert_eq!(env.home, s.module_id());
debug_assert!( debug_assert!(
!symbol_to_index.iter().any(|(id, _)| *id == s.ident_id()), !symbol_to_index.iter().any(|(id, _)| *id == s.ident_id()),
"{:?}", "{s:?}"
s
); );
symbol_to_index.push((s.ident_id(), def_index as u32)); symbol_to_index.push((s.ident_id(), def_index as u32));
@ -1838,7 +1837,7 @@ pub(crate) fn sort_can_defs(
); );
let declaration = if def_ordering.references.get_row_col(index, index) { let declaration = if def_ordering.references.get_row_col(index, index) {
debug_assert!(!is_specialization, "Self-recursive specializations can only be determined during solving - but it was determined for {:?} now, that's a bug!", def); debug_assert!(!is_specialization, "Self-recursive specializations can only be determined during solving - but it was determined for {def:?} now, that's a bug!");
if is_initial if is_initial
&& !def && !def

View File

@ -222,16 +222,16 @@ pub(crate) fn synthesize_member_impl<'a>(
ability_member: Symbol, ability_member: Symbol,
) -> (Symbol, Loc<Pattern>, &'a Loc<ast::Expr<'a>>) { ) -> (Symbol, Loc<Pattern>, &'a Loc<ast::Expr<'a>>) {
// @Opaq // @Opaq
let at_opaque = env.arena.alloc_str(&format!("@{}", opaque_name)); let at_opaque = env.arena.alloc_str(&format!("@{opaque_name}"));
let (impl_name, def_body): (String, ast::Expr<'a>) = match ability_member { let (impl_name, def_body): (String, ast::Expr<'a>) = match ability_member {
Symbol::ENCODE_TO_ENCODER => ( Symbol::ENCODE_TO_ENCODER => (
format!("#{}_toEncoder", opaque_name), format!("#{opaque_name}_toEncoder"),
to_encoder(env, at_opaque), to_encoder(env, at_opaque),
), ),
Symbol::DECODE_DECODER => (format!("#{}_decoder", opaque_name), decoder(env, at_opaque)), Symbol::DECODE_DECODER => (format!("#{opaque_name}_decoder"), decoder(env, at_opaque)),
Symbol::HASH_HASH => (format!("#{}_hash", opaque_name), hash(env, at_opaque)), Symbol::HASH_HASH => (format!("#{opaque_name}_hash"), hash(env, at_opaque)),
Symbol::BOOL_IS_EQ => (format!("#{}_isEq", opaque_name), is_eq(env, at_opaque)), Symbol::BOOL_IS_EQ => (format!("#{opaque_name}_isEq"), is_eq(env, at_opaque)),
other => internal_error!("{:?} is not a derivable ability member!", other), other => internal_error!("{:?} is not a derivable ability member!", other),
}; };

View File

@ -1362,7 +1362,7 @@ pub fn build_host_exposed_def(
match typ.shallow_structural_dealias() { match typ.shallow_structural_dealias() {
Type::Function(args, _, _) => { Type::Function(args, _, _) => {
for i in 0..args.len() { for i in 0..args.len() {
let name = format!("closure_arg_{}_{}", ident, i); let name = format!("closure_arg_{ident}_{i}");
let arg_symbol = { let arg_symbol = {
let ident = name.clone().into(); let ident = name.clone().into();
@ -1381,7 +1381,7 @@ pub fn build_host_exposed_def(
linked_symbol_arguments.push((arg_var, Expr::Var(arg_symbol, arg_var))); linked_symbol_arguments.push((arg_var, Expr::Var(arg_symbol, arg_var)));
} }
let foreign_symbol_name = format!("roc_fx_{}", ident); let foreign_symbol_name = format!("roc_fx_{ident}");
let low_level_call = Expr::ForeignCall { let low_level_call = Expr::ForeignCall {
foreign_symbol: foreign_symbol_name.into(), foreign_symbol: foreign_symbol_name.into(),
args: linked_symbol_arguments, args: linked_symbol_arguments,
@ -1389,7 +1389,7 @@ pub fn build_host_exposed_def(
}; };
let effect_closure_symbol = { let effect_closure_symbol = {
let name = format!("effect_closure_{}", ident); let name = format!("effect_closure_{ident}");
let ident = name.into(); let ident = name.into();
scope.introduce(ident, Region::zero()).unwrap() scope.introduce(ident, Region::zero()).unwrap()
@ -1435,7 +1435,7 @@ pub fn build_host_exposed_def(
_ => { _ => {
// not a function // not a function
let foreign_symbol_name = format!("roc_fx_{}", ident); let foreign_symbol_name = format!("roc_fx_{ident}");
let low_level_call = Expr::ForeignCall { let low_level_call = Expr::ForeignCall {
foreign_symbol: foreign_symbol_name.into(), foreign_symbol: foreign_symbol_name.into(),
args: linked_symbol_arguments, args: linked_symbol_arguments,
@ -1443,7 +1443,7 @@ pub fn build_host_exposed_def(
}; };
let effect_closure_symbol = { let effect_closure_symbol = {
let name = format!("effect_closure_{}", ident); let name = format!("effect_closure_{ident}");
let ident = name.into(); let ident = name.into();
scope.introduce(ident, Region::zero()).unwrap() scope.introduce(ident, Region::zero()).unwrap()

View File

@ -67,8 +67,7 @@ impl<'a> Env<'a> {
) -> Result<Symbol, RuntimeError> { ) -> Result<Symbol, RuntimeError> {
debug_assert!( debug_assert!(
!module_name_str.is_empty(), !module_name_str.is_empty(),
"Called env.qualified_lookup with an unqualified ident: {:?}", "Called env.qualified_lookup with an unqualified ident: {ident:?}"
ident
); );
let module_name = ModuleName::from(module_name_str); let module_name = ModuleName::from(module_name_str);

View File

@ -347,9 +347,7 @@ pub fn canonicalize_module_defs<'a>(
// the symbol should already be added to the scope when this module is canonicalized // the symbol should already be added to the scope when this module is canonicalized
debug_assert!( debug_assert!(
scope.contains_alias(symbol) || scope.abilities_store.is_ability(symbol), scope.contains_alias(symbol) || scope.abilities_store.is_ability(symbol),
"The {:?} is not a type alias or ability known in {:?}", "The {symbol:?} is not a type alias or ability known in {home:?}"
symbol,
home
); );
// but now we know this symbol by a different identifier, so we still need to add it to // but now we know this symbol by a different identifier, so we still need to add it to

View File

@ -220,8 +220,7 @@ fn from_str_radix(src: &str, radix: u32) -> Result<ParsedNumResult, IntErrorKind
assert!( assert!(
(2..=36).contains(&radix), (2..=36).contains(&radix),
"from_str_radix_int: must lie in the range `[2, 36]` - found {}", "from_str_radix_int: must lie in the range `[2, 36]` - found {radix}"
radix
); );
let (opt_exact_bound, src) = parse_literal_suffix(src); let (opt_exact_bound, src) = parse_literal_suffix(src);

View File

@ -531,7 +531,7 @@ pub fn canonicalize_pattern<'a>(
use std::ops::Neg; use std::ops::Neg;
let sign_str = if is_negative { "-" } else { "" }; let sign_str = if is_negative { "-" } else { "" };
let int_str = format!("{}{}", sign_str, int).into_boxed_str(); let int_str = format!("{sign_str}{int}").into_boxed_str();
let i = match int { let i = match int {
// Safety: this is fine because I128::MAX = |I128::MIN| - 1 // Safety: this is fine because I128::MAX = |I128::MIN| - 1
IntValue::I128(n) if is_negative => { IntValue::I128(n) if is_negative => {

View File

@ -37,8 +37,7 @@ pub struct CanExprOut {
pub fn can_expr_with(arena: &Bump, home: ModuleId, expr_str: &str) -> CanExprOut { pub fn can_expr_with(arena: &Bump, home: ModuleId, expr_str: &str) -> CanExprOut {
let loc_expr = roc_parse::test_helpers::parse_loc_with(arena, expr_str).unwrap_or_else(|e| { let loc_expr = roc_parse::test_helpers::parse_loc_with(arena, expr_str).unwrap_or_else(|e| {
panic!( panic!(
"can_expr_with() got a parse error when attempting to canonicalize:\n\n{:?} {:?}", "can_expr_with() got a parse error when attempting to canonicalize:\n\n{expr_str:?} {e:?}"
expr_str, e
) )
}); });

View File

@ -422,7 +422,7 @@ mod test_can {
let CanExprOut { problems, .. } = can_expr_with(&arena, test_home(), src); let CanExprOut { problems, .. } = can_expr_with(&arena, test_home(), src);
assert_eq!(problems.len(), 2); assert_eq!(problems.len(), 2);
println!("{:#?}", problems); println!("{problems:#?}");
assert!(problems.iter().any(|problem| matches!( assert!(problems.iter().any(|problem| matches!(
problem, problem,
Problem::RuntimeError(RuntimeError::Shadowing { .. }) Problem::RuntimeError(RuntimeError::Shadowing { .. })

View File

@ -202,7 +202,7 @@ fn int_to_ordinal(number: usize) -> std::string::String {
}, },
}; };
format!("{}{}", number, ending) format!("{number}{ending}")
} }
#[macro_export] #[macro_export]

View File

@ -48,9 +48,9 @@ enum Kind {
impl Debug for Kind { impl Debug for Kind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::Generated(arg0) => write!(f, "Generated({})", arg0), Self::Generated(arg0) => write!(f, "Generated({arg0})"),
Self::Empty => write!(f, "Empty"), Self::Empty => write!(f, "Empty"),
Self::Interned(arg0) => write!(f, "Interned({})", arg0), Self::Interned(arg0) => write!(f, "Interned({arg0})"),
} }
} }
} }
@ -155,7 +155,7 @@ impl SmallStringInterner {
let index = self.lengths.len(); let index = self.lengths.len();
let offset = self.buffer.len(); let offset = self.buffer.len();
write!(self.buffer, "{}", index).unwrap(); write!(self.buffer, "{index}").unwrap();
// this is a generated name, so store it as a negative length // this is a generated name, so store it as a negative length
let length = Length(-((self.buffer.len() - offset) as i16)); let length = Length(-((self.buffer.len() - offset) as i16));

View File

@ -1044,8 +1044,7 @@ pub fn constrain_expr(
debug_assert!( debug_assert!(
intersection.is_empty(), intersection.is_empty(),
"Two patterns introduce the same symbols - that's a bug!\n{:?}", "Two patterns introduce the same symbols - that's a bug!\n{intersection:?}"
intersection
); );
} }

View File

@ -298,7 +298,7 @@ fn hash_tag_union(
Expr::Int( Expr::Int(
discr_num_var, discr_num_var,
discr_precision_var, discr_precision_var,
format!("{}", discr_n).into_boxed_str(), format!("{discr_n}").into_boxed_str(),
IntValue::I128((discr_n as i128).to_ne_bytes()), IntValue::I128((discr_n as i128).to_ne_bytes()),
IntBound::Exact(discr_width), IntBound::Exact(discr_width),
), ),

View File

@ -31,7 +31,7 @@ impl Env<'_> {
let name = if i == 1 { let name = if i == 1 {
hint.clone() hint.clone()
} else { } else {
format!("{}{}", hint, i) format!("{hint}{i}")
}; };
if self.derived_ident_ids.get_id(&name).is_none() { if self.derived_ident_ids.get_id(&name).is_none() {
break name; break name;
@ -151,7 +151,7 @@ impl Env<'_> {
== self.subs.get_root_key_without_compacting(lambda_set) == self.subs.get_root_key_without_compacting(lambda_set)
}); });
debug_assert!(belongs_to_specialized_lambda_sets, debug_assert!(belongs_to_specialized_lambda_sets,
"Did not expect derivers to need to specialize unspecialized lambda sets, but we got one: {:?} for {:?}", lambda_set, spec_var) "Did not expect derivers to need to specialize unspecialized lambda sets, but we got one: {lambda_set:?} for {spec_var:?}")
} }
} }
} }

View File

@ -3164,7 +3164,7 @@ mod tests {
UsesZR => "xzr".to_owned(), UsesZR => "xzr".to_owned(),
UsesSP => "sp".to_owned(), UsesSP => "sp".to_owned(),
}, },
_ => format!("{}", self), _ => format!("{self}"),
} }
} }
} }

View File

@ -3612,7 +3612,7 @@ mod tests {
fn test_add_reg64_imm32() { fn test_add_reg64_imm32() {
disassembler_test!( disassembler_test!(
add_reg64_imm32, add_reg64_imm32,
|reg, imm| format!("add {}, 0x{:x}", reg, imm), |reg, imm| format!("add {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
); );
@ -3622,7 +3622,7 @@ mod tests {
fn test_add_reg64_reg64() { fn test_add_reg64_reg64() {
disassembler_test!( disassembler_test!(
add_reg64_reg64, add_reg64_reg64,
|reg1, reg2| format!("add {}, {}", reg1, reg2), |reg1, reg2| format!("add {reg1}, {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
@ -3632,7 +3632,7 @@ mod tests {
fn test_sub_reg64_reg64() { fn test_sub_reg64_reg64() {
disassembler_test!( disassembler_test!(
sub_reg64_reg64, sub_reg64_reg64,
|reg1, reg2| format!("sub {}, {}", reg1, reg2), |reg1, reg2| format!("sub {reg1}, {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
@ -3642,7 +3642,7 @@ mod tests {
fn test_addsd_freg64_freg64() { fn test_addsd_freg64_freg64() {
disassembler_test!( disassembler_test!(
addsd_freg64_freg64, addsd_freg64_freg64,
|reg1, reg2| format!("addsd {}, {}", reg1, reg2), |reg1, reg2| format!("addsd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3652,7 +3652,7 @@ mod tests {
fn test_addss_freg32_freg32() { fn test_addss_freg32_freg32() {
disassembler_test!( disassembler_test!(
addss_freg32_freg32, addss_freg32_freg32,
|reg1, reg2| format!("addss {}, {}", reg1, reg2), |reg1, reg2| format!("addss {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3662,7 +3662,7 @@ mod tests {
fn test_andpd_freg64_freg64() { fn test_andpd_freg64_freg64() {
disassembler_test!( disassembler_test!(
andpd_freg64_freg64, andpd_freg64_freg64,
|reg1, reg2| format!("andpd {}, {}", reg1, reg2), |reg1, reg2| format!("andpd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3729,7 +3729,7 @@ mod tests {
fn test_cmovl_reg64_reg64() { fn test_cmovl_reg64_reg64() {
disassembler_test!( disassembler_test!(
cmovl_reg64_reg64, cmovl_reg64_reg64,
|reg1, reg2| format!("cmovl {}, {}", reg1, reg2), |reg1, reg2| format!("cmovl {reg1}, {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
@ -3739,7 +3739,7 @@ mod tests {
fn test_cmp_reg64_imm32() { fn test_cmp_reg64_imm32() {
disassembler_test!( disassembler_test!(
cmp_reg64_imm32, cmp_reg64_imm32,
|reg, imm| format!("cmp {}, 0x{:x}", reg, imm), |reg, imm| format!("cmp {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
); );
@ -3749,7 +3749,7 @@ mod tests {
fn test_imul_reg64_reg64() { fn test_imul_reg64_reg64() {
disassembler_test!( disassembler_test!(
imul_reg64_reg64, imul_reg64_reg64,
|reg1, reg2| format!("imul {}, {}", reg1, reg2), |reg1, reg2| format!("imul {reg1}, {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
@ -3759,7 +3759,7 @@ mod tests {
fn test_mul_reg64_reg64() { fn test_mul_reg64_reg64() {
disassembler_test!( disassembler_test!(
mul_reg64_reg64, mul_reg64_reg64,
|reg| format!("mul {}", reg), |reg| format!("mul {reg}"),
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
} }
@ -3768,7 +3768,7 @@ mod tests {
fn test_mulsd_freg64_freg64() { fn test_mulsd_freg64_freg64() {
disassembler_test!( disassembler_test!(
mulsd_freg64_freg64, mulsd_freg64_freg64,
|reg1, reg2| format!("mulsd {}, {}", reg1, reg2), |reg1, reg2| format!("mulsd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3778,7 +3778,7 @@ mod tests {
fn test_mulss_freg32_freg32() { fn test_mulss_freg32_freg32() {
disassembler_test!( disassembler_test!(
mulss_freg32_freg32, mulss_freg32_freg32,
|reg1, reg2| format!("mulss {}, {}", reg1, reg2), |reg1, reg2| format!("mulss {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3788,7 +3788,7 @@ mod tests {
fn test_idiv_reg64_reg64() { fn test_idiv_reg64_reg64() {
disassembler_test!( disassembler_test!(
idiv_reg64_reg64, idiv_reg64_reg64,
|reg| format!("cqo\nidiv {}", reg), |reg| format!("cqo\nidiv {reg}"),
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
} }
@ -3797,7 +3797,7 @@ mod tests {
fn test_div_reg64_reg64() { fn test_div_reg64_reg64() {
disassembler_test!( disassembler_test!(
udiv_reg64_reg64, udiv_reg64_reg64,
|reg| format!("cqo\ndiv {}", reg), |reg| format!("cqo\ndiv {reg}"),
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
} }
@ -3806,7 +3806,7 @@ mod tests {
fn test_divsd_freg64_freg64() { fn test_divsd_freg64_freg64() {
disassembler_test!( disassembler_test!(
divsd_freg64_freg64, divsd_freg64_freg64,
|reg1, reg2| format!("divsd {}, {}", reg1, reg2), |reg1, reg2| format!("divsd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3816,7 +3816,7 @@ mod tests {
fn test_divss_freg32_freg32() { fn test_divss_freg32_freg32() {
disassembler_test!( disassembler_test!(
divss_freg32_freg32, divss_freg32_freg32,
|reg1, reg2| format!("divss {}, {}", reg1, reg2), |reg1, reg2| format!("divss {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -3846,7 +3846,7 @@ mod tests {
fn test_mov_reg64_imm32() { fn test_mov_reg64_imm32() {
disassembler_test!( disassembler_test!(
mov_reg64_imm32, mov_reg64_imm32,
|reg, imm| format!("mov {}, 0x{:x}", reg, imm), |reg, imm| format!("mov {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
); );
@ -3856,13 +3856,13 @@ mod tests {
fn test_mov_reg64_imm64() { fn test_mov_reg64_imm64() {
disassembler_test!( disassembler_test!(
mov_reg64_imm64, mov_reg64_imm64,
|reg, imm| format!("movabs {}, 0x{:x}", reg, imm), |reg, imm| format!("movabs {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I64] [TEST_I64]
); );
disassembler_test!( disassembler_test!(
mov_reg64_imm64, mov_reg64_imm64,
|reg, imm| format!("mov {}, 0x{:x}", reg, imm), |reg, imm| format!("mov {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32 as i64] [TEST_I32 as i64]
); );
@ -3872,7 +3872,7 @@ mod tests {
fn test_lea_reg64() { fn test_lea_reg64() {
disassembler_test!( disassembler_test!(
lea_reg64, lea_reg64,
|reg| format!("lea {}, [rip]", reg), |reg| format!("lea {reg}, [rip]"),
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
} }
@ -3898,7 +3898,7 @@ mod tests {
X86_64GeneralReg::low_32bits_string(&reg1), X86_64GeneralReg::low_32bits_string(&reg1),
X86_64GeneralReg::low_32bits_string(&reg2) X86_64GeneralReg::low_32bits_string(&reg2)
), ),
RegisterWidth::W64 => format!("mov {}, {}", reg1, reg2), RegisterWidth::W64 => format!("mov {reg1}, {reg2}"),
} }
}, },
ALL_REGISTER_WIDTHS, ALL_REGISTER_WIDTHS,
@ -3967,7 +3967,7 @@ mod tests {
fn test_movsd_freg64_base64_offset32() { fn test_movsd_freg64_base64_offset32() {
disassembler_test!( disassembler_test!(
movsd_freg64_base64_offset32, movsd_freg64_base64_offset32,
|reg1, reg2, imm| format!("movsd {}, qword ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movsd {reg1}, qword ptr [{reg2} + 0x{imm:x}]"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -3978,7 +3978,7 @@ mod tests {
fn test_movss_freg32_base32_offset32() { fn test_movss_freg32_base32_offset32() {
disassembler_test!( disassembler_test!(
movss_freg32_base32_offset32, movss_freg32_base32_offset32,
|reg1, reg2, imm| format!("movss {}, dword ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movss {reg1}, dword ptr [{reg2} + 0x{imm:x}]"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -3989,7 +3989,7 @@ mod tests {
fn test_movsd_base64_offset32_freg64() { fn test_movsd_base64_offset32_freg64() {
disassembler_test!( disassembler_test!(
movsd_base64_offset32_freg64, movsd_base64_offset32_freg64,
|reg1, imm, reg2| format!("movsd qword ptr [{} + 0x{:x}], {}", reg1, imm, reg2), |reg1, imm, reg2| format!("movsd qword ptr [{reg1} + 0x{imm:x}], {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32], [TEST_I32],
ALL_FLOAT_REGS ALL_FLOAT_REGS
@ -4011,7 +4011,7 @@ mod tests {
fn test_mov_reg64_base64_offset32() { fn test_mov_reg64_base64_offset32() {
disassembler_test!( disassembler_test!(
mov_reg64_base64_offset32, mov_reg64_base64_offset32,
|reg1, reg2, imm| format!("mov {}, qword ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("mov {reg1}, qword ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4070,7 +4070,7 @@ mod tests {
fn test_mov_base64_offset32_reg64() { fn test_mov_base64_offset32_reg64() {
disassembler_test!( disassembler_test!(
mov_base64_offset32_reg64, mov_base64_offset32_reg64,
|reg1, imm, reg2| format!("mov qword ptr [{} + 0x{:x}], {}", reg1, imm, reg2), |reg1, imm, reg2| format!("mov qword ptr [{reg1} + 0x{imm:x}], {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32], [TEST_I32],
ALL_GENERAL_REGS ALL_GENERAL_REGS
@ -4129,7 +4129,7 @@ mod tests {
fn test_movsx_reg64_base32_offset32() { fn test_movsx_reg64_base32_offset32() {
disassembler_test!( disassembler_test!(
movsx_reg64_base32_offset32, movsx_reg64_base32_offset32,
|reg1, reg2, imm| format!("movsxd {}, dword ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movsxd {reg1}, dword ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4140,7 +4140,7 @@ mod tests {
fn test_movsx_reg64_base16_offset32() { fn test_movsx_reg64_base16_offset32() {
disassembler_test!( disassembler_test!(
movsx_reg64_base16_offset32, movsx_reg64_base16_offset32,
|reg1, reg2, imm| format!("movsx {}, word ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movsx {reg1}, word ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4151,7 +4151,7 @@ mod tests {
fn test_movsx_reg64_base8_offset32() { fn test_movsx_reg64_base8_offset32() {
disassembler_test!( disassembler_test!(
movsx_reg64_base8_offset32, movsx_reg64_base8_offset32,
|reg1, reg2, imm| format!("movsx {}, byte ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movsx {reg1}, byte ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4162,7 +4162,7 @@ mod tests {
fn test_movzx_reg64_base16_offset32() { fn test_movzx_reg64_base16_offset32() {
disassembler_test!( disassembler_test!(
movzx_reg64_base16_offset32, movzx_reg64_base16_offset32,
|reg1, reg2, imm| format!("movzx {}, word ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movzx {reg1}, word ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4173,7 +4173,7 @@ mod tests {
fn test_movzx_reg64_base8_offset32() { fn test_movzx_reg64_base8_offset32() {
disassembler_test!( disassembler_test!(
movzx_reg64_base8_offset32, movzx_reg64_base8_offset32,
|reg1, reg2, imm| format!("movzx {}, byte ptr [{} + 0x{:x}]", reg1, reg2, imm), |reg1, reg2, imm| format!("movzx {reg1}, byte ptr [{reg2} + 0x{imm:x}]"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
@ -4194,7 +4194,7 @@ mod tests {
fn test_movq_reg64_freg64() { fn test_movq_reg64_freg64() {
disassembler_test!( disassembler_test!(
movq_reg64_freg64, movq_reg64_freg64,
|dst, src| format!("movq {}, {}", dst, src), |dst, src| format!("movq {dst}, {src}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -4204,7 +4204,7 @@ mod tests {
fn test_movsd_freg64_freg64() { fn test_movsd_freg64_freg64() {
disassembler_test!( disassembler_test!(
raw_movsd_freg64_freg64, raw_movsd_freg64_freg64,
|reg1, reg2| format!("movsd {}, {}", reg1, reg2), |reg1, reg2| format!("movsd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -4214,7 +4214,7 @@ mod tests {
fn test_movss_freg32_freg32() { fn test_movss_freg32_freg32() {
disassembler_test!( disassembler_test!(
raw_movss_freg32_freg32, raw_movss_freg32_freg32,
|reg1, reg2| format!("movss {}, {}", reg1, reg2), |reg1, reg2| format!("movss {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -4224,7 +4224,7 @@ mod tests {
fn test_movss_freg32_rip_offset32() { fn test_movss_freg32_rip_offset32() {
disassembler_test!( disassembler_test!(
movss_freg32_rip_offset32, movss_freg32_rip_offset32,
|reg, imm| format!("movss {}, dword ptr [rip + 0x{:x}]", reg, imm), |reg, imm| format!("movss {reg}, dword ptr [rip + 0x{imm:x}]"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
[TEST_I32 as u32] [TEST_I32 as u32]
); );
@ -4234,7 +4234,7 @@ mod tests {
fn test_movsd_freg64_rip_offset32() { fn test_movsd_freg64_rip_offset32() {
disassembler_test!( disassembler_test!(
movsd_freg64_rip_offset32, movsd_freg64_rip_offset32,
|reg, imm| format!("movsd {}, qword ptr [rip + 0x{:x}]", reg, imm), |reg, imm| format!("movsd {reg}, qword ptr [rip + 0x{imm:x}]"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
[TEST_I32 as u32] [TEST_I32 as u32]
); );
@ -4242,7 +4242,7 @@ mod tests {
#[test] #[test]
fn test_neg_reg64() { fn test_neg_reg64() {
disassembler_test!(neg_reg64, |reg| format!("neg {}", reg), ALL_GENERAL_REGS); disassembler_test!(neg_reg64, |reg| format!("neg {reg}"), ALL_GENERAL_REGS);
} }
#[test] #[test]
@ -4251,13 +4251,13 @@ mod tests {
const CVTTSS2SI_CODE: u8 = 0x2C; const CVTTSS2SI_CODE: u8 = 0x2C;
disassembler_test!( disassembler_test!(
|buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTSI2SS_CODE, r1, r2), |buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTSI2SS_CODE, r1, r2),
|reg1, reg2| format!("cvtsi2ss {}, {}", reg1, reg2), |reg1, reg2| format!("cvtsi2ss {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_GENERAL_REGS ALL_GENERAL_REGS
); );
disassembler_test!( disassembler_test!(
|buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTTSS2SI_CODE, r1, r2), |buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTTSS2SI_CODE, r1, r2),
|reg1, reg2| format!("cvttss2si {}, {}", reg1, reg2), |reg1, reg2| format!("cvttss2si {reg1}, {reg2}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -4268,7 +4268,7 @@ mod tests {
const CVTSS2SD_CODE: u8 = 0x5A; const CVTSS2SD_CODE: u8 = 0x5A;
disassembler_test!( disassembler_test!(
|buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTSS2SD_CODE, r1, r2), |buf, r1, r2| cvtsi2_help(buf, 0xF3, CVTSS2SD_CODE, r1, r2),
|reg1, reg2| format!("cvtss2sd {}, {}", reg1, reg2), |reg1, reg2| format!("cvtss2sd {reg1}, {reg2}"),
ALL_FLOAT_REGS, ALL_FLOAT_REGS,
ALL_FLOAT_REGS ALL_FLOAT_REGS
); );
@ -4292,7 +4292,7 @@ mod tests {
fn test_sub_reg64_imm32() { fn test_sub_reg64_imm32() {
disassembler_test!( disassembler_test!(
sub_reg64_imm32, sub_reg64_imm32,
|reg, imm| format!("sub {}, 0x{:x}", reg, imm), |reg, imm| format!("sub {reg}, 0x{imm:x}"),
ALL_GENERAL_REGS, ALL_GENERAL_REGS,
[TEST_I32] [TEST_I32]
); );
@ -4300,12 +4300,12 @@ mod tests {
#[test] #[test]
fn test_pop_reg64() { fn test_pop_reg64() {
disassembler_test!(pop_reg64, |reg| format!("pop {}", reg), ALL_GENERAL_REGS); disassembler_test!(pop_reg64, |reg| format!("pop {reg}"), ALL_GENERAL_REGS);
} }
#[test] #[test]
fn test_push_reg64() { fn test_push_reg64() {
disassembler_test!(push_reg64, |reg| format!("push {}", reg), ALL_GENERAL_REGS); disassembler_test!(push_reg64, |reg| format!("push {reg}"), ALL_GENERAL_REGS);
} }
#[test] #[test]

View File

@ -351,7 +351,7 @@ trait Backend<'a> {
// the functions from the generates #help module (refcounting, equality) is always suffixed // the functions from the generates #help module (refcounting, equality) is always suffixed
// with 1. That is fine, they are always unique anyway. // with 1. That is fine, they are always unique anyway.
if ident_string.contains("#help") { if ident_string.contains("#help") {
format!("{}_{}_1", module_string, ident_string) format!("{module_string}_{ident_string}_1")
} else { } else {
format!("{}_{}_{}", module_string, ident_string, state.finish()) format!("{}_{}_{}", module_string, ident_string, state.finish())
} }

View File

@ -605,7 +605,7 @@ fn build_proc<'a, B: Backend<'a>>(
let elfreloc = match reloc { let elfreloc = match reloc {
Relocation::LocalData { offset, data } => { Relocation::LocalData { offset, data } => {
let data_symbol = write::Symbol { let data_symbol = write::Symbol {
name: format!("{}.data{}", fn_name, local_data_index) name: format!("{fn_name}.data{local_data_index}")
.as_bytes() .as_bytes()
.to_vec(), .to_vec(),
value: 0, value: 0,

View File

@ -34,10 +34,7 @@ pub fn call_bitcode_fn<'ctx>(
.try_as_basic_value() .try_as_basic_value()
.left() .left()
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic!( panic!("LLVM error: Did not get return value from bitcode function {fn_name:?}")
"LLVM error: Did not get return value from bitcode function {:?}",
fn_name
)
}) })
} }
@ -49,7 +46,7 @@ pub fn call_void_bitcode_fn<'ctx>(
call_bitcode_fn_help(env, args, fn_name) call_bitcode_fn_help(env, args, fn_name)
.try_as_basic_value() .try_as_basic_value()
.right() .right()
.unwrap_or_else(|| panic!("LLVM error: Tried to call void bitcode function, but got return value from bitcode function, {:?}", fn_name)) .unwrap_or_else(|| panic!("LLVM error: Tried to call void bitcode function, but got return value from bitcode function, {fn_name:?}"))
} }
fn call_bitcode_fn_help<'ctx>( fn call_bitcode_fn_help<'ctx>(
@ -63,7 +60,7 @@ fn call_bitcode_fn_help<'ctx>(
let fn_val = env let fn_val = env
.module .module
.get_function(fn_name) .get_function(fn_name)
.unwrap_or_else(|| panic!("Unrecognized builtin function: {:?} - if you're working on the Roc compiler, do you need to rebuild the bitcode? See compiler/builtins/bitcode/README.md", fn_name)); .unwrap_or_else(|| panic!("Unrecognized builtin function: {fn_name:?} - if you're working on the Roc compiler, do you need to rebuild the bitcode? See compiler/builtins/bitcode/README.md"));
let call = env.builder.build_call(fn_val, &arguments, "call_builtin"); let call = env.builder.build_call(fn_val, &arguments, "call_builtin");
@ -378,9 +375,9 @@ fn build_rc_wrapper<'a, 'ctx>(
.to_symbol_string(symbol, &env.interns); .to_symbol_string(symbol, &env.interns);
let fn_name = match rc_operation { let fn_name = match rc_operation {
Mode::IncN => format!("{}_inc_n", fn_name), Mode::IncN => format!("{fn_name}_inc_n"),
Mode::Inc => format!("{}_inc", fn_name), Mode::Inc => format!("{fn_name}_inc"),
Mode::Dec => format!("{}_dec", fn_name), Mode::Dec => format!("{fn_name}_dec"),
}; };
let function_value = match env.module.get_function(fn_name.as_str()) { let function_value = match env.module.get_function(fn_name.as_str()) {

View File

@ -263,7 +263,7 @@ impl<'a, 'ctx, 'env> Env<'a, 'ctx, 'env> {
let fn_val = self let fn_val = self
.module .module
.get_function(intrinsic_name) .get_function(intrinsic_name)
.unwrap_or_else(|| panic!("Unrecognized intrinsic function: {}", intrinsic_name)); .unwrap_or_else(|| panic!("Unrecognized intrinsic function: {intrinsic_name}"));
let mut arg_vals: Vec<BasicMetadataValueEnum> = let mut arg_vals: Vec<BasicMetadataValueEnum> =
Vec::with_capacity_in(args.len(), self.arena); Vec::with_capacity_in(args.len(), self.arena);
@ -289,10 +289,7 @@ impl<'a, 'ctx, 'env> Env<'a, 'ctx, 'env> {
let call = self.build_intrinsic_call(intrinsic_name, args); let call = self.build_intrinsic_call(intrinsic_name, args);
call.try_as_basic_value().left().unwrap_or_else(|| { call.try_as_basic_value().left().unwrap_or_else(|| {
panic!( panic!("LLVM error: Invalid call by name for intrinsic {intrinsic_name}")
"LLVM error: Invalid call by name for intrinsic {}",
intrinsic_name
)
}) })
} }
@ -498,17 +495,14 @@ pub fn module_from_builtins<'ctx>(
} => { } => {
include_bytes!("../../../builtins/bitcode/builtins-windows-x86_64.bc") include_bytes!("../../../builtins/bitcode/builtins-windows-x86_64.bc")
} }
_ => panic!( _ => panic!("The zig builtins are not currently built for this target: {target:?}"),
"The zig builtins are not currently built for this target: {:?}",
target
),
} }
}; };
let memory_buffer = MemoryBuffer::create_from_memory_range(bitcode_bytes, module_name); let memory_buffer = MemoryBuffer::create_from_memory_range(bitcode_bytes, module_name);
let module = Module::parse_bitcode_from_buffer(&memory_buffer, ctx) let module = Module::parse_bitcode_from_buffer(&memory_buffer, ctx)
.unwrap_or_else(|err| panic!("Unable to import builtins bitcode. LLVM error: {:?}", err)); .unwrap_or_else(|err| panic!("Unable to import builtins bitcode. LLVM error: {err:?}"));
// Add LLVM intrinsics. // Add LLVM intrinsics.
add_intrinsics(ctx, &module); add_intrinsics(ctx, &module);
@ -766,7 +760,7 @@ pub fn build_exp_literal<'a, 'ctx>(
LayoutRepr::Builtin(Builtin::Int(int_width)) => { LayoutRepr::Builtin(Builtin::Int(int_width)) => {
int_with_precision(env, i128::from_ne_bytes(*bytes), int_width).into() int_with_precision(env, i128::from_ne_bytes(*bytes), int_width).into()
} }
_ => panic!("Invalid layout for int literal = {:?}", layout), _ => panic!("Invalid layout for int literal = {layout:?}"),
}, },
U128(bytes) => const_u128(env, u128::from_ne_bytes(*bytes)).into(), U128(bytes) => const_u128(env, u128::from_ne_bytes(*bytes)).into(),
@ -775,7 +769,7 @@ pub fn build_exp_literal<'a, 'ctx>(
LayoutRepr::Builtin(Builtin::Float(float_width)) => { LayoutRepr::Builtin(Builtin::Float(float_width)) => {
float_with_precision(env, *float, float_width) float_with_precision(env, *float, float_width)
} }
_ => panic!("Invalid layout for float literal = {:?}", layout), _ => panic!("Invalid layout for float literal = {layout:?}"),
}, },
Decimal(bytes) => { Decimal(bytes) => {
@ -2056,7 +2050,7 @@ pub fn get_tag_id<'a, 'ctx>(
match union_layout { match union_layout {
UnionLayout::NonRecursive(_) => { UnionLayout::NonRecursive(_) => {
debug_assert!(argument.is_pointer_value(), "{:?}", argument); debug_assert!(argument.is_pointer_value(), "{argument:?}");
let argument_ptr = argument.into_pointer_value(); let argument_ptr = argument.into_pointer_value();
get_tag_id_wrapped(env, layout_interner, *union_layout, argument_ptr) get_tag_id_wrapped(env, layout_interner, *union_layout, argument_ptr)
@ -3514,10 +3508,7 @@ fn build_switch_ir<'a, 'ctx>(
layout_interner, layout_interner,
layout_interner.get_repr(stored_layout) layout_interner.get_repr(stored_layout)
), ),
"This switch matches on {:?}, but the matched-on symbol {:?} has layout {:?}", "This switch matches on {cond_layout:?}, but the matched-on symbol {cond_symbol:?} has layout {stored_layout:?}"
cond_layout,
cond_symbol,
stored_layout
); );
let cont_block = context.append_basic_block(parent, "cont"); let cont_block = context.append_basic_block(parent, "cont");
@ -3623,7 +3614,7 @@ fn build_switch_ir<'a, 'ctx>(
condition_int_type.const_int(*int, false) condition_int_type.const_int(*int, false)
}; };
let block = context.append_basic_block(parent, format!("branch{}", int).as_str()); let block = context.append_basic_block(parent, format!("branch{int}").as_str());
cases.push((int_val, block)); cases.push((int_val, block));
} }
@ -4032,7 +4023,7 @@ fn expose_function_to_host_help_c_abi_gen_test<'a, 'ctx>(
&[], &[],
); );
let size_function_name: String = format!("roc__{}_size", ident_string); let size_function_name: String = format!("roc__{ident_string}_size");
let size_function = add_func( let size_function = add_func(
env.context, env.context,
@ -4332,7 +4323,7 @@ fn expose_function_to_host_help_c_abi<'a, 'ctx>(
roc_function, roc_function,
arguments, arguments,
return_layout, return_layout,
&format!("{}_generic", c_function_name), &format!("{c_function_name}_generic"),
); );
let c_function = expose_function_to_host_help_c_abi_v2( let c_function = expose_function_to_host_help_c_abi_v2(
@ -4351,7 +4342,7 @@ fn expose_function_to_host_help_c_abi<'a, 'ctx>(
Some(env.context.i64_type().as_basic_type_enum()), Some(env.context.i64_type().as_basic_type_enum()),
&[], &[],
); );
let size_function_name: String = format!("{}_size", c_function_name); let size_function_name: String = format!("{c_function_name}_size");
let size_function = add_func( let size_function = add_func(
env.context, env.context,
@ -4998,7 +4989,7 @@ pub fn build_procedures_expose_expects<'a>(
let mut it = func_solutions.specs(); let mut it = func_solutions.specs();
let func_spec = match it.next() { let func_spec = match it.next() {
Some(spec) => spec, Some(spec) => spec,
None => panic!("no specialization for expect {}", symbol), None => panic!("no specialization for expect {symbol}"),
}; };
debug_assert!( debug_assert!(
@ -5012,7 +5003,7 @@ pub fn build_procedures_expose_expects<'a>(
let name = roc_main_fn.get_name().to_str().unwrap(); let name = roc_main_fn.get_name().to_str().unwrap();
let expect_name = &format!("Expect_{}", name); let expect_name = &format!("Expect_{name}");
let expect_name = env.arena.alloc_str(expect_name); let expect_name = env.arena.alloc_str(expect_name);
expect_names.push(&*expect_name); expect_names.push(&*expect_name);
@ -5024,7 +5015,7 @@ pub fn build_procedures_expose_expects<'a>(
roc_main_fn, roc_main_fn,
top_level.arguments, top_level.arguments,
top_level.result, top_level.result,
&format!("Expect_{}", name), &format!("Expect_{name}"),
); );
} }
@ -5051,7 +5042,7 @@ fn build_procedures_help<'a>(
entry_point, entry_point,
it, it,
) { ) {
Err(e) => panic!("Error in alias analysis: {}", e), Err(e) => panic!("Error in alias analysis: {e}"),
Ok(solutions) => solutions, Ok(solutions) => solutions,
}; };
@ -5147,10 +5138,10 @@ fn func_spec_name<'a>(
let ident_string = symbol.as_str(interns); let ident_string = symbol.as_str(interns);
let module_string = interns.module_ids.get_name(symbol.module_id()).unwrap(); let module_string = interns.module_ids.get_name(symbol.module_id()).unwrap();
write!(buf, "{}_{}_", module_string, ident_string).unwrap(); write!(buf, "{module_string}_{ident_string}_").unwrap();
for byte in func_spec.0.iter() { for byte in func_spec.0.iter() {
write!(buf, "{:x?}", byte).unwrap(); write!(buf, "{byte:x?}").unwrap();
} }
buf buf
@ -5355,7 +5346,7 @@ fn build_closure_caller<'a, 'ctx>(
// STEP 1: build function header // STEP 1: build function header
// e.g. `roc__mainForHost_0_caller` (def_name is `mainForHost_0`) // e.g. `roc__mainForHost_0_caller` (def_name is `mainForHost_0`)
let function_name = format!("roc__{}_caller", def_name); let function_name = format!("roc__{def_name}_caller");
let function_spec = FunctionSpec::cconv(env, CCReturn::Void, None, &argument_types); let function_spec = FunctionSpec::cconv(env, CCReturn::Void, None, &argument_types);
@ -5467,9 +5458,9 @@ fn build_host_exposed_alias_size_help<'a, 'ctx>(
let i64 = env.context.i64_type().as_basic_type_enum(); let i64 = env.context.i64_type().as_basic_type_enum();
let size_function_spec = FunctionSpec::cconv(env, CCReturn::Return, Some(i64), &[]); let size_function_spec = FunctionSpec::cconv(env, CCReturn::Return, Some(i64), &[]);
let size_function_name: String = if let Some(label) = opt_label { let size_function_name: String = if let Some(label) = opt_label {
format!("roc__{}_{}_size", def_name, label) format!("roc__{def_name}_{label}_size")
} else { } else {
format!("roc__{}_size", def_name,) format!("roc__{def_name}_size",)
}; };
let size_function = add_func( let size_function = add_func(
@ -5604,10 +5595,7 @@ fn function_value_by_name_help<'a, 'ctx>(
); );
eprintln!("Is the function defined? If so, maybe there is a problem with the layout"); eprintln!("Is the function defined? If so, maybe there is a problem with the layout");
panic!( panic!("Unrecognized builtin function: {fn_name:?} (symbol: {symbol:?})",)
"Unrecognized builtin function: {:?} (symbol: {:?})",
fn_name, symbol,
)
} else { } else {
// Unrecognized non-builtin function: // Unrecognized non-builtin function:
eprintln!( eprintln!(
@ -5618,10 +5606,7 @@ fn function_value_by_name_help<'a, 'ctx>(
); );
eprintln!("Is the function defined? If so, maybe there is a problem with the layout"); eprintln!("Is the function defined? If so, maybe there is a problem with the layout");
panic!( panic!("Unrecognized non-builtin function: {fn_name:?} (symbol: {symbol:?})",)
"Unrecognized non-builtin function: {:?} (symbol: {:?})",
fn_name, symbol,
)
} }
}) })
} }
@ -6282,7 +6267,7 @@ fn define_global_str_literal<'ctx>(
message.hash(&mut hasher); message.hash(&mut hasher);
let hash = hasher.finish(); let hash = hasher.finish();
format!("_str_literal_{}", hash) format!("_str_literal_{hash}")
}; };
match module.get_global(&name) { match module.get_global(&name) {
@ -6383,7 +6368,7 @@ pub fn add_func<'ctx>(
) -> FunctionValue<'ctx> { ) -> FunctionValue<'ctx> {
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
if let Some(func) = module.get_function(name) { if let Some(func) = module.get_function(name) {
panic!("Attempting to redefine LLVM function {}, which was already defined in this module as:\n\n{:#?}", name, func); panic!("Attempting to redefine LLVM function {name}, which was already defined in this module as:\n\n{func:#?}");
} }
} }

View File

@ -329,8 +329,7 @@ fn build_neq<'a, 'ctx>(
) -> BasicValueEnum<'ctx> { ) -> BasicValueEnum<'ctx> {
if lhs_layout != rhs_layout { if lhs_layout != rhs_layout {
panic!( panic!(
"Inequality of different layouts; did you have a type mismatch?\n{:?} != {:?}", "Inequality of different layouts; did you have a type mismatch?\n{lhs_layout:?} != {rhs_layout:?}"
lhs_layout, rhs_layout
); );
} }
@ -789,7 +788,7 @@ fn build_struct_eq_help<'a, 'ctx>(
.into_int_value() .into_int_value()
}; };
current = ctx.append_basic_block(parent, &format!("eq_step_{}", index)); current = ctx.append_basic_block(parent, &format!("eq_step_{index}"));
env.builder env.builder
.build_conditional_branch(are_equal, current, return_false); .build_conditional_branch(are_equal, current, return_false);

View File

@ -2892,6 +2892,6 @@ fn load_symbol_and_lambda_set<'a, 'ctx>(
let (ptr, layout) = scope.load_symbol_and_layout(symbol); let (ptr, layout) = scope.load_symbol_and_layout(symbol);
match layout_interner.get_repr(layout) { match layout_interner.get_repr(layout) {
LayoutRepr::LambdaSet(lambda_set) => (ptr, lambda_set), LayoutRepr::LambdaSet(lambda_set) => (ptr, lambda_set),
other => panic!("Not a lambda set: {:?}, {:?}", other, ptr), other => panic!("Not a lambda set: {other:?}, {ptr:?}"),
} }
} }

View File

@ -132,7 +132,7 @@ impl<'ctx> PointerToRefcount<'ctx> {
let block = env.builder.get_insert_block().expect("to be in a function"); let block = env.builder.get_insert_block().expect("to be in a function");
let di_location = env.builder.get_current_debug_location().unwrap(); let di_location = env.builder.get_current_debug_location().unwrap();
let fn_name = &format!("decrement_refcounted_ptr_{}", alignment); let fn_name = &format!("decrement_refcounted_ptr_{alignment}");
let function = match env.module.get_function(fn_name) { let function = match env.module.get_function(fn_name) {
Some(function_value) => function_value, Some(function_value) => function_value,
@ -1398,7 +1398,7 @@ pub fn build_reset<'a, 'ctx>(
let union_layout_repr = LayoutRepr::Union(union_layout); let union_layout_repr = LayoutRepr::Union(union_layout);
let layout_id = layout_ids.get(Symbol::DEC, &union_layout_repr); let layout_id = layout_ids.get(Symbol::DEC, &union_layout_repr);
let fn_name = layout_id.to_symbol_string(Symbol::DEC, &env.interns); let fn_name = layout_id.to_symbol_string(Symbol::DEC, &env.interns);
let fn_name = format!("{}_reset", fn_name); let fn_name = format!("{fn_name}_reset");
let dec_function = build_rec_union(env, layout_interner, layout_ids, Mode::Dec, union_layout); let dec_function = build_rec_union(env, layout_interner, layout_ids, Mode::Dec, union_layout);

View File

@ -28,17 +28,14 @@ impl<'a, 'ctx> Scope<'a, 'ctx> {
match self.symbols.get(symbol) { match self.symbols.get(symbol) {
Some((_, ptr)) => *ptr, Some((_, ptr)) => *ptr,
None => panic!( None => panic!("There was no entry for {symbol:?} {symbol} in scope {self:?}"),
"There was no entry for {:?} {} in scope {:?}",
symbol, symbol, self
),
} }
} }
pub fn load_symbol_and_layout(&self, symbol: &Symbol) -> (BasicValueEnum<'ctx>, InLayout<'a>) { pub fn load_symbol_and_layout(&self, symbol: &Symbol) -> (BasicValueEnum<'ctx>, InLayout<'a>) {
match self.symbols.get(symbol) { match self.symbols.get(symbol) {
Some((layout, ptr)) => (*ptr, *layout), Some((layout, ptr)) => (*ptr, *layout),
None => panic!("There was no entry for {:?} in scope {:?}", symbol, self), None => panic!("There was no entry for {symbol:?} in scope {self:?}"),
} }
} }

View File

@ -126,7 +126,7 @@ fn index_struct_value<'a, 'ctx>(
argument, argument,
index as _, index as _,
env.arena env.arena
.alloc(format!("struct_field_access_record_{}", index)), .alloc(format!("struct_field_access_record_{index}")),
); );
let field_layout = field_layouts[index as usize]; let field_layout = field_layouts[index as usize];

View File

@ -313,7 +313,7 @@ impl<'a, 'r> WasmBackend<'a, 'r> {
if let Ok(sym_index) = self.module.linking.find_internal_symbol(START) { if let Ok(sym_index) = self.module.linking.find_internal_symbol(START) {
let fn_index = match self.module.linking.symbol_table[sym_index] { let fn_index = match self.module.linking.symbol_table[sym_index] {
SymInfo::Function(WasmObjectSymbol::ExplicitlyNamed { index, .. }) => index, SymInfo::Function(WasmObjectSymbol::ExplicitlyNamed { index, .. }) => index,
_ => panic!("linker symbol `{}` is not a function", START), _ => panic!("linker symbol `{START}` is not a function"),
}; };
self.module.export.append(Export { self.module.export.append(Export {
name: START, name: START,
@ -463,7 +463,7 @@ impl<'a, 'r> WasmBackend<'a, 'r> {
if DEBUG_SETTINGS.storage_map { if DEBUG_SETTINGS.storage_map {
println!("\nStorage:"); println!("\nStorage:");
for (sym, storage) in self.storage.symbol_storage_map.iter() { for (sym, storage) in self.storage.symbol_storage_map.iter() {
println!("{:?} => {:?}", sym, storage); println!("{sym:?} => {storage:?}");
} }
} }
} }
@ -1424,7 +1424,7 @@ impl<'a, 'r> WasmBackend<'a, 'r> {
.host_lookup .host_lookup
.iter() .iter()
.find(|(fn_name, _)| *fn_name == name) .find(|(fn_name, _)| *fn_name == name)
.unwrap_or_else(|| panic!("The Roc app tries to call `{}` but I can't find it!", name)); .unwrap_or_else(|| panic!("The Roc app tries to call `{name}` but I can't find it!"));
self.called_fns.set(*fn_index as usize, true); self.called_fns.set(*fn_index as usize, true);
@ -1614,7 +1614,7 @@ impl<'a, 'r> WasmBackend<'a, 'r> {
ListLiteralElement::Literal(lit) => { ListLiteralElement::Literal(lit) => {
// This has no Symbol but our storage methods expect one. // This has no Symbol but our storage methods expect one.
// Let's just pretend it was defined in a `Let`. // Let's just pretend it was defined in a `Let`.
let debug_name = format!("{:?}_{}", sym, i); let debug_name = format!("{sym:?}_{i}");
let elem_sym = self.create_symbol(&debug_name); let elem_sym = self.create_symbol(&debug_name);
let expr = Expr::Literal(*lit); let expr = Expr::Literal(*lit);

View File

@ -322,10 +322,7 @@ impl<'a> CodeBuilder<'a> {
self.add_insertion(pushed_at, SETLOCAL, local_id.0); self.add_insertion(pushed_at, SETLOCAL, local_id.0);
} else { } else {
if DEBUG_SETTINGS.instructions { if DEBUG_SETTINGS.instructions {
println!( println!("{symbol:?} has been popped implicitly. Leaving it on the stack.");
"{:?} has been popped implicitly. Leaving it on the stack.",
symbol
);
} }
self.add_insertion(pushed_at, TEELOCAL, local_id.0); self.add_insertion(pushed_at, TEELOCAL, local_id.0);
} }
@ -501,9 +498,7 @@ impl<'a> CodeBuilder<'a> {
debug_assert!( debug_assert!(
stack_size >= pops, stack_size >= pops,
"Wasm value stack underflow. Tried to pop {} but only {} available", "Wasm value stack underflow. Tried to pop {pops} but only {stack_size} available"
pops,
stack_size
); );
let new_len = stack_size - pops; let new_len = stack_size - pops;
@ -517,11 +512,7 @@ impl<'a> CodeBuilder<'a> {
/// Plain instruction without any immediates /// Plain instruction without any immediates
fn inst(&mut self, opcode: OpCode, pops: usize, push: bool) { fn inst(&mut self, opcode: OpCode, pops: usize, push: bool) {
self.inst_base(opcode, pops, push); self.inst_base(opcode, pops, push);
log_instruction!( log_instruction!("{:10}\t\t{:?}", format!("{opcode:?}"), self.vm_block_stack);
"{:10}\t\t{:?}",
format!("{:?}", opcode),
self.vm_block_stack
);
} }
/// Block instruction /// Block instruction
@ -538,7 +529,7 @@ impl<'a> CodeBuilder<'a> {
value_stack: Vec::with_capacity_in(8, self.arena), value_stack: Vec::with_capacity_in(8, self.arena),
}); });
log_instruction!("{:10}\t{:?}", format!("{:?}", opcode), &self.vm_block_stack); log_instruction!("{:10}\t{:?}", format!("{opcode:?}"), &self.vm_block_stack);
} }
fn inst_imm32(&mut self, opcode: OpCode, pops: usize, push: bool, immediate: u32) { fn inst_imm32(&mut self, opcode: OpCode, pops: usize, push: bool, immediate: u32) {
@ -546,7 +537,7 @@ impl<'a> CodeBuilder<'a> {
self.code.encode_u32(immediate); self.code.encode_u32(immediate);
log_instruction!( log_instruction!(
"{:10}\t{}\t{:?}", "{:10}\t{}\t{:?}",
format!("{:?}", opcode), format!("{opcode:?}"),
immediate, immediate,
self.vm_block_stack self.vm_block_stack
); );
@ -558,7 +549,7 @@ impl<'a> CodeBuilder<'a> {
self.code.encode_u32(offset); self.code.encode_u32(offset);
log_instruction!( log_instruction!(
"{:10} {:?} {}\t{:?}", "{:10} {:?} {}\t{:?}",
format!("{:?}", opcode), format!("{opcode:?}"),
align, align,
offset, offset,
self.vm_block_stack self.vm_block_stack
@ -654,7 +645,7 @@ impl<'a> CodeBuilder<'a> {
log_instruction!( log_instruction!(
"{:10}\t{}\t{:?}", "{:10}\t{}\t{:?}",
format!("{:?}", CALL), format!("{CALL:?}"),
function_index, function_index,
self.vm_block_stack self.vm_block_stack
); );
@ -725,7 +716,7 @@ impl<'a> CodeBuilder<'a> {
{ {
log_instruction!( log_instruction!(
"{:10}\t{}\t{:?}", "{:10}\t{}\t{:?}",
format!("{:?}", opcode), format!("{opcode:?}"),
x, x,
self.vm_block_stack self.vm_block_stack
); );

View File

@ -2063,8 +2063,7 @@ impl<'a> LowLevelCall<'a> {
.runtime_representation(backend.storage.symbol_layouts[&self.arguments[1]]); .runtime_representation(backend.storage.symbol_layouts[&self.arguments[1]]);
debug_assert_eq!( debug_assert_eq!(
arg_layout_raw, other_arg_layout, arg_layout_raw, other_arg_layout,
"Cannot do `==` comparison on different types: {:?} vs {:?}", "Cannot do `==` comparison on different types: {arg_layout:?} vs {other_arg_layout:?}"
arg_layout, other_arg_layout
); );
let invert_result = matches!(self.lowlevel, LowLevel::NotEq); let invert_result = matches!(self.lowlevel, LowLevel::NotEq);
@ -2502,7 +2501,7 @@ pub fn call_higher_order_lowlevel<'a>(
} }
} }
}; };
let wrapper_sym = backend.create_symbol(&format!("#wrap#{:?}", fn_name)); let wrapper_sym = backend.create_symbol(&format!("#wrap#{fn_name:?}"));
let wrapper_layout = { let wrapper_layout = {
let mut wrapper_arg_layouts: Vec<InLayout<'a>> = let mut wrapper_arg_layouts: Vec<InLayout<'a>> =
Vec::with_capacity_in(argument_layouts.len() + 1, backend.env.arena); Vec::with_capacity_in(argument_layouts.len() + 1, backend.env.arena);

View File

@ -52,7 +52,7 @@ impl WorldAbilities {
.unwrap() .unwrap()
.insert(module, (store, exposed_types)); .insert(module, (store, exposed_types));
debug_assert!(old_store.is_none(), "{:?} abilities not new", module); debug_assert!(old_store.is_none(), "{module:?} abilities not new");
} }
#[inline(always)] #[inline(always)]

View File

@ -175,7 +175,7 @@ fn start_phase<'a>(
match opt_dep_name { match opt_dep_name {
None => { None => {
panic!("Module {:?} is not in module_cache.module_names", module_id) panic!("Module {module_id:?} is not in module_cache.module_names")
} }
Some(dep_name) => { Some(dep_name) => {
let module_name = dep_name.clone(); let module_name = dep_name.clone();
@ -820,11 +820,11 @@ impl std::fmt::Display for ModuleTiming {
let multiple_make_specializations_passes = module_timing.make_specializations.len() > 1; let multiple_make_specializations_passes = module_timing.make_specializations.len() > 1;
for (i, pass_time) in module_timing.make_specializations.iter().enumerate() { for (i, pass_time) in module_timing.make_specializations.iter().enumerate() {
let suffix = if multiple_make_specializations_passes { let suffix = if multiple_make_specializations_passes {
format!(" (Pass {})", i) format!(" (Pass {i})")
} else { } else {
String::new() String::new()
}; };
report_timing(f, &format!("Make Specializations{}", suffix), *pass_time)?; report_timing(f, &format!("Make Specializations{suffix}"), *pass_time)?;
} }
report_timing(f, "Other", module_timing.other())?; report_timing(f, "Other", module_timing.other())?;
f.write_str("\n")?; f.write_str("\n")?;
@ -1866,7 +1866,7 @@ fn worker_task<'a>(
">>> {}", ">>> {}",
match &task { match &task {
BuildTask::LoadModule { module_name, .. } => { BuildTask::LoadModule { module_name, .. } => {
format!("BuildTask::LoadModule({:?})", module_name) format!("BuildTask::LoadModule({module_name:?})")
} }
BuildTask::Parse { header } => { BuildTask::Parse { header } => {
format!("BuildTask::Parse({})", header.module_path.display()) format!("BuildTask::Parse({})", header.module_path.display())
@ -1879,10 +1879,10 @@ fn worker_task<'a>(
format!("BuildTask::Solve({:?})", module.module_id) format!("BuildTask::Solve({:?})", module.module_id)
} }
BuildTask::BuildPendingSpecializations { module_id, .. } => { BuildTask::BuildPendingSpecializations { module_id, .. } => {
format!("BuildTask::BuildPendingSpecializations({:?})", module_id) format!("BuildTask::BuildPendingSpecializations({module_id:?})")
} }
BuildTask::MakeSpecializations { module_id, .. } => { BuildTask::MakeSpecializations { module_id, .. } => {
format!("BuildTask::MakeSpecializations({:?})", module_id) format!("BuildTask::MakeSpecializations({module_id:?})")
} }
} }
); );
@ -3248,8 +3248,7 @@ fn load_package_from_disk<'a>(
}, },
_parse_state, _parse_state,
)) => Err(LoadingProblem::UnexpectedHeader(format!( )) => Err(LoadingProblem::UnexpectedHeader(format!(
"expected platform/package module, got Interface with header\n{:?}", "expected platform/package module, got Interface with header\n{header:?}"
header
))), ))),
Ok(( Ok((
ast::Module { ast::Module {
@ -3258,8 +3257,7 @@ fn load_package_from_disk<'a>(
}, },
_parse_state, _parse_state,
)) => Err(LoadingProblem::UnexpectedHeader(format!( )) => Err(LoadingProblem::UnexpectedHeader(format!(
"expected platform/package module, got Hosted module with header\n{:?}", "expected platform/package module, got Hosted module with header\n{header:?}"
header
))), ))),
Ok(( Ok((
ast::Module { ast::Module {
@ -3268,8 +3266,7 @@ fn load_package_from_disk<'a>(
}, },
_parse_state, _parse_state,
)) => Err(LoadingProblem::UnexpectedHeader(format!( )) => Err(LoadingProblem::UnexpectedHeader(format!(
"expected platform/package module, got App with header\n{:?}", "expected platform/package module, got App with header\n{header:?}"
header
))), ))),
Ok(( Ok((
ast::Module { ast::Module {
@ -3402,10 +3399,7 @@ fn load_builtin_module_help<'a>(
(info, parse_state) (info, parse_state)
} }
Ok(_) => panic!("invalid header format for builtin module"), Ok(_) => panic!("invalid header format for builtin module"),
Err(e) => panic!( Err(e) => panic!("Hit a parse error in the header of {filename:?}:\n{e:?}"),
"Hit a parse error in the header of {:?}:\n{:?}",
filename, e
),
} }
} }
@ -5583,8 +5577,7 @@ fn build_pending_specializations<'a>(
} }
LayoutProblem::UnresolvedTypeVar(v) => { LayoutProblem::UnresolvedTypeVar(v) => {
let message = format!( let message = format!(
"top level function has unresolved type variable {:?}", "top level function has unresolved type variable {v:?}"
v
); );
procs_base procs_base
.runtime_errors .runtime_errors
@ -5664,8 +5657,7 @@ fn build_pending_specializations<'a>(
} }
LayoutProblem::UnresolvedTypeVar(v) => { LayoutProblem::UnresolvedTypeVar(v) => {
let message = format!( let message = format!(
"top level function has unresolved type variable {:?}", "top level function has unresolved type variable {v:?}"
v
); );
procs_base procs_base
.runtime_errors .runtime_errors
@ -5702,14 +5694,13 @@ fn build_pending_specializations<'a>(
use roc_can::pattern::Pattern; use roc_can::pattern::Pattern;
let symbol = match &loc_pattern.value { let symbol = match &loc_pattern.value {
Pattern::Identifier(_) => { Pattern::Identifier(_) => {
debug_assert!(false, "identifier ended up in Destructure {:?}", symbol); debug_assert!(false, "identifier ended up in Destructure {symbol:?}");
symbol symbol
} }
Pattern::AbilityMemberSpecialization { ident, specializes } => { Pattern::AbilityMemberSpecialization { ident, specializes } => {
debug_assert!( debug_assert!(
false, false,
"ability member ended up in Destructure {:?} specializes {:?}", "ability member ended up in Destructure {ident:?} specializes {specializes:?}"
ident, specializes
); );
symbol symbol
} }
@ -5741,8 +5732,7 @@ fn build_pending_specializations<'a>(
} }
LayoutProblem::UnresolvedTypeVar(v) => { LayoutProblem::UnresolvedTypeVar(v) => {
let message = format!( let message = format!(
"top level function has unresolved type variable {:?}", "top level function has unresolved type variable {v:?}"
v
); );
procs_base procs_base
.runtime_errors .runtime_errors
@ -5808,8 +5798,7 @@ fn build_pending_specializations<'a>(
} }
LayoutProblem::UnresolvedTypeVar(v) => { LayoutProblem::UnresolvedTypeVar(v) => {
let message = format!( let message = format!(
"top level function has unresolved type variable {:?}", "top level function has unresolved type variable {v:?}"
v
); );
procs_base procs_base
.runtime_errors .runtime_errors
@ -5881,8 +5870,7 @@ fn build_pending_specializations<'a>(
} }
LayoutProblem::UnresolvedTypeVar(v) => { LayoutProblem::UnresolvedTypeVar(v) => {
let message = format!( let message = format!(
"top level function has unresolved type variable {:?}", "top level function has unresolved type variable {v:?}"
v
); );
procs_base procs_base
.runtime_errors .runtime_errors

View File

@ -67,8 +67,7 @@ impl MakeSpecializationsDependents {
let entry = self.entry(module_id); let entry = self.entry(module_id);
debug_assert!( debug_assert!(
entry.succ.is_empty(), entry.succ.is_empty(),
"already added successors for module '{:?}'", "already added successors for module '{module_id:?}'"
module_id
); );
entry.succ.extend(succ.into_iter()); entry.succ.extend(succ.into_iter());
@ -516,8 +515,7 @@ impl<'a> Dependencies<'a> {
debug_assert_eq!( debug_assert_eq!(
make_specializations_dependents.0.len(), make_specializations_dependents.0.len(),
default_make_specializations_dependents_len, default_make_specializations_dependents_len,
"more modules were added to the graph: {:?}", "more modules were added to the graph: {make_specializations_dependents:?}"
make_specializations_dependents
); );
output output
@ -567,8 +565,7 @@ impl<'a> Dependencies<'a> {
debug_assert_eq!( debug_assert_eq!(
make_specializations_dependents.0.len(), make_specializations_dependents.0.len(),
default_make_specializations_dependents_len, default_make_specializations_dependents_len,
"more modules were added to the graph: {:?}", "more modules were added to the graph: {make_specializations_dependents:?}"
make_specializations_dependents
); );
output output

View File

@ -106,9 +106,9 @@ fn multiple_modules(subdir: &str, files: Vec<(&str, &str)>) -> Result<LoadedModu
let arena = &arena; let arena = &arena;
match multiple_modules_help(subdir, arena, files) { match multiple_modules_help(subdir, arena, files) {
Err(io_error) => panic!("IO trouble: {:?}", io_error), Err(io_error) => panic!("IO trouble: {io_error:?}"),
Ok(Err(LoadingProblem::FormattedReport(buf))) => Err(buf), Ok(Err(LoadingProblem::FormattedReport(buf))) => Err(buf),
Ok(Err(loading_problem)) => Err(format!("{:?}", loading_problem)), Ok(Err(loading_problem)) => Err(format!("{loading_problem:?}")),
Ok(Ok(mut loaded_module)) => { Ok(Ok(mut loaded_module)) => {
let home = loaded_module.module_id; let home = loaded_module.module_id;
let (filepath, src) = loaded_module.sources.get(&home).unwrap(); let (filepath, src) = loaded_module.sources.get(&home).unwrap();
@ -148,7 +148,7 @@ fn multiple_modules_help<'a>(
// Use a deterministic temporary directory. // Use a deterministic temporary directory.
// We can't have all tests use "tmp" because tests run in parallel, // We can't have all tests use "tmp" because tests run in parallel,
// so append the test name to the tmp path. // so append the test name to the tmp path.
let tmp = format!("tmp/{}", subdir); let tmp = format!("tmp/{subdir}");
let dir = roc_test_utils::TmpDir::new(&tmp); let dir = roc_test_utils::TmpDir::new(&tmp);
let app_module = files.pop().unwrap(); let app_module = files.pop().unwrap();
@ -162,7 +162,7 @@ fn multiple_modules_help<'a>(
fs::create_dir_all(file_path.parent().unwrap())?; fs::create_dir_all(file_path.parent().unwrap())?;
let mut file = File::create(file_path)?; let mut file = File::create(file_path)?;
writeln!(file, "{}", source)?; writeln!(file, "{source}")?;
file_handles.push(file); file_handles.push(file);
} }
@ -173,7 +173,7 @@ fn multiple_modules_help<'a>(
let file_path = dir.path().join(filename); let file_path = dir.path().join(filename);
let full_file_path = file_path.clone(); let full_file_path = file_path.clone();
let mut file = File::create(file_path)?; let mut file = File::create(file_path)?;
writeln!(file, "{}", source)?; writeln!(file, "{source}")?;
file_handles.push(file); file_handles.push(file);
load_and_typecheck(arena, full_file_path, Default::default(), TARGET_INFO) load_and_typecheck(arena, full_file_path, Default::default(), TARGET_INFO)
@ -188,16 +188,16 @@ fn load_fixture(
subs_by_module: ExposedByModule, subs_by_module: ExposedByModule,
) -> LoadedModule { ) -> LoadedModule {
let src_dir = fixtures_dir().join(dir_name); let src_dir = fixtures_dir().join(dir_name);
let filename = src_dir.join(format!("{}.roc", module_name)); let filename = src_dir.join(format!("{module_name}.roc"));
let arena = Bump::new(); let arena = Bump::new();
let loaded = load_and_typecheck(&arena, filename, subs_by_module, TARGET_INFO); let loaded = load_and_typecheck(&arena, filename, subs_by_module, TARGET_INFO);
let mut loaded_module = match loaded { let mut loaded_module = match loaded {
Ok(x) => x, Ok(x) => x,
Err(roc_load_internal::file::LoadingProblem::FormattedReport(report)) => { Err(roc_load_internal::file::LoadingProblem::FormattedReport(report)) => {
println!("{}", report); println!("{report}");
panic!("{}", report); panic!("{}", report);
} }
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
}; };
let home = loaded_module.module_id; let home = loaded_module.module_id;
@ -258,7 +258,7 @@ fn expect_types(mut loaded_module: LoadedModule, mut expected_types: HashMap<&st
let expected_type = expected_types let expected_type = expected_types
.remove(fully_qualified.as_str()) .remove(fully_qualified.as_str())
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic!("Defs included an unexpected symbol: {:?}", fully_qualified) panic!("Defs included an unexpected symbol: {fully_qualified:?}")
}); });
assert_eq!((&symbol, expected_type), (&symbol, actual_str.as_str())); assert_eq!((&symbol, expected_type), (&symbol, actual_str.as_str()));
@ -273,7 +273,7 @@ fn expect_types(mut loaded_module: LoadedModule, mut expected_types: HashMap<&st
let expected_type = expected_types let expected_type = expected_types
.remove(fully_qualified.as_str()) .remove(fully_qualified.as_str())
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic!("Defs included an unexpected symbol: {:?}", fully_qualified) panic!("Defs included an unexpected symbol: {fully_qualified:?}")
}); });
assert_eq!((&symbol, expected_type), (&symbol, actual_str.as_str())); assert_eq!((&symbol, expected_type), (&symbol, actual_str.as_str()));
@ -705,8 +705,7 @@ fn platform_does_not_exist() {
// assert!(report.contains("FILE NOT FOUND"), "report=({})", report); // assert!(report.contains("FILE NOT FOUND"), "report=({})", report);
assert!( assert!(
report.contains("zzz-does-not-exist/main.roc"), report.contains("zzz-does-not-exist/main.roc"),
"report=({})", "report=({report})"
report
); );
} }
Ok(_) => unreachable!("we expect failure here"), Ok(_) => unreachable!("we expect failure here"),

View File

@ -172,7 +172,7 @@ impl Symbol {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub fn contains(self, needle: &str) -> bool { pub fn contains(self, needle: &str) -> bool {
format!("{:?}", self).contains(needle) format!("{self:?}").contains(needle)
} }
} }
@ -194,7 +194,7 @@ impl fmt::Debug for Symbol {
match DEBUG_IDENT_IDS_BY_MODULE_ID.lock() { match DEBUG_IDENT_IDS_BY_MODULE_ID.lock() {
Ok(names) => match &names.get(&(module_id.to_zero_indexed() as u32)) { Ok(names) => match &names.get(&(module_id.to_zero_indexed() as u32)) {
Some(ident_ids) => match ident_ids.get_name(ident_id) { Some(ident_ids) => match ident_ids.get_name(ident_id) {
Some(ident_str) => write!(f, "`{:?}.{}`", module_id, ident_str), Some(ident_str) => write!(f, "`{module_id:?}.{ident_str}`"),
None => fallback_debug_fmt(*self, f), None => fallback_debug_fmt(*self, f),
}, },
None => fallback_debug_fmt(*self, f), None => fallback_debug_fmt(*self, f),
@ -207,7 +207,7 @@ impl fmt::Debug for Symbol {
use std::io::Write; use std::io::Write;
let mut stderr = std::io::stderr(); let mut stderr = std::io::stderr();
writeln!(stderr, "DEBUG INFO: Failed to acquire lock for Debug reading from DEBUG_IDENT_IDS_BY_MODULE_ID, presumably because a thread panicked: {:?}", err).unwrap(); writeln!(stderr, "DEBUG INFO: Failed to acquire lock for Debug reading from DEBUG_IDENT_IDS_BY_MODULE_ID, presumably because a thread panicked: {err:?}").unwrap();
fallback_debug_fmt(*self, f) fallback_debug_fmt(*self, f)
} }
@ -229,7 +229,7 @@ impl fmt::Display for Symbol {
let ident_id = self.ident_id(); let ident_id = self.ident_id();
match ident_id { match ident_id {
IdentId(value) => write!(f, "{:?}.{:?}", module_id, value), IdentId(value) => write!(f, "{module_id:?}.{value:?}"),
} }
} }
} }
@ -244,7 +244,7 @@ fn fallback_debug_fmt(symbol: Symbol, f: &mut fmt::Formatter) -> fmt::Result {
let module_id = symbol.module_id(); let module_id = symbol.module_id();
let ident_id = symbol.ident_id(); let ident_id = symbol.ident_id();
write!(f, "`{:?}.{:?}`", module_id, ident_id) write!(f, "`{module_id:?}.{ident_id:?}`")
} }
/// This is used in Debug builds only, to let us have a Debug instance /// This is used in Debug builds only, to let us have a Debug instance
@ -312,8 +312,8 @@ pub fn get_module_ident_ids<'a>(
all_ident_ids all_ident_ids
.get(module_id) .get(module_id)
.with_context(|| ModuleIdNotFoundSnafu { .with_context(|| ModuleIdNotFoundSnafu {
module_id: format!("{:?}", module_id), module_id: format!("{module_id:?}"),
all_ident_ids: format!("{:?}", all_ident_ids), all_ident_ids: format!("{all_ident_ids:?}"),
}) })
} }
@ -324,7 +324,7 @@ pub fn get_module_ident_ids_mut<'a>(
all_ident_ids all_ident_ids
.get_mut(module_id) .get_mut(module_id)
.with_context(|| ModuleIdNotFoundSnafu { .with_context(|| ModuleIdNotFoundSnafu {
module_id: format!("{:?}", module_id), module_id: format!("{module_id:?}"),
all_ident_ids: "I could not return all_ident_ids here because of borrowing issues.", all_ident_ids: "I could not return all_ident_ids here because of borrowing issues.",
}) })
} }
@ -400,7 +400,7 @@ impl fmt::Debug for ModuleId {
if PRETTY_PRINT_DEBUG_SYMBOLS { if PRETTY_PRINT_DEBUG_SYMBOLS {
match names.try_get(self.to_zero_indexed()) { match names.try_get(self.to_zero_indexed()) {
Some(str_ref) => write!(f, "{}", str_ref), Some(str_ref) => write!(f, "{str_ref}"),
None => { None => {
internal_error!( internal_error!(
"Could not find a Debug name for module ID {} in {:?}", "Could not find a Debug name for module ID {} in {:?}",
@ -645,7 +645,7 @@ impl IdentIds {
pub fn update_key(&mut self, old_name: &str, new_name: &str) -> Result<IdentId, String> { pub fn update_key(&mut self, old_name: &str, new_name: &str) -> Result<IdentId, String> {
match self.interner.find_and_update(old_name, new_name) { match self.interner.find_and_update(old_name, new_name) {
Some(index) => Ok(IdentId(index as u32)), Some(index) => Ok(IdentId(index as u32)),
None => Err(format!("The identifier {:?} is not in IdentIds", old_name)), None => Err(format!("The identifier {old_name:?} is not in IdentIds")),
} }
} }
@ -682,7 +682,7 @@ impl IdentIds {
self.get_name(ident_id) self.get_name(ident_id)
.with_context(|| IdentIdNotFoundSnafu { .with_context(|| IdentIdNotFoundSnafu {
ident_id, ident_id,
ident_ids_str: format!("{:?}", self), ident_ids_str: format!("{self:?}"),
}) })
} }

View File

@ -138,7 +138,7 @@ fn eq_struct<'a>(
) -> Stmt<'a> { ) -> Stmt<'a> {
let mut else_stmt = Stmt::Ret(Symbol::BOOL_TRUE); let mut else_stmt = Stmt::Ret(Symbol::BOOL_TRUE);
for (i, layout) in field_layouts.iter().enumerate().rev() { for (i, layout) in field_layouts.iter().enumerate().rev() {
let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{}", i)); let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{i}"));
let field1_expr = Expr::StructAtIndex { let field1_expr = Expr::StructAtIndex {
index: i as u64, index: i as u64,
field_layouts, field_layouts,
@ -146,7 +146,7 @@ fn eq_struct<'a>(
}; };
let field1_stmt = |next| Stmt::Let(field1_sym, field1_expr, *layout, next); let field1_stmt = |next| Stmt::Let(field1_sym, field1_expr, *layout, next);
let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{}", i)); let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{i}"));
let field2_expr = Expr::StructAtIndex { let field2_expr = Expr::StructAtIndex {
index: i as u64, index: i as u64,
field_layouts, field_layouts,
@ -164,7 +164,7 @@ fn eq_struct<'a>(
) )
.unwrap(); .unwrap();
let eq_call_name = format!("eq_call_{}", i); let eq_call_name = format!("eq_call_{i}");
let eq_call_sym = root.create_symbol(ident_ids, &eq_call_name); let eq_call_sym = root.create_symbol(ident_ids, &eq_call_name);
let eq_call_stmt = |next| Stmt::Let(eq_call_sym, eq_call_expr, LAYOUT_BOOL, next); let eq_call_stmt = |next| Stmt::Let(eq_call_sym, eq_call_expr, LAYOUT_BOOL, next);
@ -488,8 +488,8 @@ fn eq_tag_fields<'a>(
Some(i) => { Some(i) => {
// Implement tail recursion on this RecursivePointer, // Implement tail recursion on this RecursivePointer,
// in the innermost `else` clause after all other fields have been checked // in the innermost `else` clause after all other fields have been checked
let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{}_{}", tag_id, i)); let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{tag_id}_{i}"));
let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{}_{}", tag_id, i)); let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{tag_id}_{i}"));
let field1_expr = Expr::UnionAtIndex { let field1_expr = Expr::UnionAtIndex {
union_layout, union_layout,
@ -533,8 +533,8 @@ fn eq_tag_fields<'a>(
continue; // the tail-recursive field is handled elsewhere continue; // the tail-recursive field is handled elsewhere
} }
let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{}_{}", tag_id, i)); let field1_sym = root.create_symbol(ident_ids, &format!("field_1_{tag_id}_{i}"));
let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{}_{}", tag_id, i)); let field2_sym = root.create_symbol(ident_ids, &format!("field_2_{tag_id}_{i}"));
let field1_expr = Expr::UnionAtIndex { let field1_expr = Expr::UnionAtIndex {
union_layout, union_layout,
@ -560,7 +560,7 @@ fn eq_tag_fields<'a>(
) )
.unwrap(); .unwrap();
let eq_call_name = format!("eq_call_{}", i); let eq_call_name = format!("eq_call_{i}");
let eq_call_sym = root.create_symbol(ident_ids, &eq_call_name); let eq_call_sym = root.create_symbol(ident_ids, &eq_call_name);
stmt = Stmt::Let( stmt = Stmt::Let(

View File

@ -783,7 +783,7 @@ impl<'a> CallerProc<'a> {
.pretty(80) .pretty(80)
.to_string(); .to_string();
println!("{}", doc); println!("{doc}");
} }
Self { Self {

View File

@ -1276,7 +1276,7 @@ fn refcount_struct<'a>(
for (i, field_layout) in field_layouts.iter().enumerate().rev() { for (i, field_layout) in field_layouts.iter().enumerate().rev() {
if layout_interner.contains_refcounted(*field_layout) { if layout_interner.contains_refcounted(*field_layout) {
let field_val = root.create_symbol(ident_ids, &format!("field_val_{}", i)); let field_val = root.create_symbol(ident_ids, &format!("field_val_{i}"));
let field_val_expr = Expr::StructAtIndex { let field_val_expr = Expr::StructAtIndex {
index: i as u64, index: i as u64,
field_layouts, field_layouts,
@ -1284,7 +1284,7 @@ fn refcount_struct<'a>(
}; };
let field_val_stmt = |next| Stmt::Let(field_val, field_val_expr, *field_layout, next); let field_val_stmt = |next| Stmt::Let(field_val, field_val_expr, *field_layout, next);
let mod_unit = root.create_symbol(ident_ids, &format!("mod_field_{}", i)); let mod_unit = root.create_symbol(ident_ids, &format!("mod_field_{i}"));
let mod_args = refcount_args(root, ctx, field_val); let mod_args = refcount_args(root, ctx, field_val);
let mod_expr = root let mod_expr = root
.call_specialized_op(ident_ids, ctx, layout_interner, *field_layout, mod_args) .call_specialized_op(ident_ids, ctx, layout_interner, *field_layout, mod_args)
@ -1758,7 +1758,7 @@ fn refcount_union_tailrec<'a>(
filtered.push((i, *field)); filtered.push((i, *field));
} else { } else {
let field_val = let field_val =
root.create_symbol(ident_ids, &format!("field_{}_{}", tag_id, i)); root.create_symbol(ident_ids, &format!("field_{tag_id}_{i}"));
let field_val_expr = Expr::UnionAtIndex { let field_val_expr = Expr::UnionAtIndex {
union_layout, union_layout,
tag_id, tag_id,
@ -1896,7 +1896,7 @@ fn refcount_tag_fields<'a>(
for (i, field_layout) in field_layouts.iter().rev() { for (i, field_layout) in field_layouts.iter().rev() {
if layout_interner.contains_refcounted(*field_layout) { if layout_interner.contains_refcounted(*field_layout) {
let field_val = root.create_symbol(ident_ids, &format!("field_{}_{}", tag_id, i)); let field_val = root.create_symbol(ident_ids, &format!("field_{tag_id}_{i}"));
let field_val_expr = Expr::UnionAtIndex { let field_val_expr = Expr::UnionAtIndex {
union_layout, union_layout,
tag_id, tag_id,
@ -1905,7 +1905,7 @@ fn refcount_tag_fields<'a>(
}; };
let field_val_stmt = |next| Stmt::Let(field_val, field_val_expr, *field_layout, next); let field_val_stmt = |next| Stmt::Let(field_val, field_val_expr, *field_layout, next);
let mod_unit = root.create_symbol(ident_ids, &format!("mod_field_{}_{}", tag_id, i)); let mod_unit = root.create_symbol(ident_ids, &format!("mod_field_{tag_id}_{i}"));
let mod_args = refcount_args(root, ctx, field_val); let mod_args = refcount_args(root, ctx, field_val);
let mod_expr = root let mod_expr = root
.call_specialized_op(ident_ids, ctx, layout_interner, *field_layout, mod_args) .call_specialized_op(ident_ids, ctx, layout_interner, *field_layout, mod_args)

View File

@ -62,7 +62,7 @@ where
.pretty(80) .pretty(80)
.to_string(); .to_string();
eprintln!("Full source: {}", src); eprintln!("Full source: {src}");
let interpolated_docs = stack( let interpolated_docs = stack(
f, f,

View File

@ -806,7 +806,7 @@ fn specialize_struct<'a, 'i>(
// This value has not been index before, create a new symbol. // This value has not been index before, create a new symbol.
None => { None => {
let field_symbol = let field_symbol =
environment.create_symbol(ident_ids, &format!("field_val_{}", i)); environment.create_symbol(ident_ids, &format!("field_val_{i}"));
let field_val_expr = Expr::StructAtIndex { let field_val_expr = Expr::StructAtIndex {
index: i as u64, index: i as u64,
@ -945,7 +945,7 @@ fn specialize_union<'a, 'i>(
Some(rc) => { Some(rc) => {
let field_symbol = environment.create_symbol( let field_symbol = environment.create_symbol(
ident_ids, ident_ids,
&format!("field_val_{}", i), &format!("field_val_{i}"),
); );
let field_val_expr = Expr::UnionAtIndex { let field_val_expr = Expr::UnionAtIndex {
@ -1134,11 +1134,11 @@ fn specialize_list<'a, 'i>(
// If the symbol is unknown, we have to get the value from the list. // If the symbol is unknown, we have to get the value from the list.
// Should only happen when list elements are discarded. // Should only happen when list elements are discarded.
None => { None => {
let field_symbol = environment let field_symbol =
.create_symbol(ident_ids, &format!("field_val_{}", i)); environment.create_symbol(ident_ids, &format!("field_val_{i}"));
let index_symbol = environment let index_symbol =
.create_symbol(ident_ids, &format!("index_val_{}", i)); environment.create_symbol(ident_ids, &format!("index_val_{i}"));
let dec = arena.alloc(Stmt::Refcounting( let dec = arena.alloc(Stmt::Refcounting(
ModifyRc::Dec(field_symbol), ModifyRc::Dec(field_symbol),

View File

@ -181,8 +181,7 @@ impl<'a> PartialProcs<'a> {
pub fn insert(&mut self, symbol: Symbol, partial_proc: PartialProc<'a>) -> PartialProcId { pub fn insert(&mut self, symbol: Symbol, partial_proc: PartialProc<'a>) -> PartialProcId {
debug_assert!( debug_assert!(
!self.contains_key(symbol), !self.contains_key(symbol),
"The {:?} is inserted as a partial proc twice: that's a bug!", "The {symbol:?} is inserted as a partial proc twice: that's a bug!",
symbol,
); );
let id = PartialProcId(self.symbols.len()); let id = PartialProcId(self.symbols.len());
@ -675,7 +674,7 @@ impl<'a> Specialized<'a> {
} else { } else {
match in_progress { match in_progress {
InProgressProc::InProgress => { InProgressProc::InProgress => {
panic!("Function {:?} ({:?}) is not done specializing", s, l) panic!("Function {s:?} ({l:?}) is not done specializing")
} }
InProgressProc::Done(proc) => Some((s, l, proc)), InProgressProc::Done(proc) => Some((s, l, proc)),
} }
@ -838,11 +837,7 @@ impl<'a> SymbolSpecializations<'a> {
/// Only those bound to number literals can be compiled polymorphically. /// Only those bound to number literals can be compiled polymorphically.
fn mark_eligible(&mut self, symbol: Symbol) { fn mark_eligible(&mut self, symbol: Symbol) {
let _old = self.0.insert(symbol, VecMap::with_capacity(1)); let _old = self.0.insert(symbol, VecMap::with_capacity(1));
debug_assert!( debug_assert!(_old.is_none(), "overwriting specializations for {symbol:?}");
_old.is_none(),
"overwriting specializations for {:?}",
symbol
);
} }
/// Removes all specializations for a symbol, returning the type and symbol of each specialization. /// Removes all specializations for a symbol, returning the type and symbol of each specialization.
@ -945,8 +940,7 @@ impl<'a> Procs<'a> {
.expect("specialization stack is empty"); .expect("specialization stack is empty");
debug_assert_eq!( debug_assert_eq!(
popped, specialization, popped, specialization,
"incorrect popped specialization: passed {:?}, but was {:?}", "incorrect popped specialization: passed {specialization:?}, but was {popped:?}"
specialization, popped
); );
} }
@ -1026,7 +1020,7 @@ impl<'a> Procs<'a> {
) -> Result<ProcLayout<'a>, RuntimeError> { ) -> Result<ProcLayout<'a>, RuntimeError> {
let raw_layout = layout_cache let raw_layout = layout_cache
.raw_from_var(env.arena, annotation, env.subs) .raw_from_var(env.arena, annotation, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
let top_level = ProcLayout::from_raw_named(env.arena, name, raw_layout); let top_level = ProcLayout::from_raw_named(env.arena, name, raw_layout);
@ -1054,7 +1048,7 @@ impl<'a> Procs<'a> {
// if we've already specialized this one, no further work is needed. // if we've already specialized this one, no further work is needed.
if !already_specialized { if !already_specialized {
if self.is_module_thunk(name.name()) { if self.is_module_thunk(name.name()) {
debug_assert!(layout.arguments.is_empty(), "{:?}", name); debug_assert!(layout.arguments.is_empty(), "{name:?}");
} }
let needs_suspended_specialization = let needs_suspended_specialization =
@ -1145,7 +1139,7 @@ impl<'a> Procs<'a> {
); );
} }
Err(error) => { Err(error) => {
panic!("TODO generate a RuntimeError message for {:?}", error); panic!("TODO generate a RuntimeError message for {error:?}");
} }
} }
} }
@ -1234,7 +1228,7 @@ impl<'a> Procs<'a> {
.insert_specialized(proc_name.name(), proc_layout, proc); .insert_specialized(proc_name.name(), proc_layout, proc);
} }
Err(error) => { Err(error) => {
panic!("TODO generate a RuntimeError message for {:?}", error); panic!("TODO generate a RuntimeError message for {error:?}");
} }
} }
} }
@ -1918,13 +1912,13 @@ pub(crate) fn symbol_to_doc_string(symbol: Symbol, force_pretty: bool) -> String
use roc_module::ident::ModuleName; use roc_module::ident::ModuleName;
if pretty_print_ir_symbols() || force_pretty { if pretty_print_ir_symbols() || force_pretty {
format!("{:?}", symbol) format!("{symbol:?}")
} else { } else {
let text = format!("{}", symbol); let text = format!("{symbol}");
if text.starts_with(ModuleName::APP) { if text.starts_with(ModuleName::APP) {
let name: String = text.trim_start_matches(ModuleName::APP).into(); let name: String = text.trim_start_matches(ModuleName::APP).into();
format!("Test{}", name) format!("Test{name}")
} else { } else {
text text
} }
@ -2016,7 +2010,7 @@ impl<'a> Expr<'a> {
.text("Reset { symbol: ") .text("Reset { symbol: ")
.append(symbol_to_doc(alloc, *symbol, pretty)) .append(symbol_to_doc(alloc, *symbol, pretty))
.append(", id: ") .append(", id: ")
.append(format!("{:?}", update_mode)) .append(format!("{update_mode:?}"))
.append(" }"), .append(" }"),
ResetRef { ResetRef {
symbol, symbol,
@ -2025,7 +2019,7 @@ impl<'a> Expr<'a> {
.text("ResetRef { symbol: ") .text("ResetRef { symbol: ")
.append(symbol_to_doc(alloc, *symbol, pretty)) .append(symbol_to_doc(alloc, *symbol, pretty))
.append(", id: ") .append(", id: ")
.append(format!("{:?}", update_mode)) .append(format!("{update_mode:?}"))
.append(" }"), .append(" }"),
Struct(args) => { Struct(args) => {
let it = args.iter().map(|s| symbol_to_doc(alloc, *s, pretty)); let it = args.iter().map(|s| symbol_to_doc(alloc, *s, pretty));
@ -3036,7 +3030,7 @@ fn specialize_external_help<'a>(
let partial_proc_id = match procs.partial_procs.symbol_to_id(name.name()) { let partial_proc_id = match procs.partial_procs.symbol_to_id(name.name()) {
Some(v) => v, Some(v) => v,
None => { None => {
panic!("Cannot find a partial proc for {:?}", name); panic!("Cannot find a partial proc for {name:?}");
} }
}; };
@ -3765,8 +3759,7 @@ fn build_specialized_proc<'a>(
debug_assert_eq!( debug_assert_eq!(
pattern_layouts_len + 1, pattern_layouts_len + 1,
pattern_symbols.len(), pattern_symbols.len(),
"Tried to zip two vecs with different lengths in {:?}!", "Tried to zip two vecs with different lengths in {proc_name:?}!",
proc_name,
); );
let proc_args = proc_args.into_bump_slice(); let proc_args = proc_args.into_bump_slice();
@ -3806,14 +3799,12 @@ fn build_specialized_proc<'a>(
// so far, the problem when hitting this branch was always somewhere else // so far, the problem when hitting this branch was always somewhere else
// I think this branch should not be reachable in a bugfree compiler // I think this branch should not be reachable in a bugfree compiler
panic!( panic!(
"more arguments (according to the layout) than argument symbols for {:?}", "more arguments (according to the layout) than argument symbols for {proc_name:?}"
proc_name
) )
} }
} }
Ordering::Less => panic!( Ordering::Less => panic!(
"more argument symbols than arguments (according to the layout) for {:?}", "more argument symbols than arguments (according to the layout) for {proc_name:?}"
proc_name
), ),
} }
} }
@ -3845,14 +3836,12 @@ fn build_specialized_proc<'a>(
// so far, the problem when hitting this branch was always somewhere else // so far, the problem when hitting this branch was always somewhere else
// I think this branch should not be reachable in a bugfree compiler // I think this branch should not be reachable in a bugfree compiler
panic!( panic!(
"more arguments (according to the layout) than argument symbols for {:?}", "more arguments (according to the layout) than argument symbols for {proc_name:?}"
proc_name
) )
} }
} }
Ordering::Less => panic!( Ordering::Less => panic!(
"more argument symbols than arguments (according to the layout) for {:?}", "more argument symbols than arguments (according to the layout) for {proc_name:?}"
proc_name
), ),
} }
} }
@ -3881,7 +3870,7 @@ fn specialize_variable<'a>(
// TODO: can we get rid of raw entirely? // TODO: can we get rid of raw entirely?
let raw = layout_cache let raw = layout_cache
.raw_from_var(env.arena, fn_var, env.subs) .raw_from_var(env.arena, fn_var, env.subs)
.unwrap_or_else(|err| panic!("TODO handle invalid function {:?}", err)); .unwrap_or_else(|err| panic!("TODO handle invalid function {err:?}"));
let raw = if procs.is_module_thunk(proc_name.name()) { let raw = if procs.is_module_thunk(proc_name.name()) {
match raw { match raw {
@ -4043,7 +4032,7 @@ fn specialize_naked_symbol<'a>(
return result; return result;
} else if env.is_imported_symbol(symbol) { } else if env.is_imported_symbol(symbol) {
match layout_cache.from_var(env.arena, variable, env.subs) { match layout_cache.from_var(env.arena, variable, env.subs) {
Err(e) => panic!("invalid layout {:?}", e), Err(e) => panic!("invalid layout {e:?}"),
Ok(_) => { Ok(_) => {
// this is a 0-arity thunk // this is a 0-arity thunk
let result = call_by_name( let result = call_by_name(
@ -4573,7 +4562,7 @@ pub fn with_hole<'a>(
let layout = layout_cache let layout = layout_cache
.from_var(env.arena, branch_var, env.subs) .from_var(env.arena, branch_var, env.subs)
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
panic!("TODO turn fn_var into a RuntimeError {:?}", err) panic!("TODO turn fn_var into a RuntimeError {err:?}")
}); });
let param = Param { let param = Param {
@ -4639,7 +4628,7 @@ pub fn with_hole<'a>(
let layout = layout_cache let layout = layout_cache
.from_var(env.arena, expr_var, env.subs) .from_var(env.arena, expr_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
let param = Param { let param = Param {
symbol: assigned, symbol: assigned,
@ -4692,7 +4681,7 @@ pub fn with_hole<'a>(
let elem_layout = layout_cache let elem_layout = layout_cache
.from_var(env.arena, elem_var, env.subs) .from_var(env.arena, elem_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
for arg_expr in loc_elems.into_iter() { for arg_expr in loc_elems.into_iter() {
if let Some(literal) = if let Some(literal) =
@ -5033,7 +5022,7 @@ pub fn with_hole<'a>(
let record_layout = layout_cache let record_layout = layout_cache
.from_var(env.arena, record_var, env.subs) .from_var(env.arena, record_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
let field_layouts = match layout_cache.get_repr(record_layout) { let field_layouts = match layout_cache.get_repr(record_layout) {
LayoutRepr::Struct(field_layouts) => field_layouts, LayoutRepr::Struct(field_layouts) => field_layouts,
@ -5181,7 +5170,7 @@ pub fn with_hole<'a>(
if let Err(e) = inserted { if let Err(e) = inserted {
return runtime_error( return runtime_error(
env, env,
env.arena.alloc(format!("RuntimeError: {:?}", e,)), env.arena.alloc(format!("RuntimeError: {e:?}",)),
); );
} else { } else {
drop(inserted); drop(inserted);
@ -5754,7 +5743,7 @@ fn compile_struct_like_access<'a>(
let layout = layout_cache let layout = layout_cache
.from_var(env.arena, elem_var, env.subs) .from_var(env.arena, elem_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
Stmt::Let(assigned, expr, layout, hole) Stmt::Let(assigned, expr, layout, hole)
} }
@ -6197,7 +6186,7 @@ fn convert_tag_union<'a>(
// Layout will unpack this unwrapped tack if it only has one (non-zero-sized) field // Layout will unpack this unwrapped tack if it only has one (non-zero-sized) field
let layout = layout_cache let layout = layout_cache
.from_var(env.arena, variant_var, env.subs) .from_var(env.arena, variant_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
// even though this was originally a Tag, we treat it as a Struct from now on // even though this was originally a Tag, we treat it as a Struct from now on
let stmt = if let [only_field] = field_symbols { let stmt = if let [only_field] = field_symbols {
@ -6231,7 +6220,7 @@ fn convert_tag_union<'a>(
// Layout will unpack this unwrapped tack if it only has one (non-zero-sized) field // Layout will unpack this unwrapped tack if it only has one (non-zero-sized) field
let layout = layout_cache let layout = layout_cache
.from_var(env.arena, variant_var, env.subs) .from_var(env.arena, variant_var, env.subs)
.unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {:?}", err)); .unwrap_or_else(|err| panic!("TODO turn fn_var into a RuntimeError {err:?}"));
// even though this was originally a Tag, we treat it as a Struct from now on // even though this was originally a Tag, we treat it as a Struct from now on
let stmt = if let [only_field] = field_symbols { let stmt = if let [only_field] = field_symbols {
@ -6496,8 +6485,7 @@ fn tag_union_to_function<'a>(
Err(e) => runtime_error( Err(e) => runtime_error(
env, env,
env.arena.alloc(format!( env.arena.alloc(format!(
"Could not produce tag function due to a runtime error: {:?}", "Could not produce tag function due to a runtime error: {e:?}",
e,
)), )),
), ),
} }
@ -8284,17 +8272,13 @@ fn call_by_name<'a>(
match layout_cache.raw_from_var(env.arena, fn_var, env.subs) { match layout_cache.raw_from_var(env.arena, fn_var, env.subs) {
Err(LayoutProblem::UnresolvedTypeVar(var)) => { Err(LayoutProblem::UnresolvedTypeVar(var)) => {
let msg = format!( let msg = format!(
"Hit an unresolved type variable {:?} when creating a layout for {:?} (var {:?})", "Hit an unresolved type variable {var:?} when creating a layout for {proc_name:?} (var {fn_var:?})"
var, proc_name, fn_var
); );
evaluate_arguments_then_runtime_error(env, procs, layout_cache, msg, loc_args) evaluate_arguments_then_runtime_error(env, procs, layout_cache, msg, loc_args)
} }
Err(LayoutProblem::Erroneous) => { Err(LayoutProblem::Erroneous) => {
let msg = format!( let msg = format!("Hit an erroneous type when creating a layout for {proc_name:?}");
"Hit an erroneous type when creating a layout for {:?}",
proc_name
);
evaluate_arguments_then_runtime_error(env, procs, layout_cache, msg, loc_args) evaluate_arguments_then_runtime_error(env, procs, layout_cache, msg, loc_args)
} }
@ -8446,9 +8430,7 @@ fn call_by_name_help<'a>(
Some(name) => { Some(name) => {
debug_assert!( debug_assert!(
iter_lambda_names.next().is_none(), iter_lambda_names.next().is_none(),
"Somehow, call by name for {:?} has multiple capture niches: {:?}", "Somehow, call by name for {proc_name:?} has multiple capture niches: {lambda_set:?}"
proc_name,
lambda_set
); );
name name
} }
@ -8487,8 +8469,7 @@ fn call_by_name_help<'a>(
debug_assert_eq!( debug_assert_eq!(
argument_layouts.len(), argument_layouts.len(),
field_symbols.len(), field_symbols.len(),
"see call_by_name for background (scroll down a bit), function is {:?}", "see call_by_name for background (scroll down a bit), function is {proc_name:?}",
proc_name,
); );
call_specialized_proc( call_specialized_proc(
env, env,
@ -8539,8 +8520,7 @@ fn call_by_name_help<'a>(
debug_assert_eq!( debug_assert_eq!(
argument_layouts.len(), argument_layouts.len(),
field_symbols.len(), field_symbols.len(),
"see call_by_name for background (scroll down a bit), function is {:?}", "see call_by_name for background (scroll down a bit), function is {proc_name:?}",
proc_name,
); );
let field_symbols = field_symbols.into_bump_slice(); let field_symbols = field_symbols.into_bump_slice();
@ -8592,8 +8572,7 @@ fn call_by_name_help<'a>(
debug_assert_eq!( debug_assert_eq!(
argument_layouts.len(), argument_layouts.len(),
field_symbols.len(), field_symbols.len(),
"see call_by_name for background (scroll down a bit), function is {:?}", "see call_by_name for background (scroll down a bit), function is {proc_name:?}",
proc_name,
); );
let field_symbols = field_symbols.into_bump_slice(); let field_symbols = field_symbols.into_bump_slice();
@ -8784,8 +8763,7 @@ fn call_by_name_module_thunk<'a>(
Ok((proc, raw_layout)) => { Ok((proc, raw_layout)) => {
debug_assert!( debug_assert!(
raw_layout.is_zero_argument_thunk(), raw_layout.is_zero_argument_thunk(),
"but actually {:?}", "but actually {raw_layout:?}"
raw_layout
); );
let was_present = procs let was_present = procs
@ -9044,10 +9022,9 @@ where
} }
None => { None => {
eprintln!( eprintln!(
"a function passed to `{:?}` LowLevel call has an empty lambda set! "a function passed to `{op:?}` LowLevel call has an empty lambda set!
The most likely reason is that some symbol you use is not in scope. The most likely reason is that some symbol you use is not in scope.
", "
op
); );
hole.clone() hole.clone()
@ -10073,7 +10050,7 @@ fn unique_glue_symbol(
use std::fmt::Write; use std::fmt::Write;
let mut string = bumpalo::collections::String::with_capacity_in(32, arena); let mut string = bumpalo::collections::String::with_capacity_in(32, arena);
let _result = write!(&mut string, "roc__getter_{}_{}", module_name, unique_id); let _result = write!(&mut string, "roc__getter_{module_name}_{unique_id}");
debug_assert_eq!(_result, Ok(())); // This should never fail, but doesn't hurt to debug-check! debug_assert_eq!(_result, Ok(())); // This should never fail, but doesn't hurt to debug-check!
let bump_string = string.into_bump_str(); let bump_string = string.into_bump_str();

View File

@ -775,8 +775,7 @@ fn to_relevant_branch<'a>(
// if there is no test, the pattern should not require any // if there is no test, the pattern should not require any
debug_assert!( debug_assert!(
matches!(pattern, Pattern::Identifier(_) | Pattern::Underscore,), matches!(pattern, Pattern::Identifier(_) | Pattern::Underscore,),
"{:?}", "{pattern:?}",
pattern,
); );
Some(branch.clone()) Some(branch.clone())

View File

@ -165,8 +165,7 @@ impl<'a> LayoutCache<'a> {
let Cacheable(value, criteria) = Layout::from_var(&mut env, var); let Cacheable(value, criteria) = Layout::from_var(&mut env, var);
debug_assert!( debug_assert!(
criteria.is_cacheable(), criteria.is_cacheable(),
"{:?} not cacheable as top-level", "{value:?} not cacheable as top-level"
value
); );
value value
} }
@ -192,8 +191,7 @@ impl<'a> LayoutCache<'a> {
let Cacheable(value, criteria) = RawFunctionLayout::from_var(&mut env, var); let Cacheable(value, criteria) = RawFunctionLayout::from_var(&mut env, var);
debug_assert!( debug_assert!(
criteria.is_cacheable(), criteria.is_cacheable(),
"{:?} not cacheable as top-level", "{value:?} not cacheable as top-level"
value
); );
value value
} }
@ -1485,9 +1483,7 @@ impl<'a> LambdaSet<'a> {
{ {
debug_assert!( debug_assert!(
self.contains(function_symbol), self.contains(function_symbol),
"function symbol {:?} not in set {:?}", "function symbol {function_symbol:?} not in set {self:?}"
function_symbol,
self
); );
let comparator = |other_name: Symbol, other_captures_layouts: &[InLayout<'a>]| { let comparator = |other_name: Symbol, other_captures_layouts: &[InLayout<'a>]| {
@ -3210,10 +3206,7 @@ fn layout_from_flat_type<'a>(
Cacheable(Ok(boxed_layout), criteria) Cacheable(Ok(boxed_layout), criteria)
} }
_ => { _ => {
panic!( panic!("TODO layout_from_flat_type for Apply({symbol:?}, {args:?})");
"TODO layout_from_flat_type for Apply({:?}, {:?})",
symbol, args
);
} }
} }
} }
@ -3664,7 +3657,7 @@ pub fn union_sorted_tags<'a>(
Error => return Err(LayoutProblem::Erroneous), Error => return Err(LayoutProblem::Erroneous),
other => panic!("invalid content in tag union variable: {:?}", other), other => panic!("invalid content in tag union variable: {other:?}"),
} }
} }
}; };
@ -4387,7 +4380,7 @@ pub fn ext_var_is_empty_tag_union(subs: &Subs, tag_ext: TagExt) -> bool {
} }
// So that we can continue compiling in the presence of errors // So that we can continue compiling in the presence of errors
Error => ext_fields.is_empty(), Error => ext_fields.is_empty(),
_ => panic!("invalid content in ext_var: {:?}", content), _ => panic!("invalid content in ext_var: {content:?}"),
} }
} }
} }
@ -4442,17 +4435,14 @@ fn layout_from_num_content<'a>(
Symbol::NUM_DEC => Ok(Layout::DEC), Symbol::NUM_DEC => Ok(Layout::DEC),
_ => { _ => {
panic!( panic!("Invalid Num.Num type application: Apply({symbol:?}, {args:?})");
"Invalid Num.Num type application: Apply({:?}, {:?})",
symbol, args
);
} }
}, },
Alias(_, _, _, _) => { Alias(_, _, _, _) => {
todo!("TODO recursively resolve type aliases in num_from_content"); todo!("TODO recursively resolve type aliases in num_from_content");
} }
Structure(_) | RangedNumber(..) | LambdaSet(_) => { Structure(_) | RangedNumber(..) | LambdaSet(_) => {
panic!("Invalid Num.Num type application: {:?}", content); panic!("Invalid Num.Num type application: {content:?}");
} }
Error => Err(LayoutProblem::Erroneous), Error => Err(LayoutProblem::Erroneous),
}; };

View File

@ -743,8 +743,8 @@ impl<'a> CommentOrNewline<'a> {
use CommentOrNewline::*; use CommentOrNewline::*;
match self { match self {
Newline => "\n".to_owned(), Newline => "\n".to_owned(),
LineComment(comment_str) => format!("#{}", comment_str), LineComment(comment_str) => format!("#{comment_str}"),
DocComment(comment_str) => format!("##{}", comment_str), DocComment(comment_str) => format!("##{comment_str}"),
} }
} }

View File

@ -136,7 +136,7 @@ impl<'a> fmt::Debug for State<'a> {
write!(f, "State {{")?; write!(f, "State {{")?;
match std::str::from_utf8(self.bytes()) { match std::str::from_utf8(self.bytes()) {
Ok(string) => write!(f, "\n\tbytes: [utf8] {:?}", string)?, Ok(string) => write!(f, "\n\tbytes: [utf8] {string:?}")?,
Err(_) => write!(f, "\n\tbytes: [invalid utf8] {:?}", self.bytes())?, Err(_) => write!(f, "\n\tbytes: [invalid utf8] {:?}", self.bytes())?,
} }
@ -151,5 +151,5 @@ fn state_size() {
// cache line. // cache line.
let state_size = std::mem::size_of::<State>(); let state_size = std::mem::size_of::<State>();
let maximum = std::mem::size_of::<usize>() * 8; let maximum = std::mem::size_of::<usize>() * 8;
assert!(state_size <= maximum, "{:?} <= {:?}", state_size, maximum); assert!(state_size <= maximum, "{state_size:?} <= {maximum:?}");
} }

View File

@ -81,7 +81,7 @@ mod test_parse {
#[test] #[test]
fn string_with_escaped_char_at_end() { fn string_with_escaped_char_at_end() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""abcd{}""#, esc), |esc| format!(r#""abcd{esc}""#),
|esc, arena| bumpalo::vec![in arena; Plaintext("abcd"), EscapedChar(esc)], |esc, arena| bumpalo::vec![in arena; Plaintext("abcd"), EscapedChar(esc)],
); );
} }
@ -89,7 +89,7 @@ mod test_parse {
#[test] #[test]
fn string_with_escaped_char_in_front() { fn string_with_escaped_char_in_front() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""{}abcd""#, esc), |esc| format!(r#""{esc}abcd""#),
|esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abcd")], |esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abcd")],
); );
} }
@ -97,7 +97,7 @@ mod test_parse {
#[test] #[test]
fn string_with_escaped_char_in_middle() { fn string_with_escaped_char_in_middle() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""ab{}cd""#, esc), |esc| format!(r#""ab{esc}cd""#),
|esc, arena| bumpalo::vec![in arena; Plaintext("ab"), EscapedChar(esc), Plaintext("cd")], |esc, arena| bumpalo::vec![in arena; Plaintext("ab"), EscapedChar(esc), Plaintext("cd")],
); );
} }
@ -105,7 +105,7 @@ mod test_parse {
#[test] #[test]
fn string_with_multiple_escaped_chars() { fn string_with_multiple_escaped_chars() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""{}abc{}de{}fghi{}""#, esc, esc, esc, esc), |esc| format!(r#""{esc}abc{esc}de{esc}fghi{esc}""#),
|esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abc"), EscapedChar(esc), Plaintext("de"), EscapedChar(esc), Plaintext("fghi"), EscapedChar(esc)], |esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abc"), EscapedChar(esc), Plaintext("de"), EscapedChar(esc), Plaintext("fghi"), EscapedChar(esc)],
); );
} }
@ -247,7 +247,7 @@ mod test_parse {
// These can potentially be whole numbers. `Display` omits the decimal point for those, // These can potentially be whole numbers. `Display` omits the decimal point for those,
// causing them to no longer be parsed as fractional numbers by Roc. // causing them to no longer be parsed as fractional numbers by Roc.
// Using `Debug` instead of `Display` ensures they always have a decimal point. // Using `Debug` instead of `Display` ensures they always have a decimal point.
let float_string = format!("{:?}", num); let float_string = format!("{num:?}");
assert_parses_to(float_string.as_str(), Float(float_string.as_str())); assert_parses_to(float_string.as_str(), Float(float_string.as_str()));
} }
@ -284,7 +284,7 @@ mod test_parse {
// It should occur twice in the debug output - once for the pattern, // It should occur twice in the debug output - once for the pattern,
// and then again for the lookup. // and then again for the lookup.
let occurrences = format!("{:?}", actual).split("isTest").count() - 1; let occurrences = format!("{actual:?}").split("isTest").count() - 1;
assert_eq!(occurrences, 2); assert_eq!(occurrences, 2);
} }

View File

@ -613,11 +613,10 @@ impl RuntimeError {
match self { match self {
DegenerateBranch(region) => { DegenerateBranch(region) => {
format!( format!(
"Hit a branch pattern that does not bind all symbols its body needs, at {:?}", "Hit a branch pattern that does not bind all symbols its body needs, at {region:?}"
region
) )
} }
err => format!("{:?}", err), err => format!("{err:?}"),
} }
} }
} }

View File

@ -434,10 +434,7 @@ fn test_line_info() {
} else { } else {
"\n" // HACK! pretend there's an extra newline on the end, strictly so we can do the comparison "\n" // HACK! pretend there's an extra newline on the end, strictly so we can do the comparison
}; };
println!( println!("checking {input:?} {offset:?}, expecting {expected:?}");
"checking {:?} {:?}, expecting {:?}",
input, offset, expected
);
let line_column = info.convert_offset(offset as u32); let line_column = info.convert_offset(offset as u32);
assert!( assert!(
Some(line_column) > last, Some(line_column) > last,

View File

@ -1322,8 +1322,7 @@ pub fn type_implementing_specialization(
.filter(|mia| mia.ability == ability) .filter(|mia| mia.ability == ability)
.count() .count()
} < 2, } < 2,
"Multiple variables bound to an ability - this is ambiguous and should have been caught in canonicalization: {:?}", "Multiple variables bound to an ability - this is ambiguous and should have been caught in canonicalization: {specialization_must_implement_constraints:?}"
specialization_must_implement_constraints
); );
specialization_must_implement_constraints specialization_must_implement_constraints

View File

@ -27,14 +27,14 @@ impl Pools {
pub fn get_mut(&mut self, rank: Rank) -> &mut Vec<Variable> { pub fn get_mut(&mut self, rank: Rank) -> &mut Vec<Variable> {
match self.0.get_mut(rank.into_usize()) { match self.0.get_mut(rank.into_usize()) {
Some(reference) => reference, Some(reference) => reference,
None => panic!("Compiler bug: could not find pool at rank {}", rank), None => panic!("Compiler bug: could not find pool at rank {rank}"),
} }
} }
pub fn get(&self, rank: Rank) -> &Vec<Variable> { pub fn get(&self, rank: Rank) -> &Vec<Variable> {
match self.0.get(rank.into_usize()) { match self.0.get(rank.into_usize()) {
Some(reference) => reference, Some(reference) => reference,
None => panic!("Compiler bug: could not find pool at rank {}", rank), None => panic!("Compiler bug: could not find pool at rank {rank}"),
} }
} }

View File

@ -404,7 +404,7 @@ fn solve(
if it.peek().is_some() { if it.peek().is_some() {
let failing: Vec<_> = it.collect(); let failing: Vec<_> = it.collect();
println!("Rigids {:?}", &rigid_vars); println!("Rigids {:?}", &rigid_vars);
println!("Failing {:?}", failing); println!("Failing {failing:?}");
debug_assert!(false); debug_assert!(false);
} }
}); });
@ -1739,8 +1739,7 @@ fn check_ability_specialization(
); );
debug_assert!( debug_assert!(
!awaiting_specializations.waiting_for(impl_key), !awaiting_specializations.waiting_for(impl_key),
"still have lambda sets waiting for {:?}, but it was just resolved", "still have lambda sets waiting for {impl_key:?}, but it was just resolved"
impl_key
); );
} }
} }

View File

@ -187,9 +187,9 @@ fn trace_compaction_step_1(subs: &Subs, c_a: Variable, uls_a: &[Variable]) {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(","); .join(",");
eprintln!("===lambda set compaction==="); eprintln!("===lambda set compaction===");
eprintln!(" concrete type: {:?}", c_a); eprintln!(" concrete type: {c_a:?}");
eprintln!(" step 1:"); eprintln!(" step 1:");
eprintln!(" uls_a = {{ {} }}", uls_a); eprintln!(" uls_a = {{ {uls_a} }}");
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -205,7 +205,7 @@ fn trace_compaction_step_2(subs: &Subs, uls_a: &[Variable]) {
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(","); .join(",");
eprintln!(" step 2:"); eprintln!(" step 2:");
eprintln!(" uls_a' = {{ {} }}", uls_a); eprintln!(" uls_a' = {{ {uls_a} }}");
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -226,9 +226,9 @@ fn trace_compaction_step_3iter_start(
); );
let t_f1 = roc_types::subs::SubsFmtContent(subs.get_content_without_compacting(t_f1), subs); let t_f1 = roc_types::subs::SubsFmtContent(subs.get_content_without_compacting(t_f1), subs);
let t_f2 = roc_types::subs::SubsFmtContent(subs.get_content_without_compacting(t_f2), subs); let t_f2 = roc_types::subs::SubsFmtContent(subs.get_content_without_compacting(t_f2), subs);
eprintln!(" - iteration: {:?}", iteration_lambda_set); eprintln!(" - iteration: {iteration_lambda_set:?}");
eprintln!(" {:?}", t_f1); eprintln!(" {t_f1:?}");
eprintln!(" ~ {:?}", t_f2); eprintln!(" ~ {t_f2:?}");
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@ -239,7 +239,7 @@ fn trace_compaction_step_3iter_end(subs: &Subs, t_f_result: Variable, skipped: b
if skipped { if skipped {
eprintln!(" SKIP"); eprintln!(" SKIP");
} }
eprintln!(" = {:?}\n", t_f_result); eprintln!(" = {t_f_result:?}\n");
} }
macro_rules! trace_compact { macro_rules! trace_compact {
@ -536,7 +536,7 @@ fn compact_lambda_set<P: Phase>(
Err(()) => { Err(()) => {
// Do nothing other than to remove the concrete lambda to drop from the lambda set, // Do nothing other than to remove the concrete lambda to drop from the lambda set,
// which we already did in 1b above. // which we already did in 1b above.
trace_compact!(3iter_end_skipped. env.subs, t_f1); trace_compact!(3iter_end_skipped.env.subs, t_f1);
return OneCompactionResult::Compacted { return OneCompactionResult::Compacted {
new_obligations: Default::default(), new_obligations: Default::default(),
new_lambda_sets_to_specialize: Default::default(), new_lambda_sets_to_specialize: Default::default(),
@ -559,7 +559,7 @@ fn compact_lambda_set<P: Phase>(
Err(()) => { Err(()) => {
// Do nothing other than to remove the concrete lambda to drop from the lambda set, // Do nothing other than to remove the concrete lambda to drop from the lambda set,
// which we already did in 1b above. // which we already did in 1b above.
trace_compact!(3iter_end_skipped. env.subs, t_f1); trace_compact!(3iter_end_skipped.env.subs, t_f1);
return OneCompactionResult::Compacted { return OneCompactionResult::Compacted {
new_obligations: Default::default(), new_obligations: Default::default(),
new_lambda_sets_to_specialize: Default::default(), new_lambda_sets_to_specialize: Default::default(),
@ -572,7 +572,7 @@ fn compact_lambda_set<P: Phase>(
let t_f2 = deep_copy_var_in(env, target_rank, t_f2, env.arena); let t_f2 = deep_copy_var_in(env, target_rank, t_f2, env.arena);
// 3. Unify `t_f1 ~ t_f2`. // 3. Unify `t_f1 ~ t_f2`.
trace_compact!(3iter_start. env.subs, this_lambda_set, t_f1, t_f2); trace_compact!(3iter_start.env.subs, this_lambda_set, t_f1, t_f2);
let (vars, new_obligations, new_lambda_sets_to_specialize, _meta) = unify( let (vars, new_obligations, new_lambda_sets_to_specialize, _meta) = unify(
&mut env.uenv(), &mut env.uenv(),
t_f1, t_f1,
@ -581,7 +581,7 @@ fn compact_lambda_set<P: Phase>(
Polarity::Pos, Polarity::Pos,
) )
.expect_success("ambient functions don't unify"); .expect_success("ambient functions don't unify");
trace_compact!(3iter_end. env.subs, t_f1); trace_compact!(3iter_end.env.subs, t_f1);
env.introduce(target_rank, &vars); env.introduce(target_rank, &vars);

View File

@ -49,7 +49,7 @@ mod solve_expr {
exposed_to_host.retain(|s, _| !abilities_store.is_specialization_name(*s)); exposed_to_host.retain(|s, _| !abilities_store.is_specialization_name(*s));
debug_assert!(exposed_to_host.len() == 1, "{:?}", exposed_to_host); debug_assert!(exposed_to_host.len() == 1, "{exposed_to_host:?}");
let (_symbol, variable) = exposed_to_host.into_iter().next().unwrap(); let (_symbol, variable) = exposed_to_host.into_iter().next().unwrap();
let actual_str = name_and_print_var(variable, subs, home, &interns, DebugPrint::NOTHING); let actual_str = name_and_print_var(variable, subs, home, &interns, DebugPrint::NOTHING);
@ -61,8 +61,7 @@ mod solve_expr {
assert!( assert!(
can_problems.is_empty(), can_problems.is_empty(),
"Canonicalization problems: {}", "Canonicalization problems: {can_problems}"
can_problems
); );
assert_eq!(actual, expected.to_string()); assert_eq!(actual, expected.to_string());
@ -73,17 +72,13 @@ mod solve_expr {
assert!( assert!(
can_problems.is_empty(), can_problems.is_empty(),
"Canonicalization problems: {}", "Canonicalization problems: {can_problems}"
can_problems
); );
if !type_problems.is_empty() { if !type_problems.is_empty() {
// fail with an assert, but print the problems normally so rust doesn't try to diff // fail with an assert, but print the problems normally so rust doesn't try to diff
// an empty vec with the problems. // an empty vec with the problems.
panic!( panic!("expected:\n{expected:?}\ninferred:\n{actual:?}\nproblems:\n{type_problems}",);
"expected:\n{:?}\ninferred:\n{:?}\nproblems:\n{}",
expected, actual, type_problems,
);
} }
assert_eq!(actual, expected.to_string()); assert_eq!(actual, expected.to_string());
} }

View File

@ -335,7 +335,7 @@ fn assemble_derived_golden(
specialization_lsets.sort_by_key(|(region, _)| *region); specialization_lsets.sort_by_key(|(region, _)| *region);
for (region, var) in specialization_lsets { for (region, var) in specialization_lsets {
let pretty_lset = print_var(var, false); let pretty_lset = print_var(var, false);
let _ = writeln!(pretty_buf, "# @<{}>: {}", region, pretty_lset); let _ = writeln!(pretty_buf, "# @<{region}>: {pretty_lset}");
} }
pretty_buf.push_str(derived_source); pretty_buf.push_str(derived_source);
@ -476,10 +476,7 @@ fn check_derived_typechecks_and_golden(
.render_raw(80, &mut roc_reporting::report::CiWrite::new(&mut buf)) .render_raw(80, &mut roc_reporting::report::CiWrite::new(&mut buf))
.unwrap(); .unwrap();
panic!( panic!("Derived does not typecheck:\n{buf}\nDerived def:\n{derived_program}");
"Derived does not typecheck:\n{}\nDerived def:\n{}",
buf, derived_program
);
} }
let golden = assemble_derived_golden( let golden = assemble_derived_golden(

View File

@ -65,7 +65,7 @@ fn roc_function<'a, 'b>(
let (main_fn_name, errors, lib) = let (main_fn_name, errors, lib) =
helpers::llvm::helper(arena, config, source, arena.alloc(context)); helpers::llvm::helper(arena, config, source, arena.alloc(context));
assert!(errors.is_empty(), "Encountered errors:\n{}", errors); assert!(errors.is_empty(), "Encountered errors:\n{errors}");
run_roc_dylib!(arena.alloc(lib), main_fn_name, &Input, Output) run_roc_dylib!(arena.alloc(lib), main_fn_name, &Input, Output)
} }

View File

@ -94,7 +94,7 @@ fn roc_function<'a>(
let (main_fn_name, errors, lib) = let (main_fn_name, errors, lib) =
helpers::llvm::helper(arena, config, source, arena.alloc(context)); helpers::llvm::helper(arena, config, source, arena.alloc(context));
assert!(errors.is_empty(), "Encountered errors:\n{}", errors); assert!(errors.is_empty(), "Encountered errors:\n{errors}");
run_roc_dylib!(arena.alloc(lib), main_fn_name, *mut Input, Output) run_roc_dylib!(arena.alloc(lib), main_fn_name, *mut Input, Output)
} }

View File

@ -41,8 +41,8 @@ fn build_wasm_linking_test_host() {
let host_wasm: &str = host_wasm_path.to_str().unwrap(); let host_wasm: &str = host_wasm_path.to_str().unwrap();
let host_native: &str = host_native_path.to_str().unwrap(); let host_native: &str = host_native_path.to_str().unwrap();
println!("cargo:rerun-if-changed={}", host_source); println!("cargo:rerun-if-changed={host_source}");
println!("cargo:rerun-if-changed={}", import_source); println!("cargo:rerun-if-changed={import_source}");
if !Path::new("build").exists() { if !Path::new("build").exists() {
fs::create_dir("build").unwrap(); fs::create_dir("build").unwrap();
@ -57,7 +57,7 @@ fn build_wasm_linking_test_host() {
"-target", "-target",
"wasm32-freestanding-musl", "wasm32-freestanding-musl",
host_source, host_source,
&format!("-femit-bin={}", host_wasm), &format!("-femit-bin={host_wasm}"),
]); ]);
let mut import_obj_path = PathBuf::from("build").join("wasm_linking_host_imports"); let mut import_obj_path = PathBuf::from("build").join("wasm_linking_host_imports");
@ -73,7 +73,7 @@ fn build_wasm_linking_test_host() {
"build-exe", "build-exe",
host_source, host_source,
import_obj, import_obj,
&format!("-femit-bin={}", host_native), &format!("-femit-bin={host_native}"),
#[cfg(windows)] #[cfg(windows)]
"--subsystem", "--subsystem",
#[cfg(windows)] #[cfg(windows)]
@ -148,7 +148,7 @@ fn run_zig(args: &[&str]) {
let mut zig_cmd = zig(); let mut zig_cmd = zig();
let full_zig_cmd = zig_cmd.args(args); let full_zig_cmd = zig_cmd.args(args);
println!("{:?}", full_zig_cmd); println!("{full_zig_cmd:?}");
let zig_cmd_output = full_zig_cmd.output().unwrap(); let zig_cmd_output = full_zig_cmd.output().unwrap();
@ -164,6 +164,6 @@ fn run_zig(args: &[&str]) {
panic!("zig call failed with status {:?}", zig_cmd_output.status); panic!("zig call failed with status {:?}", zig_cmd_output.status);
} }
assert!(zig_cmd_output.stdout.is_empty(), "{:#?}", zig_cmd_output); assert!(zig_cmd_output.stdout.is_empty(), "{zig_cmd_output:#?}");
assert!(zig_cmd_output.stderr.is_empty(), "{:#?}", zig_cmd_output); assert!(zig_cmd_output.stderr.is_empty(), "{zig_cmd_output:#?}");
} }

View File

@ -1776,14 +1776,14 @@ fn assert_concat_worked(num_elems1: i64, num_elems2: i64) {
let vec2: Vec<i64> = (0..num_elems2) let vec2: Vec<i64> = (0..num_elems2)
.map(|i| 54321 % (i + num_elems1 + num_elems2 + 1)) .map(|i| 54321 % (i + num_elems1 + num_elems2 + 1))
.collect(); .collect();
let slice_str1 = format!("{:?}", vec1); let slice_str1 = format!("{vec1:?}");
let slice_str2 = format!("{:?}", vec2); let slice_str2 = format!("{vec2:?}");
let mut expected = vec1; let mut expected = vec1;
expected.extend(vec2); expected.extend(vec2);
assert_evals_to!( assert_evals_to!(
&format!("List.concat {} {}", slice_str1, slice_str2), &format!("List.concat {slice_str1} {slice_str2}"),
RocList::from_slice(&expected), RocList::from_slice(&expected),
RocList<i64> RocList<i64>
); );

View File

@ -89,10 +89,10 @@ fn create_llvm_module<'a>(
Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport( Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport(
report, report,
))) => { ))) => {
println!("{}", report); println!("{report}");
panic!(); panic!();
} }
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
}; };
use roc_load::MonomorphizedModule; use roc_load::MonomorphizedModule;
@ -283,8 +283,7 @@ fn create_llvm_module<'a>(
let path = std::env::temp_dir().join("test.ll"); let path = std::env::temp_dir().join("test.ll");
env.module.print_to_file(&path).unwrap(); env.module.print_to_file(&path).unwrap();
panic!( panic!(
"Errors defining module:\n\n{}\n\nI have written the full module to `{:?}`", "Errors defining module:\n\n{errors}\n\nI have written the full module to `{path:?}`"
errors, path
); );
}; };
@ -374,7 +373,7 @@ fn annotate_with_debug_info<'ctx>(
ErrorKind::NotFound => panic!( ErrorKind::NotFound => panic!(
r"I could not find the `debugir` tool on the PATH, install it from https://github.com/vaivaswatha/debugir" r"I could not find the `debugir` tool on the PATH, install it from https://github.com/vaivaswatha/debugir"
), ),
_ => panic!("{:?}", error), _ => panic!("{error:?}"),
} }
} }
} }
@ -495,17 +494,14 @@ fn llvm_module_to_wasm_file(
let msg = String::from_utf8_lossy(&output.stderr); let msg = String::from_utf8_lossy(&output.stderr);
if msg.contains("wasm-ld: error: unknown file type") { if msg.contains("wasm-ld: error: unknown file type") {
panic!( panic!("{msg}\nThis can happen if multiple tests have the same input string");
"{}\nThis can happen if multiple tests have the same input string",
msg
);
} else { } else {
panic!("{}", msg); panic!("{}", msg);
} }
} }
assert!(output.status.success(), "{:#?}", output); assert!(output.status.success(), "{output:#?}");
assert!(output.stdout.is_empty(), "{:#?}", output); assert!(output.stdout.is_empty(), "{output:#?}");
test_wasm_path test_wasm_path
} }
@ -570,7 +566,7 @@ pub fn try_run_lib_function<T>(
let main: libloading::Symbol<unsafe extern "C" fn(*mut RocCallResult<T>)> = lib let main: libloading::Symbol<unsafe extern "C" fn(*mut RocCallResult<T>)> = lib
.get(main_fn_name.as_bytes()) .get(main_fn_name.as_bytes())
.ok() .ok()
.ok_or(format!("Unable to JIT compile `{}`", main_fn_name)) .ok_or(format!("Unable to JIT compile `{main_fn_name}`"))
.expect("errored"); .expect("errored");
let mut main_result = MaybeUninit::uninit(); let mut main_result = MaybeUninit::uninit();
@ -607,7 +603,7 @@ where
match result { match result {
Ok(raw) => { Ok(raw) => {
// only if there are no exceptions thrown, check for errors // only if there are no exceptions thrown, check for errors
assert!(errors.is_empty(), "Encountered errors:\n{}", errors); assert!(errors.is_empty(), "Encountered errors:\n{errors}");
#[allow(clippy::redundant_closure_call)] #[allow(clippy::redundant_closure_call)]
let given = transform(raw); let given = transform(raw);
@ -618,8 +614,8 @@ where
std::mem::forget(given); std::mem::forget(given);
} }
Err((msg, tag)) => match tag { Err((msg, tag)) => match tag {
CrashTag::Roc => panic!(r#"Roc failed with message: "{}""#, msg), CrashTag::Roc => panic!(r#"Roc failed with message: "{msg}""#),
CrashTag::User => panic!(r#"User crash with message: "{}""#, msg), CrashTag::User => panic!(r#"User crash with message: "{msg}""#),
}, },
} }
} }

View File

@ -24,7 +24,7 @@ pub(crate) fn src_hash(src: &str) -> u64 {
pub(crate) fn save_wasm_file(app_module_bytes: &[u8], build_dir_hash: u64) { pub(crate) fn save_wasm_file(app_module_bytes: &[u8], build_dir_hash: u64) {
use std::path::Path; use std::path::Path;
let debug_dir_str = format!("/tmp/roc/gen_wasm/{:016x}", build_dir_hash); let debug_dir_str = format!("/tmp/roc/gen_wasm/{build_dir_hash:016x}");
let debug_dir_path = Path::new(&debug_dir_str); let debug_dir_path = Path::new(&debug_dir_str);
let final_wasm_file = debug_dir_path.join("final.wasm"); let final_wasm_file = debug_dir_path.join("final.wasm");

View File

@ -123,10 +123,10 @@ fn compiles_to_ir(test_name: &str, src: &str, mode: &str, allow_type_errors: boo
Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport( Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport(
report, report,
))) => { ))) => {
println!("{}", report); println!("{report}");
panic!(); panic!();
} }
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
}; };
use roc_load::MonomorphizedModule; use roc_load::MonomorphizedModule;
@ -201,7 +201,7 @@ fn verify_procedures<'a>(
let result = procs_string.join("\n"); let result = procs_string.join("\n");
let path = format!("generated/{}.txt", test_name); let path = format!("generated/{test_name}.txt");
std::fs::create_dir_all("generated").unwrap(); std::fs::create_dir_all("generated").unwrap();
std::fs::write(&path, result).unwrap(); std::fs::write(&path, result).unwrap();

View File

@ -96,10 +96,10 @@ impl<'a> Output<'a> {
pub fn debug_format_inner(&self) -> String { pub fn debug_format_inner(&self) -> String {
match self { match self {
Output::Header(header) => format!("{:#?}\n", header), Output::Header(header) => format!("{header:#?}\n"),
Output::ModuleDefs(defs) => format!("{:#?}\n", defs), Output::ModuleDefs(defs) => format!("{defs:#?}\n"),
Output::Expr(expr) => format!("{:#?}\n", expr), Output::Expr(expr) => format!("{expr:#?}\n"),
Output::Full { .. } => format!("{:#?}\n", self), Output::Full { .. } => format!("{self:#?}\n"),
} }
} }
} }
@ -224,7 +224,7 @@ impl<'a> Input<'a> {
// the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same. // the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same.
// I don't have the patience to debug this right now, so let's leave it for another day... // I don't have the patience to debug this right now, so let's leave it for another day...
// TODO: fix PartialEq impl on ast types // TODO: fix PartialEq impl on ast types
if format!("{:?}", ast_normalized) != format!("{:?}", reparsed_ast_normalized) { if format!("{ast_normalized:?}") != format!("{reparsed_ast_normalized:?}") {
panic!( panic!(
"Formatting bug; formatting didn't reparse to the same AST (after removing spaces)\n\n\ "Formatting bug; formatting didn't reparse to the same AST (after removing spaces)\n\n\
* * * Source code before formatting:\n{}\n\n\ * * * Source code before formatting:\n{}\n\n\

View File

@ -43,8 +43,7 @@ mod test_fmt {
fmt_defs(buf, &loc_defs, 0); fmt_defs(buf, &loc_defs, 0);
} }
Err(error) => panic!( Err(error) => panic!(
r"Unexpected parse failure when parsing this for defs formatting:\n\n{:?}\n\nParse error was:\n\n{:?}\n\n", r"Unexpected parse failure when parsing this for defs formatting:\n\n{src:?}\n\nParse error was:\n\n{error:?}\n\n"
src, error
), ),
} }
} }
@ -67,8 +66,7 @@ mod test_fmt {
let (reparsed_ast, state) = module::parse_header(&arena, State::new(output.as_bytes())).unwrap_or_else(|err| { let (reparsed_ast, state) = module::parse_header(&arena, State::new(output.as_bytes())).unwrap_or_else(|err| {
panic!( panic!(
"After formatting, the source code no longer parsed!\n\nParse error was: {:?}\n\nThe code that failed to parse:\n\n{}\n\n", "After formatting, the source code no longer parsed!\n\nParse error was: {err:?}\n\nThe code that failed to parse:\n\n{output}\n\n"
err, output
); );
}); });
@ -80,13 +78,11 @@ mod test_fmt {
// the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same. // the PartialEq implementation is returning `false` even when the Debug-formatted impl is exactly the same.
// I don't have the patience to debug this right now, so let's leave it for another day... // I don't have the patience to debug this right now, so let's leave it for another day...
// TODO: fix PartialEq impl on ast types // TODO: fix PartialEq impl on ast types
if format!("{:?}", ast_normalized) != format!("{:?}", reparsed_ast_normalized) { if format!("{ast_normalized:?}") != format!("{reparsed_ast_normalized:?}") {
panic!( panic!(
"Formatting bug; formatting didn't reparse to the same AST (after removing spaces)\n\n\ "Formatting bug; formatting didn't reparse to the same AST (after removing spaces)\n\n\
* * * Source code before formatting:\n{}\n\n\ * * * Source code before formatting:\n{src}\n\n\
* * * Source code after formatting:\n{}\n\n", * * * Source code after formatting:\n{output}\n\n"
src,
output
); );
} }
@ -111,7 +107,7 @@ mod test_fmt {
// those more than we want to know that the expectation failed! // those more than we want to know that the expectation failed!
assert_multiline_str_eq!(expected, output); assert_multiline_str_eq!(expected, output);
} }
Err(error) => panic!("Unexpected parse failure when parsing this for module header formatting:\n\n{:?}\n\nParse error was:\n\n{:?}\n\n", src, error) Err(error) => panic!("Unexpected parse failure when parsing this for module header formatting:\n\n{src:?}\n\nParse error was:\n\n{error:?}\n\n")
}; };
} }

View File

@ -526,14 +526,13 @@ mod test_snapshots {
// Expect file to be missing // Expect file to be missing
assert!( assert!(
!result_path.exists(), !result_path.exists(),
"Expected {:?} to be missing. \ "Expected {result_path:?} to be missing. \
This is how we represent a 'default' result (i.e. a test that \ This is how we represent a 'default' result (i.e. a test that \
formats to the same thing as the input). \ formats to the same thing as the input). \
Consider running the tests with:\n\ Consider running the tests with:\n\
`env ROC_SNAPSHOT_TEST_OVERWRITE=1 cargo test ...`\n\ `env ROC_SNAPSHOT_TEST_OVERWRITE=1 cargo test ...`\n\
(which will delete the file for you),\n\ (which will delete the file for you),\n\
and commiting the delete.", and commiting the delete."
result_path
); );
} }
} }
@ -545,15 +544,12 @@ mod test_snapshots {
let mut parent = std::path::PathBuf::from("tests"); let mut parent = std::path::PathBuf::from("tests");
parent.push("snapshots"); parent.push("snapshots");
parent.push(expect.to_dir_name()); parent.push(expect.to_dir_name());
let input_path = parent.join(format!("{}.{}.roc", name, ty)); let input_path = parent.join(format!("{name}.{ty}.roc"));
let result_path = parent.join(format!("{}.{}.result-ast", name, ty)); let result_path = parent.join(format!("{name}.{ty}.result-ast"));
let formatted_path = parent.join(format!("{}.{}.formatted.roc", name, ty)); let formatted_path = parent.join(format!("{name}.{ty}.formatted.roc"));
let source = std::fs::read_to_string(&input_path).unwrap_or_else(|err| { let source = std::fs::read_to_string(&input_path).unwrap_or_else(|err| {
panic!( panic!("Could not find a snapshot test result at {input_path:?} - {err:?}")
"Could not find a snapshot test result at {:?} - {:?}",
input_path, err
)
}); });
let input = func(&source); let input = func(&source);
@ -566,14 +562,14 @@ mod test_snapshots {
} }
Ok(ast.debug_format_inner()) Ok(ast.debug_format_inner())
} }
Err(err) => Err(format!("{:?}", err)), Err(err) => Err(format!("{err:?}")),
}; };
if expect == TestExpectation::Pass { if expect == TestExpectation::Pass {
let tokens = roc_parse::highlight::highlight(&source); let tokens = roc_parse::highlight::highlight(&source);
for token in tokens { for token in tokens {
if token.value == roc_parse::highlight::Token::Error { if token.value == roc_parse::highlight::Token::Error {
panic!("Found an error highlight token in the input: {:?}", token); panic!("Found an error highlight token in the input: {token:?}");
} }
} }
} }
@ -653,7 +649,7 @@ mod test_snapshots {
#[test] #[test]
fn string_with_escaped_char_at_end() { fn string_with_escaped_char_at_end() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""abcd{}""#, esc), |esc| format!(r#""abcd{esc}""#),
|esc, arena| bumpalo::vec![in arena; Plaintext("abcd"), EscapedChar(esc)], |esc, arena| bumpalo::vec![in arena; Plaintext("abcd"), EscapedChar(esc)],
); );
} }
@ -661,7 +657,7 @@ mod test_snapshots {
#[test] #[test]
fn string_with_escaped_char_in_front() { fn string_with_escaped_char_in_front() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""{}abcd""#, esc), |esc| format!(r#""{esc}abcd""#),
|esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abcd")], |esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abcd")],
); );
} }
@ -669,7 +665,7 @@ mod test_snapshots {
#[test] #[test]
fn string_with_escaped_char_in_middle() { fn string_with_escaped_char_in_middle() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""ab{}cd""#, esc), |esc| format!(r#""ab{esc}cd""#),
|esc, arena| bumpalo::vec![in arena; Plaintext("ab"), EscapedChar(esc), Plaintext("cd")], |esc, arena| bumpalo::vec![in arena; Plaintext("ab"), EscapedChar(esc), Plaintext("cd")],
); );
} }
@ -677,7 +673,7 @@ mod test_snapshots {
#[test] #[test]
fn string_with_multiple_escaped_chars() { fn string_with_multiple_escaped_chars() {
parses_with_escaped_char( parses_with_escaped_char(
|esc| format!(r#""{}abc{}de{}fghi{}""#, esc, esc, esc, esc), |esc| format!(r#""{esc}abc{esc}de{esc}fghi{esc}""#),
|esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abc"), EscapedChar(esc), Plaintext("de"), EscapedChar(esc), Plaintext("fghi"), EscapedChar(esc)], |esc, arena| bumpalo::vec![in arena; EscapedChar(esc), Plaintext("abc"), EscapedChar(esc), Plaintext("de"), EscapedChar(esc), Plaintext("fghi"), EscapedChar(esc)],
); );
} }

View File

@ -820,7 +820,7 @@ fn write_content<'a>(
"".to_string() "".to_string()
}; };
if env.home == symbol.module_id() { if env.home == symbol.module_id() {
format!("{}{}", ident_str, disambiguation,) format!("{ident_str}{disambiguation}",)
} else { } else {
format!( format!(
"{}.{}{}", "{}.{}{}",

View File

@ -774,11 +774,11 @@ impl fmt::Debug for Subs {
let root = self.get_root_key_without_compacting(var); let root = self.get_root_key_without_compacting(var);
if var == root { if var == root {
write!(f, "{} => ", i)?; write!(f, "{i} => ")?;
subs_fmt_desc(&desc, self, f)?; subs_fmt_desc(&desc, self, f)?;
} else { } else {
write!(f, "{} => <{:?}>", i, root)?; write!(f, "{i} => <{root:?}>")?;
} }
writeln!(f)?; writeln!(f)?;
@ -811,7 +811,7 @@ fn subs_fmt_content(this: &Content, subs: &Subs, f: &mut fmt::Formatter) -> fmt:
Some(index) => subs[*index].as_str(), Some(index) => subs[*index].as_str(),
None => "_", None => "_",
}; };
write!(f, "Flex({})", name) write!(f, "Flex({name})")
} }
Content::FlexAbleVar(name, symbols) => { Content::FlexAbleVar(name, symbols) => {
let name = match name { let name = match name {
@ -827,7 +827,7 @@ fn subs_fmt_content(this: &Content, subs: &Subs, f: &mut fmt::Formatter) -> fmt:
Content::RecursionVar { Content::RecursionVar {
structure, structure,
opt_name, opt_name,
} => write!(f, "Recursion({:?}, {:?})", structure, opt_name), } => write!(f, "Recursion({structure:?}, {opt_name:?})"),
Content::Structure(flat_type) => subs_fmt_flat_type(flat_type, subs, f), Content::Structure(flat_type) => subs_fmt_flat_type(flat_type, subs, f),
Content::Alias(name, arguments, actual, kind) => { Content::Alias(name, arguments, actual, kind) => {
let slice = subs.get_subs_slice(arguments.all_variables()); let slice = subs.get_subs_slice(arguments.all_variables());
@ -855,7 +855,7 @@ fn subs_fmt_content(this: &Content, subs: &Subs, f: &mut fmt::Formatter) -> fmt:
write!(f, "LambdaSet([")?; write!(f, "LambdaSet([")?;
for (name, slice) in solved.iter_from_subs(subs) { for (name, slice) in solved.iter_from_subs(subs) {
write!(f, "{:?} ", name)?; write!(f, "{name:?} ")?;
for var in slice { for var in slice {
write!( write!(
f, f,
@ -869,7 +869,7 @@ fn subs_fmt_content(this: &Content, subs: &Subs, f: &mut fmt::Formatter) -> fmt:
write!(f, "]")?; write!(f, "]")?;
if let Some(rec_var) = recursion_var.into_variable() { if let Some(rec_var) = recursion_var.into_variable() {
write!(f, " as <{:?}>", rec_var)?; write!(f, " as <{rec_var:?}>")?;
} }
for Uls(var, member, region) in subs.get_subs_slice(*unspecialized) { for Uls(var, member, region) in subs.get_subs_slice(*unspecialized) {
write!( write!(
@ -881,10 +881,10 @@ fn subs_fmt_content(this: &Content, subs: &Subs, f: &mut fmt::Formatter) -> fmt:
region region
)?; )?;
} }
write!(f, ", ^<{:?}>)", ambient_function_var) write!(f, ", ^<{ambient_function_var:?}>)")
} }
Content::RangedNumber(range) => { Content::RangedNumber(range) => {
write!(f, "RangedNumber( {:?})", range) write!(f, "RangedNumber( {range:?})")
} }
Content::Error => write!(f, "Error"), Content::Error => write!(f, "Error"),
} }
@ -903,7 +903,7 @@ fn subs_fmt_flat_type(this: &FlatType, subs: &Subs, f: &mut fmt::Formatter) -> f
FlatType::Apply(name, arguments) => { FlatType::Apply(name, arguments) => {
let slice = subs.get_subs_slice(*arguments); let slice = subs.get_subs_slice(*arguments);
write!(f, "Apply({:?}, {:?})", name, slice) write!(f, "Apply({name:?}, {slice:?})")
} }
FlatType::Func(arguments, lambda_set, result) => { FlatType::Func(arguments, lambda_set, result) => {
let slice = subs.get_subs_slice(*arguments); let slice = subs.get_subs_slice(*arguments);
@ -948,7 +948,7 @@ fn subs_fmt_flat_type(this: &FlatType, subs: &Subs, f: &mut fmt::Formatter) -> f
)?; )?;
} }
write!(f, "}}<{:?}>", new_ext) write!(f, "}}<{new_ext:?}>")
} }
FlatType::Tuple(elems, ext) => { FlatType::Tuple(elems, ext) => {
write!(f, "( ")?; write!(f, "( ")?;
@ -962,14 +962,14 @@ fn subs_fmt_flat_type(this: &FlatType, subs: &Subs, f: &mut fmt::Formatter) -> f
)?; )?;
} }
write!(f, ")<{:?}>", new_ext) write!(f, ")<{new_ext:?}>")
} }
FlatType::TagUnion(tags, ext) => { FlatType::TagUnion(tags, ext) => {
write!(f, "[")?; write!(f, "[")?;
let (it, new_ext) = tags.sorted_iterator_and_ext(subs, *ext); let (it, new_ext) = tags.sorted_iterator_and_ext(subs, *ext);
for (name, slice) in it { for (name, slice) in it {
write!(f, "{:?} ", name)?; write!(f, "{name:?} ")?;
for var in slice { for var in slice {
write!( write!(
f, f,
@ -981,26 +981,22 @@ fn subs_fmt_flat_type(this: &FlatType, subs: &Subs, f: &mut fmt::Formatter) -> f
write!(f, ", ")?; write!(f, ", ")?;
} }
write!(f, "]<{:?}>", new_ext) write!(f, "]<{new_ext:?}>")
} }
FlatType::FunctionOrTagUnion(tagnames, symbol, ext) => { FlatType::FunctionOrTagUnion(tagnames, symbol, ext) => {
let tagnames: &[TagName] = subs.get_subs_slice(*tagnames); let tagnames: &[TagName] = subs.get_subs_slice(*tagnames);
write!( write!(f, "FunctionOrTagUnion({tagnames:?}, {symbol:?}, {ext:?})")
f,
"FunctionOrTagUnion({:?}, {:?}, {:?})",
tagnames, symbol, ext
)
} }
FlatType::RecursiveTagUnion(rec, tags, ext) => { FlatType::RecursiveTagUnion(rec, tags, ext) => {
write!(f, "[")?; write!(f, "[")?;
let (it, new_ext) = tags.sorted_iterator_and_ext(subs, *ext); let (it, new_ext) = tags.sorted_iterator_and_ext(subs, *ext);
for (name, slice) in it { for (name, slice) in it {
write!(f, "{:?} {:?}, ", name, slice)?; write!(f, "{name:?} {slice:?}, ")?;
} }
write!(f, "]<{:?}> as <{:?}>", new_ext, rec) write!(f, "]<{new_ext:?}> as <{rec:?}>")
} }
FlatType::EmptyRecord => write!(f, "EmptyRecord"), FlatType::EmptyRecord => write!(f, "EmptyRecord"),
FlatType::EmptyTuple => write!(f, "EmptyTuple"), FlatType::EmptyTuple => write!(f, "EmptyTuple"),
@ -1016,7 +1012,7 @@ impl std::fmt::Debug for DebugUtable<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("UnificationTable {\n")?; f.write_str("UnificationTable {\n")?;
for v in 0..self.0.utable.len() { for v in 0..self.0.utable.len() {
f.write_fmt(format_args!(" {} => ", v))?; f.write_fmt(format_args!(" {v} => "))?;
let var = unsafe { Variable::from_index(v as u32) }; let var = unsafe { Variable::from_index(v as u32) };
let root = self.0.utable.root_key_without_compacting(var); let root = self.0.utable.root_key_without_compacting(var);
if root == var { if root == var {
@ -2820,9 +2816,7 @@ where
debug_assert_eq!( debug_assert_eq!(
labels.len(), labels.len(),
variables.len(), variables.len(),
"tag name len != variables len: {:?} {:?}", "tag name len != variables len: {labels:?} {variables:?}",
labels,
variables,
); );
Self { Self {
@ -4025,7 +4019,7 @@ where
} else { } else {
// TODO is this the proper use of index here, or should we be // TODO is this the proper use of index here, or should we be
// doing something else like turning it into an ASCII letter? // doing something else like turning it into an ASCII letter?
Lowercase::from(format!("{}{}", given_name, index)) Lowercase::from(format!("{given_name}{index}"))
}; };
match taken_names.get(&indexed_name) { match taken_names.get(&indexed_name) {
@ -4335,7 +4329,7 @@ fn flat_type_to_err_type(
ErrorType::Error => ErrorType::Record(err_fields, TypeExt::Closed), ErrorType::Error => ErrorType::Record(err_fields, TypeExt::Closed),
other => other =>
panic!("Tried to convert a record extension to an error, but the record extension had the ErrorType of {:?}", other) panic!("Tried to convert a record extension to an error, but the record extension had the ErrorType of {other:?}")
} }
} }
@ -4367,7 +4361,7 @@ fn flat_type_to_err_type(
ErrorType::Error => ErrorType::Tuple(err_elems, TypeExt::Closed), ErrorType::Error => ErrorType::Tuple(err_elems, TypeExt::Closed),
other => other =>
panic!("Tried to convert a record extension to an error, but the record extension had the ErrorType of {:?}", other) panic!("Tried to convert a record extension to an error, but the record extension had the ErrorType of {other:?}")
} }
} }
@ -4393,7 +4387,7 @@ fn flat_type_to_err_type(
ErrorType::Error => ErrorType::TagUnion(err_tags, TypeExt::Closed, pol), ErrorType::Error => ErrorType::TagUnion(err_tags, TypeExt::Closed, pol),
other => other =>
panic!("Tried to convert a tag union extension to an error, but the tag union extension had the ErrorType of {:?}", other) panic!("Tried to convert a tag union extension to an error, but the tag union extension had the ErrorType of {other:?}")
} }
} }
@ -4423,7 +4417,7 @@ fn flat_type_to_err_type(
ErrorType::Error => ErrorType::TagUnion(err_tags, TypeExt::Closed, pol), ErrorType::Error => ErrorType::TagUnion(err_tags, TypeExt::Closed, pol),
other => other =>
panic!("Tried to convert a tag union extension to an error, but the tag union extension had the ErrorType of {:?}", other) panic!("Tried to convert a tag union extension to an error, but the tag union extension had the ErrorType of {other:?}")
} }
} }
@ -4455,7 +4449,7 @@ fn flat_type_to_err_type(
ErrorType::Error => ErrorType::RecursiveTagUnion(rec_error_type, err_tags, TypeExt::Closed, pol), ErrorType::Error => ErrorType::RecursiveTagUnion(rec_error_type, err_tags, TypeExt::Closed, pol),
other => other =>
panic!("Tried to convert a recursive tag union extension to an error, but the tag union extension had the ErrorType of {:?}", other) panic!("Tried to convert a recursive tag union extension to an error, but the tag union extension had the ErrorType of {other:?}")
} }
} }
} }

View File

@ -55,11 +55,11 @@ impl<T: fmt::Debug> fmt::Debug for RecordField<T> {
use RecordField::*; use RecordField::*;
match self { match self {
Optional(typ) => write!(f, "Optional({:?})", typ), Optional(typ) => write!(f, "Optional({typ:?})"),
Required(typ) => write!(f, "Required({:?})", typ), Required(typ) => write!(f, "Required({typ:?})"),
Demanded(typ) => write!(f, "Demanded({:?})", typ), Demanded(typ) => write!(f, "Demanded({typ:?})"),
RigidRequired(typ) => write!(f, "RigidRequired({:?})", typ), RigidRequired(typ) => write!(f, "RigidRequired({typ:?})"),
RigidOptional(typ) => write!(f, "RigidOptional({:?})", typ), RigidOptional(typ) => write!(f, "RigidOptional({typ:?})"),
} }
} }
} }
@ -1949,10 +1949,10 @@ fn write_tags<'a>(
let mut it = tags.peekable(); let mut it = tags.peekable();
while let Some((label, arguments)) = it.next() { while let Some((label, arguments)) = it.next() {
write!(f, "{:?}", label)?; write!(f, "{label:?}")?;
for argument in arguments { for argument in arguments {
write!(f, " {:?}", argument)?; write!(f, " {argument:?}")?;
} }
if it.peek().is_some() { if it.peek().is_some() {
@ -1976,23 +1976,23 @@ impl fmt::Debug for Type {
write!(f, ", ")?; write!(f, ", ")?;
} }
write!(f, "{:?}", arg)?; write!(f, "{arg:?}")?;
} }
write!(f, " |{:?}|", closure)?; write!(f, " |{closure:?}|")?;
write!(f, " -> ")?; write!(f, " -> ")?;
ret.fmt(f)?; ret.fmt(f)?;
write!(f, ")") write!(f, ")")
} }
Type::Variable(var) => write!(f, "<{:?}>", var), Type::Variable(var) => write!(f, "<{var:?}>"),
Type::Apply(symbol, args, _) => { Type::Apply(symbol, args, _) => {
write!(f, "({:?}", symbol)?; write!(f, "({symbol:?}")?;
for arg in args { for arg in args {
write!(f, " {:?}", arg)?; write!(f, " {arg:?}")?;
} }
write!(f, ")") write!(f, ")")
@ -2004,10 +2004,10 @@ impl fmt::Debug for Type {
lambda_set_variables, lambda_set_variables,
infer_ext_in_output_types, infer_ext_in_output_types,
}) => { }) => {
write!(f, "(DelayedAlias {:?}", symbol)?; write!(f, "(DelayedAlias {symbol:?}")?;
for arg in type_arguments { for arg in type_arguments {
write!(f, " {:?}", arg)?; write!(f, " {arg:?}")?;
} }
for (lambda_set, greek_letter) in for (lambda_set, greek_letter) in
@ -2017,7 +2017,7 @@ impl fmt::Debug for Type {
} }
for (i, infer_ext) in infer_ext_in_output_types.iter().enumerate() { for (i, infer_ext) in infer_ext_in_output_types.iter().enumerate() {
write!(f, " `{}@{:?}", i, infer_ext)?; write!(f, " `{i}@{infer_ext:?}")?;
} }
write!(f, ")")?; write!(f, ")")?;
@ -2032,12 +2032,12 @@ impl fmt::Debug for Type {
actual: _actual, actual: _actual,
.. ..
} => { } => {
write!(f, "(Alias {:?}", symbol)?; write!(f, "(Alias {symbol:?}")?;
for arg in type_arguments { for arg in type_arguments {
write!(f, " {:?}", &arg.typ)?; write!(f, " {:?}", &arg.typ)?;
if let Some(abs) = &arg.opt_abilities { if let Some(abs) = &arg.opt_abilities {
write!(f, ":{:?}", abs)?; write!(f, ":{abs:?}")?;
} }
} }
@ -2048,7 +2048,7 @@ impl fmt::Debug for Type {
} }
// Sometimes it's useful to see the expansion of the alias // Sometimes it's useful to see the expansion of the alias
write!(f, "[ but actually {:?} ]", _actual)?; write!(f, "[ but actually {_actual:?} ]")?;
write!(f, ")")?; write!(f, ")")?;
@ -2059,10 +2059,10 @@ impl fmt::Debug for Type {
type_arguments: arguments, type_arguments: arguments,
.. ..
} => { } => {
write!(f, "HostExposedAlias {:?}", name)?; write!(f, "HostExposedAlias {name:?}")?;
for arg in arguments { for arg in arguments {
write!(f, " {:?}", arg)?; write!(f, " {arg:?}")?;
} }
// Sometimes it's useful to see the expansion of the alias // Sometimes it's useful to see the expansion of the alias
@ -2082,13 +2082,11 @@ impl fmt::Debug for Type {
for (label, field_type) in fields { for (label, field_type) in fields {
match field_type { match field_type {
RecordField::Optional(_) | RecordField::RigidOptional(_) => { RecordField::Optional(_) | RecordField::RigidOptional(_) => {
write!(f, "{:?} ? {:?}", label, field_type)? write!(f, "{label:?} ? {field_type:?}")?
} }
RecordField::Required(_) RecordField::Required(_)
| RecordField::Demanded(_) | RecordField::Demanded(_)
| RecordField::RigidRequired(_) => { | RecordField::RigidRequired(_) => write!(f, "{label:?} : {field_type:?}")?,
write!(f, "{:?} : {:?}", label, field_type)?
}
} }
if any_written_yet { if any_written_yet {
@ -2129,7 +2127,7 @@ impl fmt::Debug for Type {
let mut any_written_yet = false; let mut any_written_yet = false;
for (_, field_type) in elems.iter() { for (_, field_type) in elems.iter() {
write!(f, "{:?}", field_type)?; write!(f, "{field_type:?}")?;
if any_written_yet { if any_written_yet {
write!(f, ", ")?; write!(f, ", ")?;
@ -2179,7 +2177,7 @@ impl fmt::Debug for Type {
} }
Type::FunctionOrTagUnion(tag_name, _, ext) => { Type::FunctionOrTagUnion(tag_name, _, ext) => {
write!(f, "[")?; write!(f, "[")?;
write!(f, "{:?}", tag_name)?; write!(f, "{tag_name:?}")?;
write!(f, "]")?; write!(f, "]")?;
match ext { match ext {
@ -2204,9 +2202,9 @@ impl fmt::Debug for Type {
} => { } => {
write!(f, "ClosureTag(")?; write!(f, "ClosureTag(")?;
write!(f, "{:?}, ", name)?; write!(f, "{name:?}, ")?;
for capture in captures { for capture in captures {
write!(f, "{:?}, ", capture)?; write!(f, "{capture:?}, ")?;
} }
write!(f, ")") write!(f, ")")
@ -2229,13 +2227,13 @@ impl fmt::Debug for Type {
} }
}?; }?;
write!(f, " as <{:?}>", rec) write!(f, " as <{rec:?}>")
} }
Type::RangedNumber(range_vars) => { Type::RangedNumber(range_vars) => {
write!(f, "Ranged({:?})", range_vars) write!(f, "Ranged({range_vars:?})")
} }
Type::UnspecializedLambdaSet { unspecialized } => { Type::UnspecializedLambdaSet { unspecialized } => {
write!(f, "{:?}", unspecialized) write!(f, "{unspecialized:?}")
} }
} }
} }
@ -4005,7 +4003,7 @@ fn write_debug_error_type_help(error_type: ErrorType, buf: &mut String, parens:
buf.push('('); buf.push('(');
} }
buf.push_str(name.as_str()); buf.push_str(name.as_str());
write!(buf, "has {:?}", symbol).unwrap(); write!(buf, "has {symbol:?}").unwrap();
if write_parens { if write_parens {
buf.push(')'); buf.push(')');
} }
@ -4016,7 +4014,7 @@ fn write_debug_error_type_help(error_type: ErrorType, buf: &mut String, parens:
if write_parens { if write_parens {
buf.push('('); buf.push('(');
} }
write!(buf, "{:?}", symbol).unwrap(); write!(buf, "{symbol:?}").unwrap();
for arg in arguments { for arg in arguments {
buf.push(' '); buf.push(' ');
@ -4061,7 +4059,7 @@ fn write_debug_error_type_help(error_type: ErrorType, buf: &mut String, parens:
if write_parens { if write_parens {
buf.push('('); buf.push('(');
} }
write!(buf, "{:?}", symbol).unwrap(); write!(buf, "{symbol:?}").unwrap();
for arg in arguments { for arg in arguments {
buf.push(' '); buf.push(' ');
@ -4146,7 +4144,7 @@ fn write_debug_error_type_help(error_type: ErrorType, buf: &mut String, parens:
let mut it = tags.into_iter().peekable(); let mut it = tags.into_iter().peekable();
while let Some((tag, args)) = it.next() { while let Some((tag, args)) = it.next() {
write!(buf, "{:?}", tag).unwrap(); write!(buf, "{tag:?}").unwrap();
for arg in args { for arg in args {
buf.push(' '); buf.push(' ');
write_debug_error_type_help(arg, buf, Parens::InTypeParam); write_debug_error_type_help(arg, buf, Parens::InTypeParam);
@ -4165,7 +4163,7 @@ fn write_debug_error_type_help(error_type: ErrorType, buf: &mut String, parens:
let mut it = tags.into_iter().peekable(); let mut it = tags.into_iter().peekable();
while let Some((tag, args)) = it.next() { while let Some((tag, args)) = it.next() {
write!(buf, "{:?}", tag).unwrap(); write!(buf, "{tag:?}").unwrap();
for arg in args { for arg in args {
buf.push(' '); buf.push(' ');
write_debug_error_type_help(arg, buf, Parens::Unnecessary); write_debug_error_type_help(arg, buf, Parens::Unnecessary);

View File

@ -60,10 +60,10 @@ pub fn write_compiled_ir<'a>(
Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport( Err(LoadMonomorphizedError::LoadingProblem(roc_load::LoadingProblem::FormattedReport(
report, report,
))) => { ))) => {
println!("{}", report); println!("{report}");
panic!(); panic!();
} }
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
}; };
use roc_load::MonomorphizedModule; use roc_load::MonomorphizedModule;
@ -146,9 +146,9 @@ fn write_procedures<'a>(
let mut procs = procs_strings.iter().peekable(); let mut procs = procs_strings.iter().peekable();
while let Some(proc) = procs.next() { while let Some(proc) = procs.next() {
if procs.peek().is_some() { if procs.peek().is_some() {
writeln!(writer, "{}", proc)?; writeln!(writer, "{proc}")?;
} else { } else {
write!(writer, "{}", proc)?; write!(writer, "{proc}")?;
} }
} }

View File

@ -337,7 +337,7 @@ fn assemble_query_output(
for (module, source) in other_modules.iter() { for (module, source) in other_modules.iter() {
writeln!(writer, "## module {module}")?; writeln!(writer, "## module {module}")?;
writeln!(writer, "{}\n", source)?; writeln!(writer, "{source}\n")?;
} }
if !other_modules.is_empty() { if !other_modules.is_empty() {

View File

@ -1853,8 +1853,7 @@ fn unify_unspecialized_lambdas<M: MetaCollector>(
debug_assert!( debug_assert!(
is_sorted_unspecialized_lamba_set_list(env.subs, &merged_uls), is_sorted_unspecialized_lamba_set_list(env.subs, &merged_uls),
"merging of unspecialized lambda sets does not preserve sort! {:?}", "merging of unspecialized lambda sets does not preserve sort! {merged_uls:?}"
merged_uls
); );
Ok(( Ok((

View File

@ -151,10 +151,7 @@ pub fn generate_docs_html(root_file: PathBuf) {
); );
fs::write(build_dir.join("index.html"), rendered_package).unwrap_or_else(|error| { fs::write(build_dir.join("index.html"), rendered_package).unwrap_or_else(|error| {
panic!( panic!("Attempted to write index.html but failed with this error: {error}")
"Attempted to write index.html but failed with this error: {}",
error
)
}); });
} }
@ -470,10 +467,10 @@ pub fn load_module_for_docs(filename: PathBuf) -> LoadedModule {
) { ) {
Ok(loaded) => loaded, Ok(loaded) => loaded,
Err(LoadingProblem::FormattedReport(report)) => { Err(LoadingProblem::FormattedReport(report)) => {
eprintln!("{}", report); eprintln!("{report}");
std::process::exit(1); std::process::exit(1);
} }
Err(e) => panic!("{:?}", e), Err(e) => panic!("{e:?}"),
} }
} }
@ -796,8 +793,7 @@ fn doc_url<'a>(
Err(_) => { Err(_) => {
// TODO return Err here // TODO return Err here
panic!( panic!(
"Tried to generate an automatic link in docs for symbol `{}`, but that symbol was not in scope in this module.", "Tried to generate an automatic link in docs for symbol `{ident}`, but that symbol was not in scope in this module."
ident
); );
} }
} }
@ -819,8 +815,7 @@ fn doc_url<'a>(
else if !all_exposed_symbols.contains(&symbol) { else if !all_exposed_symbols.contains(&symbol) {
// TODO return Err here // TODO return Err here
panic!( panic!(
"Tried to generate an automatic link in docs for `{}.{}`, but `{}` does not expose `{}`.", "Tried to generate an automatic link in docs for `{module_name}.{ident}`, but `{module_name}` does not expose `{ident}`.");
module_name, ident, module_name, ident);
} }
// This is a valid symbol for this dependency, // This is a valid symbol for this dependency,
@ -831,7 +826,7 @@ fn doc_url<'a>(
} }
None => { None => {
// TODO return Err here // TODO return Err here
panic!("Tried to generate a doc link for `{}.{}` but the `{}` module was not imported!", module_name, ident, module_name); panic!("Tried to generate a doc link for `{module_name}.{ident}` but the `{module_name}` module was not imported!");
} }
} }
} }
@ -847,7 +842,7 @@ fn doc_url<'a>(
DocUrl { DocUrl {
url, url,
title: format!("Docs for {}.{}", module_name, ident), title: format!("Docs for {module_name}.{ident}"),
} }
} }
@ -935,8 +930,7 @@ fn markdown_to_html(
for event in parser { for event in parser {
match event { match event {
Event::Code(code_str) => { Event::Code(code_str) => {
let inline_code = let inline_code = pulldown_cmark::CowStr::from(format!("<code>{code_str}</code>"));
pulldown_cmark::CowStr::from(format!("<code>{}</code>", code_str));
docs_parser.push(pulldown_cmark::Event::Html(inline_code)); docs_parser.push(pulldown_cmark::Event::Html(inline_code));
} }
Event::End(Link(LinkType::ShortcutUnknown, ref _url, ref _title)) => { Event::End(Link(LinkType::ShortcutUnknown, ref _url, ref _title)) => {

View File

@ -66,13 +66,13 @@ impl fmt::Display for CodeLines {
for row in &self.lines { for row in &self.lines {
let row_str = row let row_str = row
.chars() .chars()
.map(|code_char| format!("{}", code_char)) .map(|code_char| format!("{code_char}"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(" "); .join(" ");
let escaped_row_str = row_str.replace('\n', "\\n"); let escaped_row_str = row_str.replace('\n', "\\n");
write!(f, "\n{}", escaped_row_str)?; write!(f, "\n{escaped_row_str}")?;
} }
writeln!(f, " (code_lines, {:?} lines)", self.lines.len())?; writeln!(f, " (code_lines, {:?} lines)", self.lines.len())?;

View File

@ -278,7 +278,7 @@ pub enum EdError {
pub type EdResult<T, E = EdError> = std::result::Result<T, E>; pub type EdResult<T, E = EdError> = std::result::Result<T, E>;
pub fn print_err(err: &EdError) { pub fn print_err(err: &EdError) {
eprintln!("{}", format!("{}", err).truecolor(255, 0, 0)); eprintln!("{}", format!("{err}").truecolor(255, 0, 0));
if let Some(backtrace) = ErrorCompat::backtrace(err) { if let Some(backtrace) = ErrorCompat::backtrace(err) {
eprintln!("{}", color_backtrace(backtrace)); eprintln!("{}", color_backtrace(backtrace));
@ -286,7 +286,7 @@ pub fn print_err(err: &EdError) {
} }
fn color_backtrace(backtrace: &snafu::Backtrace) -> String { fn color_backtrace(backtrace: &snafu::Backtrace) -> String {
let backtrace_str = format!("{}", backtrace); let backtrace_str = format!("{backtrace}");
let backtrace_split = backtrace_str.split('\n'); let backtrace_split = backtrace_str.split('\n');
let irrelevant_src = vec![".cargo", "registry", ".rustup", "rustc"]; let irrelevant_src = vec![".cargo", "registry", ".rustup", "rustc"];
@ -301,10 +301,10 @@ fn color_backtrace(backtrace: &snafu::Backtrace) -> String {
} }
format!("{}\n", line.truecolor(255, 100, 100)) format!("{}\n", line.truecolor(255, 100, 100))
} else { } else {
format!("{}\n", line) format!("{line}\n")
} }
} else { } else {
format!("{}\n", line) format!("{line}\n")
}; };
if let Some(prev_line) = prev_line_opt { if let Some(prev_line) = prev_line_opt {
@ -328,7 +328,7 @@ fn contains_one_of(main_str: &str, contain_slice: &[&str]) -> bool {
impl From<EdError> for String { impl From<EdError> for String {
fn from(ed_error: EdError) -> Self { fn from(ed_error: EdError) -> Self {
format!("{}", ed_error) format!("{ed_error}")
} }
} }

View File

@ -429,11 +429,11 @@ impl fmt::Display for GridNodeMap {
for row in &self.lines { for row in &self.lines {
let row_str = row let row_str = row
.iter() .iter()
.map(|mark_node_id| format!(" {} ", mark_node_id)) .map(|mark_node_id| format!(" {mark_node_id} "))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "); .join(", ");
writeln!(f, "{}", row_str)?; writeln!(f, "{row_str}")?;
} }
writeln!(f, "(grid_node_map, {:?} lines)", self.lines.len())?; writeln!(f, "(grid_node_map, {:?} lines)", self.lines.len())?;

View File

@ -92,7 +92,7 @@ fn run_event_loop(project_path_opt: Option<&Path>) -> Result<(), Box<dyn Error>>
) )
}) })
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
panic!("Failed to request device: `{}`", err); panic!("Failed to request device: `{err}`");
}) })
.await .await
}); });
@ -125,7 +125,7 @@ fn run_event_loop(project_path_opt: Option<&Path>) -> Result<(), Box<dyn Error>>
let code_arena = Bump::new(); let code_arena = Bump::new();
let (file_path_buf, code_str) = read_main_roc_file(project_path_opt); let (file_path_buf, code_str) = read_main_roc_file(project_path_opt);
println!("Loading file {:?}...", file_path_buf); println!("Loading file {file_path_buf:?}...");
let file_path = Path::new(&file_path_buf); let file_path = Path::new(&file_path_buf);
let loaded_module = load_module( let loaded_module = load_module(
@ -237,7 +237,7 @@ fn run_event_loop(project_path_opt: Option<&Path>) -> Result<(), Box<dyn Error>>
if let Err(e) = input_outcome_res { if let Err(e) = input_outcome_res {
print_err(&e) print_err(&e)
} else if let Ok(InputOutcome::Ignored) = input_outcome_res { } else if let Ok(InputOutcome::Ignored) = input_outcome_res {
println!("\nInput '{}' ignored!", ch); println!("\nInput '{ch}' ignored!");
} else { } else {
window.request_redraw() window.request_redraw()
} }
@ -507,10 +507,7 @@ fn read_main_roc_file(project_path_opt: Option<&Path>) -> (PathBuf, String) {
let dir_items = ls(project_path, &ls_config) let dir_items = ls(project_path, &ls_config)
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
panic!( panic!("Failed to list items in project directory; error: {err:?}")
"Failed to list items in project directory; error: {:?}",
err
)
}) })
.items; .items;
@ -574,15 +571,13 @@ fn init_new_roc_project(project_dir_path: &Path) -> (PathBuf, String) {
fn create_roc_file_if_not_exists(project_dir_path: &Path, roc_file_path: &Path) -> String { fn create_roc_file_if_not_exists(project_dir_path: &Path, roc_file_path: &Path) -> String {
if !roc_file_path.exists() { if !roc_file_path.exists() {
let mut roc_file = File::create(roc_file_path).unwrap_or_else(|err| { let mut roc_file = File::create(roc_file_path).unwrap_or_else(|err| {
panic!("No roc file path was passed to the editor, so I wanted to create a new roc project with the file {:?}, but it failed: {}", roc_file_path, err) panic!("No roc file path was passed to the editor, so I wanted to create a new roc project with the file {roc_file_path:?}, but it failed: {err}")
}); });
write!(roc_file, "{}", HELLO_WORLD).unwrap_or_else(|err| { write!(roc_file, "{HELLO_WORLD}").unwrap_or_else(|err| {
panic!( panic!(
r#"No roc file path was passed to the editor, so I created a new roc project with the file {:?} r#"No roc file path was passed to the editor, so I created a new roc project with the file {roc_file_path:?}
I wanted to write roc hello world to that file, but it failed: {:?}"#, I wanted to write roc hello world to that file, but it failed: {err:?}"#
roc_file_path,
err
) )
}); });
@ -590,8 +585,7 @@ fn create_roc_file_if_not_exists(project_dir_path: &Path, roc_file_path: &Path)
} else { } else {
std::fs::read_to_string(roc_file_path).unwrap_or_else(|err| { std::fs::read_to_string(roc_file_path).unwrap_or_else(|err| {
panic!( panic!(
"I detected an existing {:?} inside {:?}, but I failed to read from it: {}", "I detected an existing {roc_file_path:?} inside {project_dir_path:?}, but I failed to read from it: {err}"
roc_file_path, project_dir_path, err
) )
}) })
} }
@ -613,10 +607,7 @@ fn copy_roc_platform_if_not_exists(
} else if !project_platform_path.exists() { } else if !project_platform_path.exists() {
copy(orig_platform_path, project_dir_path, &CopyOptions::new()).unwrap_or_else(|err|{ copy(orig_platform_path, project_dir_path, &CopyOptions::new()).unwrap_or_else(|err|{
panic!(r#"No roc file path was passed to the editor, so I wanted to create a new roc project and roc projects require a platform, panic!(r#"No roc file path was passed to the editor, so I wanted to create a new roc project and roc projects require a platform,
I tried to copy the platform at {:?} to {:?} but it failed: {}"#, I tried to copy the platform at {orig_platform_path:?} to {project_platform_path:?} but it failed: {err}"#
orig_platform_path,
project_platform_path,
err
) )
}); });
} }

View File

@ -206,7 +206,7 @@ impl<'a> EdModule<'a> {
match parse_res { match parse_res {
Ok(ast) => Ok(EdModule { env, ast }), Ok(ast) => Ok(EdModule { env, ast }),
Err(err) => SrcParseSnafu { Err(err) => SrcParseSnafu {
syntax_err: format!("{:?}", err), syntax_err: format!("{err:?}"),
} }
.fail(), .fail(),
} }
@ -315,20 +315,17 @@ pub mod test_ed_model {
let platform_module_path = platform_dir.join("main.roc"); let platform_module_path = platform_dir.join("main.roc");
let mut platform_module_file = let mut platform_module_file =
File::create(platform_module_path).expect("Failed to create main.roc"); File::create(platform_module_path).expect("Failed to create main.roc");
writeln!(platform_module_file, "{}", PLATFORM_STR).expect("Failed to write to main.roc"); writeln!(platform_module_file, "{PLATFORM_STR}").expect("Failed to write to main.roc");
let temp_file_path_buf = let temp_file_path_buf =
PathBuf::from([Uuid::new_v4().to_string(), ".roc".to_string()].join("")); PathBuf::from([Uuid::new_v4().to_string(), ".roc".to_string()].join(""));
let temp_file_full_path = temp_dir.path().join(temp_file_path_buf); let temp_file_full_path = temp_dir.path().join(temp_file_path_buf);
let mut file = File::create(temp_file_full_path.clone()).unwrap_or_else(|_| { let mut file = File::create(temp_file_full_path.clone()).unwrap_or_else(|_| {
panic!( panic!("Failed to create temporary file for path {temp_file_full_path:?}")
"Failed to create temporary file for path {:?}",
temp_file_full_path
)
}); });
writeln!(file, "{}", clean_code_str) writeln!(file, "{clean_code_str}")
.unwrap_or_else(|_| panic!("Failed to write {:?} to file: {:?}", clean_code_str, file)); .unwrap_or_else(|_| panic!("Failed to write {clean_code_str:?} to file: {file:?}"));
let loaded_module = load_module( let loaded_module = load_module(
&temp_file_full_path, &temp_file_full_path,

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