From 4591986bc2cabb20da810cf7442fbf9dbc43758b Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 10:46:09 -0700 Subject: [PATCH 1/8] Fix clippy warnings in stacks signer Signed-off-by: Jacinta Ferrant --- stacks-signer/src/cli.rs | 16 ++++++++-------- stacks-signer/src/client/mod.rs | 2 +- stacks-signer/src/client/stacks_client.rs | 4 ++-- stacks-signer/src/config.rs | 7 +++---- stacks-signer/src/main.rs | 6 +++--- stacks-signer/src/signerdb.rs | 2 +- 6 files changed, 18 insertions(+), 19 deletions(-) diff --git a/stacks-signer/src/cli.rs b/stacks-signer/src/cli.rs index 5d5b8806e7..a0eed95de5 100644 --- a/stacks-signer/src/cli.rs +++ b/stacks-signer/src/cli.rs @@ -222,7 +222,7 @@ impl TryFrom<&str> for Vote { match input.to_lowercase().as_str() { "yes" => Ok(Vote::Yes), "no" => Ok(Vote::No), - _ => Err(format!("Invalid vote: {}. Must be `yes` or `no`.", input)), + _ => Err(format!("Invalid vote: {input}. Must be `yes` or `no`.")), } } } @@ -230,7 +230,7 @@ impl TryFrom<&str> for Vote { impl TryFrom for Vote { type Error = String; fn try_from(input: u8) -> Result { - Vote::from_u8(input).ok_or_else(|| format!("Invalid vote: {}. Must be 0 or 1.", input)) + Vote::from_u8(input).ok_or_else(|| format!("Invalid vote: {input}. Must be 0 or 1.")) } } @@ -287,7 +287,7 @@ impl ValueEnum for StackingSignatureMethod { method => match Pox4SignatureTopic::lookup_by_name(method) { Some(topic) => topic, None => { - return Err(format!("Invalid topic: {}", input)); + return Err(format!("Invalid topic: {input}")); } }, }; @@ -328,7 +328,7 @@ pub struct GenerateStackingSignatureArgs { /// Parse the contract ID fn parse_contract(contract: &str) -> Result { - QualifiedContractIdentifier::parse(contract).map_err(|e| format!("Invalid contract: {}", e)) + QualifiedContractIdentifier::parse(contract).map_err(|e| format!("Invalid contract: {e}")) } /// Parse a BTC address argument and return a `PoxAddress`. @@ -355,12 +355,12 @@ pub fn parse_pox_addr(pox_address_literal: &str) -> Result { /// Parse the hexadecimal Stacks private key fn parse_private_key(private_key: &str) -> Result { - StacksPrivateKey::from_hex(private_key).map_err(|e| format!("Invalid private key: {}", e)) + StacksPrivateKey::from_hex(private_key).map_err(|e| format!("Invalid private key: {e}")) } /// Parse the hexadecimal Stacks public key fn parse_public_key(public_key: &str) -> Result { - StacksPublicKey::from_hex(public_key).map_err(|e| format!("Invalid public key: {}", e)) + StacksPublicKey::from_hex(public_key).map_err(|e| format!("Invalid public key: {e}")) } /// Parse the vote @@ -370,7 +370,7 @@ fn parse_vote(vote: &str) -> Result { /// Parse the hexadecimal encoded message signature fn parse_message_signature(signature: &str) -> Result { - MessageSignature::from_hex(signature).map_err(|e| format!("Invalid message signature: {}", e)) + MessageSignature::from_hex(signature).map_err(|e| format!("Invalid message signature: {e}")) } /// Parse the input data @@ -384,7 +384,7 @@ fn parse_data(data: &str) -> Result, String> { data.to_string() }; let data = - b58::from(&encoded_data).map_err(|e| format!("Failed to decode provided data: {}", e))?; + b58::from(&encoded_data).map_err(|e| format!("Failed to decode provided data: {e}"))?; Ok(data) } diff --git a/stacks-signer/src/client/mod.rs b/stacks-signer/src/client/mod.rs index 21b44784b8..974297cb9e 100644 --- a/stacks-signer/src/client/mod.rs +++ b/stacks-signer/src/client/mod.rs @@ -346,7 +346,7 @@ pub(crate) mod tests { stackerdbs: Some( stackerdb_contract_ids .into_iter() - .map(|cid| format!("{}", cid)) + .map(|cid| cid.to_string()) .collect(), ), }; diff --git a/stacks-signer/src/client/stacks_client.rs b/stacks-signer/src/client/stacks_client.rs index dee668792b..10d990a1f2 100644 --- a/stacks-signer/src/client/stacks_client.rs +++ b/stacks-signer/src/client/stacks_client.rs @@ -115,7 +115,7 @@ impl StacksClient { let stacks_address = StacksAddress::p2pkh(mainnet, &pubkey); Self { stacks_address, - http_origin: format!("http://{}", node_host), + http_origin: format!("http://{node_host}"), tx_version, chain_id, stacks_node_client: reqwest::blocking::Client::new(), @@ -751,7 +751,7 @@ impl StacksClient { } fn tenure_tip_path(&self, consensus_hash: &ConsensusHash) -> String { - format!("{}/v3/tenures/tip/{}", self.http_origin, consensus_hash) + format!("{}/v3/tenures/tip/{consensus_hash}", self.http_origin) } } diff --git a/stacks-signer/src/config.rs b/stacks-signer/src/config.rs index ac438e5819..f1eb4cbb95 100644 --- a/stacks-signer/src/config.rs +++ b/stacks-signer/src/config.rs @@ -564,7 +564,7 @@ pub fn build_signer_config_tomls( let mut signer_config_tomls = vec![]; for stacks_private_key in stacks_private_keys { - let endpoint = format!("localhost:{}", port_start); + let endpoint = format!("localhost:{port_start}"); port_start += 1; let stacks_public_key = StacksPublicKey::from_private(stacks_private_key).to_hex(); @@ -615,7 +615,7 @@ tx_fee_ustx = {tx_fee_ustx} } if let Some(metrics_port) = metrics_port_start { - let metrics_endpoint = format!("localhost:{}", metrics_port); + let metrics_endpoint = format!("localhost:{metrics_port}"); signer_config_toml = format!( r#" {signer_config_toml} @@ -709,8 +709,7 @@ Dry run: false assert!( config_str == expected_str_v4 || config_str == expected_str_v6, - "Config string does not match expected output. Actual:\n{}", - config_str + "Config string does not match expected output. Actual:\n{config_str}", ); } diff --git a/stacks-signer/src/main.rs b/stacks-signer/src/main.rs index 2e1bf771e6..75e1703854 100644 --- a/stacks-signer/src/main.rs +++ b/stacks-signer/src/main.rs @@ -84,7 +84,7 @@ fn handle_list_chunks(args: StackerDBArgs) { let chunk_list = session.list_chunks().unwrap(); let chunk_list_json = serde_json::to_string(&chunk_list).unwrap(); let hexed_json = to_hex(chunk_list_json.as_bytes()); - println!("{}", hexed_json); + println!("{hexed_json}"); } fn handle_put_chunk(args: PutChunkArgs) { @@ -148,7 +148,7 @@ fn handle_generate_stacking_signature( }; if do_print { - println!("{}", output_str); + println!("{output_str}"); } signature @@ -156,7 +156,7 @@ fn handle_generate_stacking_signature( fn handle_check_config(args: RunSignerArgs) { let config = GlobalConfig::try_from(&args.config).unwrap(); - println!("Signer version: {}\nConfig: \n{}", *VERSION_STRING, config); + println!("Signer version: {}\nConfig: \n{config}", *VERSION_STRING); } fn handle_generate_vote(args: GenerateVoteArgs, do_print: bool) -> MessageSignature { diff --git a/stacks-signer/src/signerdb.rs b/stacks-signer/src/signerdb.rs index a27397da75..e069d8c664 100644 --- a/stacks-signer/src/signerdb.rs +++ b/stacks-signer/src/signerdb.rs @@ -148,7 +148,7 @@ impl Display for BlockState { BlockState::GloballyAccepted => "GloballyAccepted", BlockState::GloballyRejected => "GloballyRejected", }; - write!(f, "{}", state) + write!(f, "{state}") } } From afa8a631adc57aceb8fd5842335ea55972c03ace Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 10:48:36 -0700 Subject: [PATCH 2/8] Fix clippy warnings in libstackerdb Signed-off-by: Jacinta Ferrant --- libstackerdb/src/libstackerdb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libstackerdb/src/libstackerdb.rs b/libstackerdb/src/libstackerdb.rs index 539025d197..44d51b6d7f 100644 --- a/libstackerdb/src/libstackerdb.rs +++ b/libstackerdb/src/libstackerdb.rs @@ -137,7 +137,7 @@ pub struct StackerDBChunkAckData { impl fmt::Display for StackerDBChunkAckData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } From 4d6e86c60d51a73210fbdccf9e0e7a45146c157f Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 10:50:04 -0700 Subject: [PATCH 3/8] Fix clippy warnings in pox-locking Signed-off-by: Jacinta Ferrant --- pox-locking/src/events.rs | 5 ++--- pox-locking/src/events_24.rs | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/pox-locking/src/events.rs b/pox-locking/src/events.rs index 010a9dcf16..3a71083673 100644 --- a/pox-locking/src/events.rs +++ b/pox-locking/src/events.rs @@ -84,7 +84,7 @@ fn create_event_info_aggregation_code(function_name: &str) -> String { ) {{ ;; Function name - name: "{func_name}", + name: "{function_name}", ;; who called this ;; NOTE: these fields are required by downstream clients. ;; Even though tx-sender is *not* a stacker, the field is @@ -97,8 +97,7 @@ fn create_event_info_aggregation_code(function_name: &str) -> String { }} ) - "#, - func_name = function_name + "# ) } diff --git a/pox-locking/src/events_24.rs b/pox-locking/src/events_24.rs index b827988e94..40c10de905 100644 --- a/pox-locking/src/events_24.rs +++ b/pox-locking/src/events_24.rs @@ -78,7 +78,7 @@ fn create_event_info_aggregation_code(function_name: &str) -> String { ) {{ ;; Function name - name: "{func_name}", + name: "{function_name}", ;; who called this ;; NOTE: these fields are required by downstream clients. ;; Even though tx-sender is *not* a stacker, the field is @@ -91,8 +91,7 @@ fn create_event_info_aggregation_code(function_name: &str) -> String { }} ) - "#, - func_name = function_name + "# ) } From ad87cf690e8664a0c986558af1d87315d9fcb1f0 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 10:54:24 -0700 Subject: [PATCH 4/8] Fix clippy warnings in libsigner Signed-off-by: Jacinta Ferrant --- libsigner/src/events.rs | 2 +- libsigner/src/http.rs | 15 +++++---------- libsigner/src/libsigner.rs | 2 +- libsigner/src/runloop.rs | 2 +- libsigner/src/tests/mod.rs | 7 ++----- libsigner/src/v0/messages.rs | 10 ++++------ 6 files changed, 14 insertions(+), 24 deletions(-) diff --git a/libsigner/src/events.rs b/libsigner/src/events.rs index c8b2464902..ea3ab746f0 100644 --- a/libsigner/src/events.rs +++ b/libsigner/src/events.rs @@ -620,7 +620,7 @@ impl NewBlockTransaction { Ok(None) } else { let tx_bytes = hex_bytes(&self.raw_tx).map_err(|e| { - CodecError::DeserializeError(format!("Failed to deserialize raw tx: {}", e)) + CodecError::DeserializeError(format!("Failed to deserialize raw tx: {e}")) })?; let tx = StacksTransaction::consensus_deserialize(&mut &tx_bytes[..])?; Ok(Some(tx)) diff --git a/libsigner/src/http.rs b/libsigner/src/http.rs index 680a8858d0..ba135b69f6 100644 --- a/libsigner/src/http.rs +++ b/libsigner/src/http.rs @@ -107,8 +107,7 @@ pub fn decode_http_request(payload: &[u8]) -> Result Result<(HashMap, if let Some(version) = resp.version { if version != 0 && version != 1 { return Err(RPCError::MalformedResponse(format!( - "Unrecognized HTTP code {}", - version + "Unrecognized HTTP code {version}" ))); } } else { @@ -180,8 +178,7 @@ pub fn decode_http_response(payload: &[u8]) -> Result<(HashMap, let key = resp.headers[i].name.to_string().to_lowercase(); if headers.contains_key(&key) { return Err(RPCError::MalformedResponse(format!( - "Invalid HTTP respuest: duplicate header \"{}\"", - key + "Invalid HTTP respuest: duplicate header \"{key}\"" ))); } headers.insert(key, value); @@ -237,13 +234,11 @@ pub fn run_http_request( let req_txt = if let Some(content_type) = content_type { format!( - "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nContent-Type: {}\r\n{}User-Agent: libsigner/0.1\r\nAccept: */*\r\n\r\n", - verb, path, host, content_type, content_length_hdr + "{verb} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nContent-Type: {content_type}\r\n{content_length_hdr}User-Agent: libsigner/0.1\r\nAccept: */*\r\n\r\n" ) } else { format!( - "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n{}User-Agent: libsigner/0.1\r\nAccept: */*\r\n\r\n", - verb, path, host, content_length_hdr + "{verb} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n{content_length_hdr}User-Agent: libsigner/0.1\r\nAccept: */*\r\n\r\n" ) }; debug!("HTTP request\n{}", &req_txt); diff --git a/libsigner/src/libsigner.rs b/libsigner/src/libsigner.rs index 1198112388..3cecbfb5fd 100644 --- a/libsigner/src/libsigner.rs +++ b/libsigner/src/libsigner.rs @@ -88,5 +88,5 @@ lazy_static! { #[test] fn test_version_string() { - assert!(VERSION_STRING.contains(format!("stacks-signer {}", STACKS_SIGNER_VERSION).as_str())); + assert!(VERSION_STRING.contains(format!("stacks-signer {STACKS_SIGNER_VERSION}").as_str())); } diff --git a/libsigner/src/runloop.rs b/libsigner/src/runloop.rs index ecb8a25662..f66ec9bdbf 100644 --- a/libsigner/src/runloop.rs +++ b/libsigner/src/runloop.rs @@ -170,7 +170,7 @@ pub fn set_runloop_signal_handler(mut st } } _ => { - let msg = format!("Graceful termination request received (signal `{}`), will complete the ongoing runloop cycles and terminate\n", sig_id); + let msg = format!("Graceful termination request received (signal `{sig_id}`), will complete the ongoing runloop cycles and terminate\n"); async_safe_write_stderr(&msg); stop_signaler.send(); } diff --git a/libsigner/src/tests/mod.rs b/libsigner/src/tests/mod.rs index 593de940c1..778c84758a 100644 --- a/libsigner/src/tests/mod.rs +++ b/libsigner/src/tests/mod.rs @@ -229,15 +229,12 @@ fn test_status_endpoint() { let mut sock = match TcpStream::connect(endpoint) { Ok(sock) => sock, Err(e) => { - eprint!("Error connecting to {}: {}", endpoint, e); + eprint!("Error connecting to {endpoint}: {e}"); sleep_ms(100); return; } }; - let req = format!( - "GET /status HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", - endpoint - ); + let req = format!("GET /status HTTP/1.1\r\nHost: {endpoint}\r\nConnection: close\r\n\r\n"); sock.write_all(req.as_bytes()).unwrap(); let mut buf = [0; 128]; diff --git a/libsigner/src/v0/messages.rs b/libsigner/src/v0/messages.rs index 30cd5a2bfb..8854522bdf 100644 --- a/libsigner/src/v0/messages.rs +++ b/libsigner/src/v0/messages.rs @@ -1725,7 +1725,7 @@ impl StacksMessageCodec for RejectReason { impl std::fmt::Display for RejectCode { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - RejectCode::ValidationFailed(code) => write!(f, "Validation failed: {:?}", code), + RejectCode::ValidationFailed(code) => write!(f, "Validation failed: {code:?}"), RejectCode::ConnectivityIssues(reason) => write!( f, "The block was rejected due to connectivity issues with the signer: {reason}" @@ -1754,7 +1754,7 @@ impl std::fmt::Display for RejectCode { impl std::fmt::Display for RejectReason { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - RejectReason::ValidationFailed(code) => write!(f, "Validation failed: {:?}", code), + RejectReason::ValidationFailed(code) => write!(f, "Validation failed: {code:?}"), RejectReason::ConnectivityIssues(reason) => write!( f, "The block was rejected due to connectivity issues with the signer: {reason}" @@ -1830,7 +1830,7 @@ impl std::fmt::Display for RejectReason { ) } RejectReason::Unknown(code) => { - write!(f, "Unknown reject code: {}", code) + write!(f, "Unknown reject code: {code}") } RejectReason::NotRejected => { write!(f, "The block was approved, no rejection details needed.") @@ -1870,9 +1870,7 @@ mod test { let slot_identifiers_len = MessageSlotID::ALL.len(); assert!( SIGNER_SLOTS_PER_USER as usize >= slot_identifiers_len, - "stacks_common::SIGNER_SLOTS_PER_USER ({}) must be >= slot identifiers ({})", - SIGNER_SLOTS_PER_USER, - slot_identifiers_len, + "stacks_common::SIGNER_SLOTS_PER_USER ({SIGNER_SLOTS_PER_USER}) must be >= slot identifiers ({slot_identifiers_len})" ); } From a638e68c3415ae79b4413cb4b4e1a4481cecf626 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 11:23:19 -0700 Subject: [PATCH 5/8] Fix clippy warnings in clarity Signed-off-by: Jacinta Ferrant --- .../src/vm/analysis/arithmetic_checker/mod.rs | 2 +- .../vm/analysis/arithmetic_checker/tests.rs | 21 +-- clarity/src/vm/analysis/errors.rs | 106 +++++++-------- .../vm/analysis/read_only_checker/tests.rs | 2 +- .../src/vm/analysis/trait_checker/tests.rs | 58 ++++---- .../type_checker/v2_05/tests/assets.rs | 4 +- .../type_checker/v2_05/tests/contracts.rs | 15 +-- .../analysis/type_checker/v2_05/tests/mod.rs | 38 ++---- .../type_checker/v2_1/tests/assets.rs | 4 +- .../type_checker/v2_1/tests/contracts.rs | 124 +++++++++--------- .../analysis/type_checker/v2_1/tests/mod.rs | 42 +++--- clarity/src/vm/ast/errors.rs | 69 +++++----- clarity/src/vm/ast/mod.rs | 2 +- clarity/src/vm/ast/parser/v1.rs | 28 ++-- clarity/src/vm/ast/parser/v2/lexer/error.rs | 28 ++-- clarity/src/vm/ast/parser/v2/lexer/mod.rs | 36 ++--- clarity/src/vm/ast/parser/v2/lexer/token.rs | 12 +- clarity/src/vm/ast/parser/v2/mod.rs | 45 +++---- clarity/src/vm/callables.rs | 8 +- clarity/src/vm/contexts.rs | 28 ++-- clarity/src/vm/coverage.rs | 12 +- clarity/src/vm/database/clarity_db.rs | 39 +++--- clarity/src/vm/database/clarity_store.rs | 2 +- clarity/src/vm/database/sqlite.rs | 25 ++-- clarity/src/vm/docs/contracts.rs | 4 +- clarity/src/vm/docs/mod.rs | 37 +++--- clarity/src/vm/errors.rs | 2 +- clarity/src/vm/events.rs | 30 ++--- clarity/src/vm/mod.rs | 6 +- clarity/src/vm/representations.rs | 13 +- clarity/src/vm/test_util/mod.rs | 6 +- clarity/src/vm/tests/assets.rs | 2 +- clarity/src/vm/tests/contracts.rs | 4 +- clarity/src/vm/tests/datamaps.rs | 2 +- clarity/src/vm/tests/defines.rs | 25 ++-- clarity/src/vm/tests/sequences.rs | 26 ++-- clarity/src/vm/tests/simple_apply_eval.rs | 29 ++-- clarity/src/vm/tests/traits.rs | 12 +- clarity/src/vm/types/mod.rs | 86 ++++++------ clarity/src/vm/types/serialization.rs | 31 ++--- clarity/src/vm/types/signatures.rs | 20 +-- 41 files changed, 492 insertions(+), 593 deletions(-) diff --git a/clarity/src/vm/analysis/arithmetic_checker/mod.rs b/clarity/src/vm/analysis/arithmetic_checker/mod.rs index e0f774d9be..fc1b0659c4 100644 --- a/clarity/src/vm/analysis/arithmetic_checker/mod.rs +++ b/clarity/src/vm/analysis/arithmetic_checker/mod.rs @@ -58,7 +58,7 @@ impl std::error::Error for Error { impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/clarity/src/vm/analysis/arithmetic_checker/tests.rs b/clarity/src/vm/analysis/arithmetic_checker/tests.rs index 0e7d520cb3..ea55512d40 100644 --- a/clarity/src/vm/analysis/arithmetic_checker/tests.rs +++ b/clarity/src/vm/analysis/arithmetic_checker/tests.rs @@ -77,8 +77,7 @@ fn test_bad_defines(#[case] version: ClarityVersion, #[case] epoch: StacksEpochI assert_eq!( arithmetic_check(contract, version, epoch), Err(error.clone()), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); } } @@ -120,14 +119,12 @@ fn test_variables_fail_arithmetic_check_clarity1() { assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity1, StacksEpochId::Epoch2_05), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity1, StacksEpochId::Epoch21), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); } @@ -188,8 +185,7 @@ fn test_variables_fail_arithmetic_check_clarity2() { assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity2, StacksEpochId::Epoch21), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); } } @@ -321,14 +317,12 @@ fn test_functions_clarity1() { assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity1, StacksEpochId::Epoch2_05), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity1, StacksEpochId::Epoch21), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); } } @@ -458,8 +452,7 @@ fn test_functions_clarity2() { assert_eq!( arithmetic_check(contract, ClarityVersion::Clarity2, StacksEpochId::Epoch21), result.clone(), - "Check contract:\n {}", - contract + "Check contract:\n {contract}" ); } } diff --git a/clarity/src/vm/analysis/errors.rs b/clarity/src/vm/analysis/errors.rs index 6cd03afc3c..29a5081626 100644 --- a/clarity/src/vm/analysis/errors.rs +++ b/clarity/src/vm/analysis/errors.rs @@ -244,7 +244,7 @@ impl CheckError { impl fmt::Display for CheckErrors { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } @@ -253,7 +253,7 @@ impl fmt::Display for CheckError { write!(f, "{}", self.err)?; if let Some(ref e) = self.expressions { - write!(f, "\nNear:\n{:?}", e)?; + write!(f, "\nNear:\n{e:?}")?; } Ok(()) @@ -332,7 +332,7 @@ fn formatted_expected_types(expected_types: &[TypeSignature]) -> String { if expected_types.len() > 2 { for expected_type in expected_types[1..expected_types.len() - 1].iter() { - expected_types_joined.push_str(&format!(", '{}'", expected_type)); + expected_types_joined.push_str(&format!(", '{expected_type}'")); } } expected_types_joined.push_str(&format!( @@ -355,112 +355,112 @@ impl DiagnosableError for CheckErrors { format!("match on a result type uses the following syntax: (match input ok-name if-ok-expression err-name if-err-expression). Caused by: {}", source.message()), CheckErrors::BadMatchInput(t) => - format!("match requires an input of either a response or optional, found input: '{}'", t), + format!("match requires an input of either a response or optional, found input: '{t}'"), CheckErrors::TypeAnnotationExpectedFailure => "analysis expected type to already be annotated for expression".into(), CheckErrors::CostOverflow => "contract execution cost overflowed cost counter".into(), - CheckErrors::CostBalanceExceeded(a, b) => format!("contract execution cost exceeded budget: {:?} > {:?}", a, b), - CheckErrors::MemoryBalanceExceeded(a, b) => format!("contract execution cost exceeded memory budget: {:?} > {:?}", a, b), + CheckErrors::CostBalanceExceeded(a, b) => format!("contract execution cost exceeded budget: {a:?} > {b:?}"), + CheckErrors::MemoryBalanceExceeded(a, b) => format!("contract execution cost exceeded memory budget: {a:?} > {b:?}"), CheckErrors::InvalidTypeDescription => "supplied type description is invalid".into(), CheckErrors::EmptyTuplesNotAllowed => "tuple types may not be empty".into(), CheckErrors::BadSyntaxExpectedListOfPairs => "bad syntax: function expects a list of pairs to bind names, e.g., ((name-0 a) (name-1 b) ...)".into(), - CheckErrors::UnknownTypeName(name) => format!("failed to parse type: '{}'", name), + CheckErrors::UnknownTypeName(name) => format!("failed to parse type: '{name}'"), CheckErrors::ValueTooLarge => "created a type which was greater than maximum allowed value size".into(), CheckErrors::ValueOutOfBounds => "created a type which value size was out of defined bounds".into(), CheckErrors::TypeSignatureTooDeep => "created a type which was deeper than maximum allowed type depth".into(), CheckErrors::ExpectedName => "expected a name argument to this function".into(), - CheckErrors::NoSuperType(a, b) => format!("unable to create a supertype for the two types: '{}' and '{}'", a, b), + CheckErrors::NoSuperType(a, b) => format!("unable to create a supertype for the two types: '{a}' and '{b}'"), CheckErrors::UnknownListConstructionFailure => "invalid syntax for list definition".into(), CheckErrors::ListTypesMustMatch => "expecting elements of same type in a list".into(), CheckErrors::ConstructedListTooLarge => "reached limit of elements in a sequence".into(), - CheckErrors::TypeError(expected_type, found_type) => format!("expecting expression of type '{}', found '{}'", expected_type, found_type), - CheckErrors::TypeLiteralError(expected_type, found_type) => format!("expecting a literal of type '{}', found '{}'", expected_type, found_type), - CheckErrors::TypeValueError(expected_type, found_value) => format!("expecting expression of type '{}', found '{}'", expected_type, found_value), + CheckErrors::TypeError(expected_type, found_type) => format!("expecting expression of type '{expected_type}', found '{found_type}'"), + CheckErrors::TypeLiteralError(expected_type, found_type) => format!("expecting a literal of type '{expected_type}', found '{found_type}'"), + CheckErrors::TypeValueError(expected_type, found_value) => format!("expecting expression of type '{expected_type}', found '{found_value}'"), CheckErrors::UnionTypeError(expected_types, found_type) => format!("expecting expression of type {}, found '{}'", formatted_expected_types(expected_types), found_type), CheckErrors::UnionTypeValueError(expected_types, found_type) => format!("expecting expression of type {}, found '{}'", formatted_expected_types(expected_types), found_type), - CheckErrors::ExpectedOptionalType(found_type) => format!("expecting expression of type 'optional', found '{}'", found_type), - CheckErrors::ExpectedOptionalOrResponseType(found_type) => format!("expecting expression of type 'optional' or 'response', found '{}'", found_type), - CheckErrors::ExpectedOptionalOrResponseValue(found_type) => format!("expecting expression of type 'optional' or 'response', found '{}'", found_type), - CheckErrors::ExpectedResponseType(found_type) => format!("expecting expression of type 'response', found '{}'", found_type), - CheckErrors::ExpectedOptionalValue(found_type) => format!("expecting expression of type 'optional', found '{}'", found_type), - CheckErrors::ExpectedResponseValue(found_type) => format!("expecting expression of type 'response', found '{}'", found_type), + CheckErrors::ExpectedOptionalType(found_type) => format!("expecting expression of type 'optional', found '{found_type}'"), + CheckErrors::ExpectedOptionalOrResponseType(found_type) => format!("expecting expression of type 'optional' or 'response', found '{found_type}'"), + CheckErrors::ExpectedOptionalOrResponseValue(found_type) => format!("expecting expression of type 'optional' or 'response', found '{found_type}'"), + CheckErrors::ExpectedResponseType(found_type) => format!("expecting expression of type 'response', found '{found_type}'"), + CheckErrors::ExpectedOptionalValue(found_type) => format!("expecting expression of type 'optional', found '{found_type}'"), + CheckErrors::ExpectedResponseValue(found_type) => format!("expecting expression of type 'response', found '{found_type}'"), CheckErrors::CouldNotDetermineResponseOkType => "attempted to obtain 'ok' value from response, but 'ok' type is indeterminate".into(), CheckErrors::CouldNotDetermineResponseErrType => "attempted to obtain 'err' value from response, but 'err' type is indeterminate".into(), CheckErrors::CouldNotDetermineMatchTypes => "attempted to match on an (optional) or (response) type where either the some, ok, or err type is indeterminate. you may wish to use unwrap-panic or unwrap-err-panic instead.".into(), CheckErrors::CouldNotDetermineType => "type of expression cannot be determined".into(), CheckErrors::BadTupleFieldName => "invalid tuple field name".into(), - CheckErrors::ExpectedTuple(type_signature) => format!("expecting tuple, found '{}'", type_signature), - CheckErrors::NoSuchTupleField(field_name, tuple_signature) => format!("cannot find field '{}' in tuple '{}'", field_name, tuple_signature), + CheckErrors::ExpectedTuple(type_signature) => format!("expecting tuple, found '{type_signature}'"), + CheckErrors::NoSuchTupleField(field_name, tuple_signature) => format!("cannot find field '{field_name}' in tuple '{tuple_signature}'"), CheckErrors::BadTupleConstruction => "invalid tuple syntax, expecting list of pair".into(), CheckErrors::TupleExpectsPairs => "invalid tuple syntax, expecting pair".into(), - CheckErrors::NoSuchDataVariable(var_name) => format!("use of unresolved persisted variable '{}'", var_name), + CheckErrors::NoSuchDataVariable(var_name) => format!("use of unresolved persisted variable '{var_name}'"), CheckErrors::BadTransferSTXArguments => "STX transfer expects an int amount, from principal, to principal".into(), CheckErrors::BadTransferFTArguments => "transfer expects an int amount, from principal, to principal".into(), CheckErrors::BadTransferNFTArguments => "transfer expects an asset, from principal, to principal".into(), CheckErrors::BadMintFTArguments => "mint expects a uint amount and from principal".into(), CheckErrors::BadBurnFTArguments => "burn expects a uint amount and from principal".into(), CheckErrors::BadMapName => "invalid map name".into(), - CheckErrors::NoSuchMap(map_name) => format!("use of unresolved map '{}'", map_name), + CheckErrors::NoSuchMap(map_name) => format!("use of unresolved map '{map_name}'"), CheckErrors::DefineFunctionBadSignature => "invalid function definition".into(), CheckErrors::BadFunctionName => "invalid function name".into(), CheckErrors::BadMapTypeDefinition => "invalid map definition".into(), - CheckErrors::PublicFunctionMustReturnResponse(found_type) => format!("public functions must return an expression of type 'response', found '{}'", found_type), + CheckErrors::PublicFunctionMustReturnResponse(found_type) => format!("public functions must return an expression of type 'response', found '{found_type}'"), CheckErrors::DefineVariableBadSignature => "invalid variable definition".into(), - CheckErrors::ReturnTypesMustMatch(type_1, type_2) => format!("detected two execution paths, returning two different expression types (got '{}' and '{}')", type_1, type_2), - CheckErrors::NoSuchContract(contract_identifier) => format!("use of unresolved contract '{}'", contract_identifier), - CheckErrors::NoSuchPublicFunction(contract_identifier, function_name) => format!("contract '{}' has no public function '{}'", contract_identifier, function_name), - CheckErrors::PublicFunctionNotReadOnly(contract_identifier, function_name) => format!("function '{}' in '{}' is not read-only", contract_identifier, function_name), - CheckErrors::ContractAlreadyExists(contract_identifier) => format!("contract name '{}' conflicts with existing contract", contract_identifier), + CheckErrors::ReturnTypesMustMatch(type_1, type_2) => format!("detected two execution paths, returning two different expression types (got '{type_1}' and '{type_2}')"), + CheckErrors::NoSuchContract(contract_identifier) => format!("use of unresolved contract '{contract_identifier}'"), + CheckErrors::NoSuchPublicFunction(contract_identifier, function_name) => format!("contract '{contract_identifier}' has no public function '{function_name}'"), + CheckErrors::PublicFunctionNotReadOnly(contract_identifier, function_name) => format!("function '{contract_identifier}' in '{function_name}' is not read-only"), + CheckErrors::ContractAlreadyExists(contract_identifier) => format!("contract name '{contract_identifier}' conflicts with existing contract"), CheckErrors::ContractCallExpectName => "missing contract name for call".into(), - CheckErrors::ExpectedCallableType(found_type) => format!("expected a callable contract, found {}", found_type), - CheckErrors::NoSuchBlockInfoProperty(property_name) => format!("use of block unknown property '{}'", property_name), - CheckErrors::NoSuchBurnBlockInfoProperty(property_name) => format!("use of burn block unknown property '{}'", property_name), - CheckErrors::NoSuchStacksBlockInfoProperty(property_name) => format!("use of unknown stacks block property '{}'", property_name), - CheckErrors::NoSuchTenureInfoProperty(property_name) => format!("use of unknown tenure property '{}'", property_name), + CheckErrors::ExpectedCallableType(found_type) => format!("expected a callable contract, found {found_type}"), + CheckErrors::NoSuchBlockInfoProperty(property_name) => format!("use of block unknown property '{property_name}'"), + CheckErrors::NoSuchBurnBlockInfoProperty(property_name) => format!("use of burn block unknown property '{property_name}'"), + CheckErrors::NoSuchStacksBlockInfoProperty(property_name) => format!("use of unknown stacks block property '{property_name}'"), + CheckErrors::NoSuchTenureInfoProperty(property_name) => format!("use of unknown tenure property '{property_name}'"), CheckErrors::GetBlockInfoExpectPropertyName => "missing property name for block info introspection".into(), CheckErrors::GetBurnBlockInfoExpectPropertyName => "missing property name for burn block info introspection".into(), CheckErrors::GetStacksBlockInfoExpectPropertyName => "missing property name for stacks block info introspection".into(), CheckErrors::GetTenureInfoExpectPropertyName => "missing property name for tenure info introspection".into(), - CheckErrors::NameAlreadyUsed(name) => format!("defining '{}' conflicts with previous value", name), + CheckErrors::NameAlreadyUsed(name) => format!("defining '{name}' conflicts with previous value"), CheckErrors::ReservedWord(name) => format!("{name} is a reserved word"), CheckErrors::NonFunctionApplication => "expecting expression of type function".into(), CheckErrors::ExpectedListApplication => "expecting expression of type list".into(), - CheckErrors::ExpectedSequence(found_type) => format!("expecting expression of type 'list', 'buff', 'string-ascii' or 'string-utf8' - found '{}'", found_type), + CheckErrors::ExpectedSequence(found_type) => format!("expecting expression of type 'list', 'buff', 'string-ascii' or 'string-utf8' - found '{found_type}'"), CheckErrors::MaxLengthOverflow => format!("expecting a value <= {}", u32::MAX), CheckErrors::BadLetSyntax => "invalid syntax of 'let'".into(), CheckErrors::CircularReference(references) => format!("detected circular reference: ({})", references.join(", ")), CheckErrors::BadSyntaxBinding => "invalid syntax binding".into(), CheckErrors::MaxContextDepthReached => "reached depth limit".into(), - CheckErrors::UndefinedVariable(var_name) => format!("use of unresolved variable '{}'", var_name), - CheckErrors::UndefinedFunction(var_name) => format!("use of unresolved function '{}'", var_name), - CheckErrors::RequiresAtLeastArguments(expected, found) => format!("expecting >= {} arguments, got {}", expected, found), - CheckErrors::RequiresAtMostArguments(expected, found) => format!("expecting < {} arguments, got {}", expected, found), - CheckErrors::IncorrectArgumentCount(expected_count, found_count) => format!("expecting {} arguments, got {}", expected_count, found_count), - CheckErrors::IfArmsMustMatch(type_1, type_2) => format!("expression types returned by the arms of 'if' must match (got '{}' and '{}')", type_1, type_2), - CheckErrors::MatchArmsMustMatch(type_1, type_2) => format!("expression types returned by the arms of 'match' must match (got '{}' and '{}')", type_1, type_2), - CheckErrors::DefaultTypesMustMatch(type_1, type_2) => format!("expression types passed in 'default-to' must match (got '{}' and '{}')", type_1, type_2), + CheckErrors::UndefinedVariable(var_name) => format!("use of unresolved variable '{var_name}'"), + CheckErrors::UndefinedFunction(var_name) => format!("use of unresolved function '{var_name}'"), + CheckErrors::RequiresAtLeastArguments(expected, found) => format!("expecting >= {expected} arguments, got {found}"), + CheckErrors::RequiresAtMostArguments(expected, found) => format!("expecting < {expected} arguments, got {found}"), + CheckErrors::IncorrectArgumentCount(expected_count, found_count) => format!("expecting {expected_count} arguments, got {found_count}"), + CheckErrors::IfArmsMustMatch(type_1, type_2) => format!("expression types returned by the arms of 'if' must match (got '{type_1}' and '{type_2}')"), + CheckErrors::MatchArmsMustMatch(type_1, type_2) => format!("expression types returned by the arms of 'match' must match (got '{type_1}' and '{type_2}')"), + CheckErrors::DefaultTypesMustMatch(type_1, type_2) => format!("expression types passed in 'default-to' must match (got '{type_1}' and '{type_2}')"), CheckErrors::TooManyExpressions => "reached limit of expressions".into(), - CheckErrors::IllegalOrUnknownFunctionApplication(function_name) => format!("use of illegal / unresolved function '{}", function_name), - CheckErrors::UnknownFunction(function_name) => format!("use of unresolved function '{}'", function_name), + CheckErrors::IllegalOrUnknownFunctionApplication(function_name) => format!("use of illegal / unresolved function '{function_name}"), + CheckErrors::UnknownFunction(function_name) => format!("use of unresolved function '{function_name}'"), CheckErrors::TraitBasedContractCallInReadOnly => "use of trait based contract calls are not allowed in read-only context".into(), CheckErrors::WriteAttemptedInReadOnly => "expecting read-only statements, detected a writing operation".into(), CheckErrors::AtBlockClosureMustBeReadOnly => "(at-block ...) closures expect read-only statements, but detected a writing operation".into(), CheckErrors::BadTokenName => "expecting an token name as an argument".into(), CheckErrors::DefineFTBadSignature => "(define-token ...) expects a token name as an argument".into(), CheckErrors::DefineNFTBadSignature => "(define-asset ...) expects an asset name and an asset identifier type signature as arguments".into(), - CheckErrors::NoSuchNFT(asset_name) => format!("tried to use asset function with a undefined asset ('{}')", asset_name), - CheckErrors::NoSuchFT(asset_name) => format!("tried to use token function with a undefined token ('{}')", asset_name), - CheckErrors::NoSuchTrait(contract_name, trait_name) => format!("use of unresolved trait {}.{}", contract_name, trait_name), - CheckErrors::TraitReferenceUnknown(trait_name) => format!("use of undeclared trait <{}>", trait_name), - CheckErrors::TraitMethodUnknown(trait_name, func_name) => format!("method '{}' unspecified in trait <{}>", func_name, trait_name), + CheckErrors::NoSuchNFT(asset_name) => format!("tried to use asset function with a undefined asset ('{asset_name}')"), + CheckErrors::NoSuchFT(asset_name) => format!("tried to use token function with a undefined token ('{asset_name}')"), + CheckErrors::NoSuchTrait(contract_name, trait_name) => format!("use of unresolved trait {contract_name}.{trait_name}"), + CheckErrors::TraitReferenceUnknown(trait_name) => format!("use of undeclared trait <{trait_name}>"), + CheckErrors::TraitMethodUnknown(trait_name, func_name) => format!("method '{func_name}' unspecified in trait <{trait_name}>"), CheckErrors::ImportTraitBadSignature => "(use-trait ...) expects a trait name and a trait identifier".into(), - CheckErrors::BadTraitImplementation(trait_name, func_name) => format!("invalid signature for method '{}' regarding trait's specification <{}>", func_name, trait_name), + CheckErrors::BadTraitImplementation(trait_name, func_name) => format!("invalid signature for method '{func_name}' regarding trait's specification <{trait_name}>"), CheckErrors::ExpectedTraitIdentifier => "expecting expression of type trait identifier".into(), CheckErrors::UnexpectedTraitOrFieldReference => "unexpected use of trait reference or field".into(), CheckErrors::DefineTraitBadSignature => "invalid trait definition".into(), - CheckErrors::DefineTraitDuplicateMethod(method_name) => format!("duplicate method name '{}' in trait definition", method_name), + CheckErrors::DefineTraitDuplicateMethod(method_name) => format!("duplicate method name '{method_name}' in trait definition"), CheckErrors::TraitReferenceNotAllowed => "trait references can not be stored".into(), CheckErrors::ContractOfExpectsTrait => "trait reference expected".into(), - CheckErrors::IncompatibleTrait(expected_trait, actual_trait) => format!("trait '{}' is not a compatible with expected trait, '{}'", actual_trait, expected_trait), + CheckErrors::IncompatibleTrait(expected_trait, actual_trait) => format!("trait '{actual_trait}' is not a compatible with expected trait, '{expected_trait}'"), CheckErrors::InvalidCharactersDetected => "invalid characters detected".into(), CheckErrors::InvalidUTF8Encoding => "invalid UTF8 encoding".into(), CheckErrors::InvalidSecp65k1Signature => "invalid seckp256k1 signature".into(), @@ -468,7 +468,7 @@ impl DiagnosableError for CheckErrors { "internal error - please file an issue on https://github.com/stacks-network/stacks-blockchain".into() }, CheckErrors::UncheckedIntermediaryResponses => "intermediary responses in consecutive statements must be checked".into(), - CheckErrors::CostComputationFailed(s) => format!("contract cost computation failed: {}", s), + CheckErrors::CostComputationFailed(s) => format!("contract cost computation failed: {s}"), CheckErrors::CouldNotDetermineSerializationType => "could not determine the input type for the serialization function".into(), CheckErrors::ExecutionTimeExpired => "execution time expired".into(), } diff --git a/clarity/src/vm/analysis/read_only_checker/tests.rs b/clarity/src/vm/analysis/read_only_checker/tests.rs index 1f0d17117b..56eb0c47c6 100644 --- a/clarity/src/vm/analysis/read_only_checker/tests.rs +++ b/clarity/src/vm/analysis/read_only_checker/tests.rs @@ -71,7 +71,7 @@ fn test_at_block_violations() { for contract in examples.iter() { let err = mem_type_check(contract).unwrap_err(); - eprintln!("{}", err); + eprintln!("{err}"); assert_eq!(err.err, CheckErrors::AtBlockClosureMustBeReadOnly) } } diff --git a/clarity/src/vm/analysis/trait_checker/tests.rs b/clarity/src/vm/analysis/trait_checker/tests.rs index ab997afc58..2361cd1726 100644 --- a/clarity/src/vm/analysis/trait_checker/tests.rs +++ b/clarity/src/vm/analysis/trait_checker/tests.rs @@ -99,7 +99,7 @@ fn test_incomplete_impl_trait_1(#[case] version: ClarityVersion, #[case] epoch: .unwrap_err(); match err.err { CheckErrors::BadTraitImplementation(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -126,7 +126,7 @@ fn test_incomplete_impl_trait_2(#[case] version: ClarityVersion, #[case] epoch: .unwrap_err(); match err.err { CheckErrors::BadTraitImplementation(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -150,7 +150,7 @@ fn test_impl_trait_arg_admission_1(#[case] version: ClarityVersion, #[case] epoc .unwrap_err(); match err.err { CheckErrors::BadTraitImplementation(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -290,7 +290,7 @@ fn test_get_trait_reference_from_tuple( .unwrap_err(); match err.err { CheckErrors::ContractCallExpectName => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -333,7 +333,7 @@ fn test_dynamic_dispatch_by_defining_and_impl_trait( .unwrap_err(); match err.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -360,7 +360,7 @@ fn test_define_map_storing_trait_references( match err.err { ParseErrors::TraitReferenceNotAllowed => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -384,7 +384,7 @@ fn test_cycle_in_traits_1_contract(#[case] version: ClarityVersion, #[case] epoc .unwrap_err(); match err.err { ParseErrors::CircularReference(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -435,7 +435,7 @@ fn test_cycle_in_traits_2_contracts(#[case] version: ClarityVersion, #[case] epo .unwrap_err(); match err.err { CheckErrors::NoSuchContract(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -488,7 +488,7 @@ fn test_dynamic_dispatch_unknown_method( .unwrap_err(); match err.err { CheckErrors::TraitMethodUnknown(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -672,7 +672,7 @@ fn test_dynamic_dispatch_collision_trait( .unwrap_err(); match err.err { ParseErrors::NameAlreadyUsed(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -701,7 +701,7 @@ fn test_dynamic_dispatch_collision_defined_trait( .unwrap_err(); match err.err { ParseErrors::NameAlreadyUsed(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -741,7 +741,7 @@ fn test_dynamic_dispatch_collision_imported_trait( .unwrap_err(); match err.err { ParseErrors::NameAlreadyUsed(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -813,7 +813,7 @@ fn test_dynamic_dispatch_importing_non_existant_trait( .unwrap_err(); match err.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -1106,7 +1106,7 @@ fn test_dynamic_dispatch_including_wrong_nested_trait( CheckErrors::TypeError(TypeSignature::CallableType(_), TypeSignature::CallableType(_)) if epoch >= StacksEpochId::Epoch21 && version < ClarityVersion::Clarity2 => {} CheckErrors::TraitReferenceUnknown(name) => assert_eq!(name.as_str(), "trait-a"), - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -1160,7 +1160,7 @@ fn test_dynamic_dispatch_mismatched_args( .unwrap_err(); match err.err { CheckErrors::TypeError(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -1214,7 +1214,7 @@ fn test_dynamic_dispatch_mismatched_returns( .unwrap_err(); match err.err { CheckErrors::BadTraitImplementation(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -1250,7 +1250,7 @@ fn test_bad_call_with_trait(#[case] version: ClarityVersion, #[case] epoch: Stac .unwrap_err(); match err.err { CheckErrors::TypeError(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), } } @@ -1276,7 +1276,7 @@ fn test_good_call_with_trait(#[case] version: ClarityVersion, #[case] epoch: Sta let mut marf = MemoryBackingStore::new(); let mut db = marf.as_analysis_db(); - println!("c4: {:?}", c4); + println!("c4: {c4:?}"); db.execute(|db| { type_check(&def_contract_id, &mut c1, db, true, &epoch, &version).unwrap(); @@ -1310,7 +1310,7 @@ fn test_good_call_2_with_trait(#[case] version: ClarityVersion, #[case] epoch: S let mut marf = MemoryBackingStore::new(); let mut db = marf.as_analysis_db(); - println!("c4: {:?}", c4); + println!("c4: {c4:?}"); db.execute(|db| { type_check(&def_contract_id, &mut c1, db, true, &epoch, &version).unwrap(); @@ -1459,11 +1459,11 @@ fn test_dynamic_dispatch_pass_bound_principal_as_trait_in_user_defined_functions Err(err) if version == ClarityVersion::Clarity1 => { match err.err { CheckErrors::TypeError(_, _) => {} - _ => panic!("{:?}", err), + _ => panic!("{err:?}"), }; } Ok(_) if version >= ClarityVersion::Clarity2 => (), - _ => panic!("got {:?}", result), + _ => panic!("got {result:?}"), } } @@ -1553,7 +1553,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_principal.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_principal), + _ => panic!("{err_principal:?}"), } let err_int = db .execute(|db| { @@ -1563,7 +1563,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_int.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_int), + _ => panic!("{err_int:?}"), } let err_uint = db .execute(|db| { @@ -1573,7 +1573,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_uint.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_uint), + _ => panic!("{err_uint:?}"), } let err_bool = db .execute(|db| { @@ -1583,7 +1583,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_bool.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_bool), + _ => panic!("{err_bool:?}"), } let err_list = db .execute(|db| { @@ -1593,7 +1593,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_list.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_list), + _ => panic!("{err_list:?}"), } let err_buff = db .execute(|db| { @@ -1603,7 +1603,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_buff.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_buff), + _ => panic!("{err_buff:?}"), } let err_tuple = db .execute(|db| { @@ -1613,7 +1613,7 @@ fn test_contract_of_wrong_type(#[case] version: ClarityVersion, #[case] epoch: S .unwrap_err(); match err_tuple.err { CheckErrors::TraitReferenceUnknown(_) => {} - _ => panic!("{:?}", err_tuple), + _ => panic!("{err_tuple:?}"), } } @@ -1816,6 +1816,6 @@ fn test_trait_contract_not_found(#[case] version: ClarityVersion, #[case] epoch: diagnostic: _, }) if version < ClarityVersion::Clarity2 => assert!(contract.ends_with(".trait-contract")), Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("{}: {:?}", version, res), + res => panic!("{version}: {res:?}"), } } diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs index badfba6245..3d1e8ad9d1 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/assets.rs @@ -235,14 +235,14 @@ fn test_bad_asset_usage() { ]; for (script, expected_err) in bad_scripts.iter().zip(expected.iter()) { - let tokens_contract = format!("{}\n{}", FIRST_CLASS_TOKENS, script); + let tokens_contract = format!("{FIRST_CLASS_TOKENS}\n{script}"); let actual_err = mem_type_check( &tokens_contract, ClarityVersion::Clarity1, StacksEpochId::Epoch2_05, ) .unwrap_err(); - println!("{}", script); + println!("{script}"); assert_eq!(&actual_err.err, expected_err); } } diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs index 0eec9c1d67..ed5a53d7bf 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/contracts.rs @@ -382,7 +382,7 @@ fn test_names_tokens_contracts_interface() { "non_fungible_tokens": [] }"#).unwrap(); - eprintln!("{}", test_contract_json_str); + eprintln!("{test_contract_json_str}"); assert_json_eq!(test_contract_json, test_contract_json_expected); } @@ -443,9 +443,8 @@ fn test_names_tokens_contracts_bad() { (err 1)))"; let names_contract = format!( - "{} - {}", - SIMPLE_NAMES, broken_public + "{SIMPLE_NAMES} + {broken_public}" ); let tokens_contract_id = QualifiedContractIdentifier::local("tokens").unwrap(); @@ -663,7 +662,7 @@ fn test_expects() { StacksEpochId::Epoch2_05, ) .unwrap_err(); - eprintln!("unmatched_return_types returned check error: {}", err); + eprintln!("unmatched_return_types returned check error: {err}"); assert!(matches!(err.err, CheckErrors::ReturnTypesMustMatch(_, _))); } @@ -673,7 +672,7 @@ fn test_expects() { StacksEpochId::Epoch2_05, ) .unwrap_err(); - eprintln!("bad_default_types returned check error: {}", err); + eprintln!("bad_default_types returned check error: {err}"); assert!(matches!(err.err, CheckErrors::DefaultTypesMustMatch(_, _))); let err = mem_type_check( @@ -682,7 +681,7 @@ fn test_expects() { StacksEpochId::Epoch2_05, ) .unwrap_err(); - eprintln!("notype_response_type returned check error: {}", err); + eprintln!("notype_response_type returned check error: {err}"); assert!(matches!( err.err, CheckErrors::CouldNotDetermineResponseErrType @@ -694,7 +693,7 @@ fn test_expects() { StacksEpochId::Epoch2_05, ) .unwrap_err(); - eprintln!("notype_response_type_2 returned check error: {}", err); + eprintln!("notype_response_type_2 returned check error: {err}"); assert!(matches!( err.err, CheckErrors::CouldNotDetermineResponseOkType diff --git a/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs b/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs index c314fa319d..68c7bec3b6 100644 --- a/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_05/tests/mod.rs @@ -1134,7 +1134,7 @@ fn test_concat_append_supertypes() { ]; for (good_test, expected) in good.iter().zip(expected.iter()) { - eprintln!("{}", good_test); + eprintln!("{good_test}"); assert_eq!( expected, &format!("{}", type_check_helper(good_test).unwrap()) @@ -2056,8 +2056,7 @@ fn test_fetch_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); mem_type_check( @@ -2083,8 +2082,7 @@ fn test_fetch_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2104,8 +2102,7 @@ fn test_fetch_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2131,8 +2128,7 @@ fn test_insert_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-add (key int) (value int)) - ({}))", - case + ({case}))" ); mem_type_check( &contract_src, @@ -2158,8 +2154,7 @@ fn test_insert_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-add (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2182,8 +2177,7 @@ fn test_insert_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-add (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2209,8 +2203,7 @@ fn test_delete_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); mem_type_check( &contract_src, @@ -2234,8 +2227,7 @@ fn test_delete_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2255,8 +2247,7 @@ fn test_delete_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2284,8 +2275,7 @@ fn test_set_entry_matching_type_signatures() { (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-set (key int) (value int)) (let ((known-value 2)) - ({})))", - case + ({case})))" ); mem_type_check( &contract_src, @@ -2311,8 +2301,7 @@ fn test_set_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-set (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, @@ -2335,8 +2324,7 @@ fn test_set_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-set (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check( &contract_src, diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs index ab06802f27..8f766f8712 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/assets.rs @@ -215,14 +215,14 @@ fn test_bad_asset_usage() { ]; for (script, expected_err) in bad_scripts.iter().zip(expected.iter()) { - let tokens_contract = format!("{}\n{}", FIRST_CLASS_TOKENS, script); + let tokens_contract = format!("{FIRST_CLASS_TOKENS}\n{script}"); let actual_err = mem_run_analysis( &tokens_contract, ClarityVersion::Clarity2, StacksEpochId::latest(), ) .unwrap_err(); - println!("{}", script); + println!("{script}"); assert_eq!(&actual_err.err, expected_err); } } diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs index 838be9e6bb..c4c6da4219 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/contracts.rs @@ -433,7 +433,7 @@ fn test_names_tokens_contracts_interface() { "clarity_version": "Clarity3" }"#).unwrap(); - eprintln!("{}", test_contract_json_str); + eprintln!("{test_contract_json_str}"); assert_json_eq!(test_contract_json, test_contract_json_expected); } @@ -468,9 +468,8 @@ fn test_names_tokens_contracts_bad(#[case] version: ClarityVersion, #[case] epoc (err 1)))"; let names_contract = format!( - "{} - {}", - SIMPLE_NAMES, broken_public + "{SIMPLE_NAMES} + {broken_public}" ); let tokens_contract_id = QualifiedContractIdentifier::local("tokens").unwrap(); @@ -622,23 +621,23 @@ fn test_expects() { for unmatched_return_types in bad_return_types_tests.iter() { let err = mem_type_check(unmatched_return_types).unwrap_err(); - eprintln!("unmatched_return_types returned check error: {}", err); + eprintln!("unmatched_return_types returned check error: {err}"); assert!(matches!(err.err, CheckErrors::ReturnTypesMustMatch(_, _))); } let err = mem_type_check(bad_default_type).unwrap_err(); - eprintln!("bad_default_types returned check error: {}", err); + eprintln!("bad_default_types returned check error: {err}"); assert!(matches!(err.err, CheckErrors::DefaultTypesMustMatch(_, _))); let err = mem_type_check(notype_response_type).unwrap_err(); - eprintln!("notype_response_type returned check error: {}", err); + eprintln!("notype_response_type returned check error: {err}"); assert!(matches!( err.err, CheckErrors::CouldNotDetermineResponseErrType )); let err = mem_type_check(notype_response_type_2).unwrap_err(); - eprintln!("notype_response_type_2 returned check error: {}", err); + eprintln!("notype_response_type_2 returned check error: {err}"); assert!(matches!( err.err, CheckErrors::CouldNotDetermineResponseOkType @@ -1707,7 +1706,7 @@ fn test_traits_multi_contract(#[case] version: ClarityVersion) { assert_eq!(function.as_str(), "do-it"); } Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("{:?}", res), + res => panic!("{res:?}"), } } @@ -1720,9 +1719,8 @@ fn load_versioned( epoch: StacksEpochId, ) -> Result { let source = read_to_string(format!( - "{}/src/vm/analysis/type_checker/v2_1/tests/contracts/{}.clar", - env!("CARGO_MANIFEST_DIR"), - name + "{}/src/vm/analysis/type_checker/v2_1/tests/contracts/{name}.clar", + env!("CARGO_MANIFEST_DIR") )) .unwrap(); let contract_id = QualifiedContractIdentifier::local(name).unwrap(); @@ -1740,7 +1738,7 @@ fn call_versioned( version: ClarityVersion, epoch: StacksEpochId, ) -> Result { - let source = format!("(contract-call? .{} {} {})", contract, function, args); + let source = format!("(contract-call? .{contract} {function} {args})"); let contract_id = QualifiedContractIdentifier::transient(); let mut contract = parse(&contract_id, source.as_str(), version, epoch).map_err(|e| e.to_string())?; @@ -1759,7 +1757,7 @@ fn clarity_trait_experiments_impl(#[case] version: ClarityVersion, #[case] epoch }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -1774,7 +1772,7 @@ fn clarity_trait_experiments_use(#[case] version: ClarityVersion, #[case] epoch: }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -1790,7 +1788,7 @@ fn clarity_trait_experiments_empty_trait( let result = db.execute(|db| load_versioned(db, "empty-trait", version, epoch)); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -1809,7 +1807,7 @@ fn clarity_trait_experiments_duplicate_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -1875,7 +1873,7 @@ fn clarity_trait_experiments_out_of_order( let result = db.execute(|db| load_versioned(db, "out-of-order-traits", version, epoch)); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -1893,7 +1891,7 @@ fn clarity_trait_experiments_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -1914,7 +1912,7 @@ fn clarity_trait_experiments_impl_double_trait_both( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -1937,7 +1935,7 @@ fn clarity_trait_experiments_impl_double_trait_1( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -1958,7 +1956,7 @@ fn clarity_trait_experiments_impl_double_trait_2( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -1982,7 +1980,7 @@ fn clarity_trait_experiments_use_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2006,7 +2004,7 @@ fn clarity_trait_experiments_use_partial_double_trait_1( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2028,7 +2026,7 @@ fn clarity_trait_experiments_use_partial_double_trait_2( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2046,7 +2044,7 @@ fn clarity_trait_experiments_identical_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2067,7 +2065,7 @@ fn clarity_trait_experiments_impl_identical_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2125,7 +2123,7 @@ fn clarity_trait_experiments_use_math_trait_transitive_name( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("TraitReferenceUnknown(\"math-alias\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2147,7 +2145,7 @@ fn clarity_trait_experiments_use_original_and_define_a_trait( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TraitMethodUnknown(\"a\", \"do-it\")")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2169,7 +2167,7 @@ fn clarity_trait_experiments_use_redefined_and_define_a_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("TraitMethodUnknown(\"a\", \"do-that\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), } } @@ -2208,7 +2206,7 @@ fn clarity_trait_experiments_use_a_trait_transitive_redefined( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2230,7 +2228,7 @@ fn clarity_trait_experiments_nested_traits( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2263,7 +2261,7 @@ fn clarity_trait_experiments_call_nested_trait_1( assert!(err.starts_with("TypeError")) } Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2289,7 +2287,7 @@ fn clarity_trait_experiments_call_nested_trait_2( assert!(err.starts_with("TypeError")) } Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2315,7 +2313,7 @@ fn clarity_trait_experiments_call_nested_trait_3_ok( assert!(err.starts_with("TypeError")) } Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2338,7 +2336,7 @@ fn clarity_trait_experiments_call_nested_trait_3_err( }); match result { Ok(_) => (), - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2371,7 +2369,7 @@ fn clarity_trait_experiments_call_nested_trait_4( assert!(err.starts_with("TypeError")) } Ok(_) if version >= ClarityVersion::Clarity2 => (), - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2409,7 +2407,7 @@ fn clarity_trait_experiments_trait_literal( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2428,7 +2426,7 @@ fn clarity_trait_experiments_pass_let_rename_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2469,7 +2467,7 @@ fn clarity_trait_experiments_call_let_rename_trait( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TraitReferenceUnknown(\"new-math-contract\")")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2591,7 +2589,7 @@ fn clarity_trait_experiments_return_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2637,7 +2635,7 @@ fn clarity_trait_experiments_constant_call( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TraitReferenceUnknown(\"principal-value\")")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2663,7 +2661,7 @@ fn clarity_trait_experiments_constant_to_trait( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(CallableType(Trait(TraitIdentifier")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2690,7 +2688,7 @@ fn clarity_trait_experiments_constant_to_constant_call( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(CallableType(Trait(TraitIdentifier")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2712,7 +2710,7 @@ fn clarity_trait_experiments_downcast_literal_1( }) .unwrap_err(); if epoch <= StacksEpochId::Epoch2_05 { - println!("err: {}", err); + println!("err: {err}"); assert!(err.starts_with("TypeError(TraitReferenceType(TraitIdentifier { name: ClarityName(\"math\"), contract_identifier: QualifiedContractIdentifier { issuer: StandardPrincipalData(S1G2081040G2081040G2081040G208105NK8PE5), name: ContractName(\"math-trait\") } }), PrincipalType)")); } else { assert!(err.starts_with("TypeError(CallableType(Trait(TraitIdentifier { name: ClarityName(\"math\"), contract_identifier: QualifiedContractIdentifier { issuer: StandardPrincipalData(S1G2081040G2081040G2081040G208105NK8PE5), name: ContractName(\"math-trait\") } })), PrincipalType)")); @@ -2879,7 +2877,7 @@ fn clarity_trait_experiments_identical_trait_cast( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(CallableType(Trait(TraitIdentifier")) } - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2905,7 +2903,7 @@ fn clarity_trait_experiments_trait_cast( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(CallableType(Trait(TraitIdentifier")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -2954,7 +2952,7 @@ fn clarity_trait_experiments_renamed_trait_cast( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2973,7 +2971,7 @@ fn clarity_trait_experiments_readonly_use_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -2992,7 +2990,7 @@ fn clarity_trait_experiments_readonly_pass_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3032,7 +3030,7 @@ fn clarity_trait_experiments_readonly_static_call( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3079,7 +3077,7 @@ fn clarity_trait_experiments_dyn_call_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3152,7 +3150,7 @@ fn clarity_trait_experiments_call_use_principal( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3180,7 +3178,7 @@ fn clarity_trait_experiments_call_return_trait( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3211,7 +3209,7 @@ fn clarity_trait_experiments_call_full_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -3242,7 +3240,7 @@ fn clarity_trait_experiments_call_partial_double_trait( Err(err) if version >= ClarityVersion::Clarity2 => { assert!(err.starts_with("DefineTraitDuplicateMethod(\"foo\")")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -3270,7 +3268,7 @@ fn clarity_trait_experiments_trait_recursion( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3294,7 +3292,7 @@ fn clarity_trait_experiments_principals_list_to_traits_list( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(SequenceType(ListType")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -3314,7 +3312,7 @@ fn clarity_trait_experiments_traits_list_to_traits_list( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3340,7 +3338,7 @@ fn clarity_trait_experiments_mixed_list_to_traits_list( Err(err) if version == ClarityVersion::Clarity1 => { assert!(err.starts_with("TypeError(SequenceType(ListType")) } - res => panic!("got {:?}", res), + res => panic!("got {res:?}"), }; } @@ -3411,7 +3409,7 @@ fn clarity_trait_experiments_double_trait_method2_v1( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3482,7 +3480,7 @@ fn clarity_trait_experiments_double_trait_method2_v1_v2( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } @@ -3539,6 +3537,6 @@ fn clarity_trait_experiments_cross_epochs( }); match result { Ok(_) => (), - res => panic!("expected success, got {:?}", res), + res => panic!("expected success, got {res:?}"), }; } diff --git a/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs b/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs index 5ce27eabcb..bb3e86a6ec 100644 --- a/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs +++ b/clarity/src/vm/analysis/type_checker/v2_1/tests/mod.rs @@ -1864,7 +1864,7 @@ fn test_concat_append_supertypes() { ]; for (good_test, expected) in good.iter().zip(expected.iter()) { - eprintln!("{}", good_test); + eprintln!("{good_test}"); assert_eq!( expected, &format!("{}", type_check_helper(good_test).unwrap()) @@ -2769,8 +2769,7 @@ fn test_fetch_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); mem_type_check(&contract_src).unwrap(); @@ -2791,8 +2790,7 @@ fn test_fetch_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::TypeError(_, _))); @@ -2807,8 +2805,7 @@ fn test_fetch_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-get (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::UndefinedVariable(_))); @@ -2829,8 +2826,7 @@ fn test_insert_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-add (key int) (value int)) - ({}))", - case + ({case}))" ); mem_type_check(&contract_src).unwrap(); } @@ -2851,8 +2847,7 @@ fn test_insert_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-add (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::TypeError(_, _))); @@ -2870,8 +2865,7 @@ fn test_insert_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-add (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::UndefinedVariable(_))); @@ -2892,8 +2886,7 @@ fn test_delete_entry_matching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); mem_type_check(&contract_src).unwrap(); } @@ -2912,8 +2905,7 @@ fn test_delete_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::TypeError(_, _))); @@ -2928,8 +2920,7 @@ fn test_delete_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-del (key int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::UndefinedVariable(_))); @@ -2952,8 +2943,7 @@ fn test_set_entry_matching_type_signatures() { (define-private (compatible-tuple) (tuple (key 1))) (define-private (kv-set (key int) (value int)) (let ((known-value 2)) - ({})))", - case + ({case})))" ); mem_type_check(&contract_src).unwrap(); } @@ -2974,8 +2964,7 @@ fn test_set_entry_mismatching_type_signatures() { "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (incompatible-tuple) (tuple (k 1))) (define-private (kv-set (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::TypeError(_, _))); @@ -2993,8 +2982,7 @@ fn test_set_entry_unbound_variables() { let contract_src = format!( "(define-map kv-store {{ key: int }} {{ value: int }}) (define-private (kv-set (key int) (value int)) - ({}))", - case + ({case}))" ); let res = mem_type_check(&contract_src).unwrap_err(); assert!(matches!(res.err, CheckErrors::UndefinedVariable(_))); @@ -3636,7 +3624,7 @@ fn test_principal_admits() { for good_test in good.iter() { let res = mem_type_check(good_test); - println!("{:?}", res); + println!("{res:?}"); assert!(res.is_ok()); } @@ -3662,7 +3650,7 @@ fn test_principal_admits() { for bad_test in bad.iter() { let res = mem_type_check(bad_test); - println!("{:?}", res); + println!("{res:?}"); assert!(res.is_err()); } } diff --git a/clarity/src/vm/ast/errors.rs b/clarity/src/vm/ast/errors.rs index 278846fc50..aa60d75f5f 100644 --- a/clarity/src/vm/ast/errors.rs +++ b/clarity/src/vm/ast/errors.rs @@ -137,7 +137,7 @@ impl fmt::Display for ParseError { write!(f, "{:?}", self.err)?; if let Some(ref e) = self.pre_expressions { - write!(f, "\nNear:\n{:?}", e)?; + write!(f, "\nNear:\n{e:?}")?; } Ok(()) @@ -185,45 +185,43 @@ impl DiagnosableError for ParseErrors { match &self { ParseErrors::CostOverflow => "Used up cost budget during the parse".into(), ParseErrors::CostBalanceExceeded(bal, used) => format!( - "Used up cost budget during the parse: {} balance, {} used", - bal, used + "Used up cost budget during the parse: {bal} balance, {used} used" ), ParseErrors::MemoryBalanceExceeded(bal, used) => format!( - "Used up memory budget during the parse: {} balance, {} used", - bal, used + "Used up memory budget during the parse: {bal} balance, {used} used" ), ParseErrors::TooManyExpressions => "Too many expressions".into(), ParseErrors::FailedCapturingInput => "Failed to capture value from input".into(), ParseErrors::SeparatorExpected(found) => { - format!("Expected whitespace or a close parens. Found: '{}'", found) + format!("Expected whitespace or a close parens. Found: '{found}'") } ParseErrors::SeparatorExpectedAfterColon(found) => { - format!("Whitespace expected after colon (:), Found: '{}'", found) + format!("Whitespace expected after colon (:), Found: '{found}'") } ParseErrors::ProgramTooLarge => "Program too large to parse".into(), ParseErrors::IllegalContractName(contract_name) => { - format!("Illegal contract name: '{}'", contract_name) + format!("Illegal contract name: '{contract_name}'") } ParseErrors::IllegalVariableName(var_name) => { - format!("Illegal variable name: '{}'", var_name) + format!("Illegal variable name: '{var_name}'") } - ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{}'", value), + ParseErrors::UnknownQuotedValue(value) => format!("Unknown 'quoted value '{value}'"), ParseErrors::FailedParsingIntValue(value) => { - format!("Failed to parse int literal '{}'", value) + format!("Failed to parse int literal '{value}'") } ParseErrors::FailedParsingUIntValue(value) => { - format!("Failed to parse uint literal 'u{}'", value) + format!("Failed to parse uint literal 'u{value}'") } ParseErrors::FailedParsingHexValue(value, x) => { - format!("Invalid hex-string literal {}: {}", value, x) + format!("Invalid hex-string literal {value}: {x}") } ParseErrors::FailedParsingPrincipal(value) => { - format!("Invalid principal literal: {}", value) + format!("Invalid principal literal: {value}") } - ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {}", value), - ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {}", value), + ParseErrors::FailedParsingBuffer(value) => format!("Invalid buffer literal: {value}"), + ParseErrors::FailedParsingField(value) => format!("Invalid field literal: {value}"), ParseErrors::FailedParsingRemainder(remainder) => { - format!("Failed to lex input remainder: '{}'", remainder) + format!("Failed to lex input remainder: '{remainder}'") } ParseErrors::ClosingParenthesisUnexpected => { "Tried to close list which isn't open.".into() @@ -236,21 +234,20 @@ impl DiagnosableError for ParseErrors { ParseErrors::ColonSeparatorUnexpected => "Misplaced colon.".into(), ParseErrors::CommaSeparatorUnexpected => "Misplaced comma.".into(), ParseErrors::TupleColonExpected(i) => { - format!("Tuple literal construction expects a colon at index {}", i) + format!("Tuple literal construction expects a colon at index {i}") } ParseErrors::TupleCommaExpected(i) => { - format!("Tuple literal construction expects a comma at index {}", i) + format!("Tuple literal construction expects a comma at index {i}") } ParseErrors::TupleItemExpected(i) => format!( - "Tuple literal construction expects a key or value at index {}", - i + "Tuple literal construction expects a key or value at index {i}" ), ParseErrors::CircularReference(function_names) => format!( "detected interdependent functions ({})", function_names.join(", ") ), ParseErrors::NameAlreadyUsed(name) => { - format!("defining '{}' conflicts with previous value", name) + format!("defining '{name}' conflicts with previous value") } ParseErrors::ImportTraitBadSignature => { "(use-trait ...) expects a trait name and a trait identifier".into() @@ -263,43 +260,41 @@ impl DiagnosableError for ParseErrors { } ParseErrors::TraitReferenceNotAllowed => "trait references can not be stored".into(), ParseErrors::TraitReferenceUnknown(trait_name) => { - format!("use of undeclared trait <{}>", trait_name) + format!("use of undeclared trait <{trait_name}>") } ParseErrors::ExpressionStackDepthTooDeep => format!( - "AST has too deep of an expression nesting. The maximum stack depth is {}", - MAX_CALL_STACK_DEPTH + "AST has too deep of an expression nesting. The maximum stack depth is {MAX_CALL_STACK_DEPTH}" ), ParseErrors::VaryExpressionStackDepthTooDeep => format!( - "AST has too deep of an expression nesting. The maximum stack depth is {}", - MAX_CALL_STACK_DEPTH + "AST has too deep of an expression nesting. The maximum stack depth is {MAX_CALL_STACK_DEPTH}" ), ParseErrors::InvalidCharactersDetected => "invalid characters detected".into(), ParseErrors::InvalidEscaping => "invalid escaping detected in string".into(), - ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {}", s), + ParseErrors::CostComputationFailed(s) => format!("Cost computation failed: {s}"), // Parser v2 errors ParseErrors::Lexer(le) => le.message(), ParseErrors::ContractNameTooLong(name) => { - format!("contract name '{}' is too long", name) + format!("contract name '{name}' is too long") } ParseErrors::ExpectedContractIdentifier => "expected contract identifier".into(), ParseErrors::ExpectedTraitIdentifier => "expected trait identifier".into(), - ParseErrors::IllegalTraitName(name) => format!("illegal trait name, '{}'", name), + ParseErrors::IllegalTraitName(name) => format!("illegal trait name, '{name}'"), ParseErrors::InvalidPrincipalLiteral => "invalid principal literal".into(), ParseErrors::InvalidBuffer => "invalid hex-string literal".into(), - ParseErrors::NameTooLong(name) => format!("illegal name (too long), '{}'", name), - ParseErrors::UnexpectedToken(token) => format!("unexpected '{}'", token), - ParseErrors::ExpectedClosing(token) => format!("expected closing '{}'", token), + ParseErrors::NameTooLong(name) => format!("illegal name (too long), '{name}'"), + ParseErrors::UnexpectedToken(token) => format!("unexpected '{token}'"), + ParseErrors::ExpectedClosing(token) => format!("expected closing '{token}'"), ParseErrors::TupleColonExpectedv2 => "expected ':' after key in tuple".into(), ParseErrors::TupleCommaExpectedv2 => { "expected ',' separating key-value pairs in tuple".into() } ParseErrors::TupleValueExpected => "expected value expression for tuple".into(), - ParseErrors::IllegalClarityName(name) => format!("illegal clarity name, '{}'", name), - ParseErrors::IllegalASCIIString(s) => format!("illegal ascii string \"{}\"", s), - ParseErrors::IllegalUtf8String(s) => format!("illegal UTF8 string \"{}\"", s), + ParseErrors::IllegalClarityName(name) => format!("illegal clarity name, '{name}'"), + ParseErrors::IllegalASCIIString(s) => format!("illegal ascii string \"{s}\""), + ParseErrors::IllegalUtf8String(s) => format!("illegal UTF8 string \"{s}\""), ParseErrors::ExpectedWhitespace => "expected whitespace before expression".into(), - ParseErrors::NoteToMatchThis(token) => format!("to match this '{}'", token), + ParseErrors::NoteToMatchThis(token) => format!("to match this '{token}'"), ParseErrors::UnexpectedParserFailure => "unexpected failure while parsing".to_string(), ParseErrors::InterpreterFailure => "unexpected failure while parsing".to_string(), ParseErrors::ExecutionTimeExpired => "max execution time expired".to_string(), diff --git a/clarity/src/vm/ast/mod.rs b/clarity/src/vm/ast/mod.rs index 263fc86526..50b2788147 100644 --- a/clarity/src/vm/ast/mod.rs +++ b/clarity/src/vm/ast/mod.rs @@ -206,7 +206,7 @@ fn inner_build_ast( 0, Diagnostic { level: Level::Error, - message: format!("runtime_cost error: {:?}", e), + message: format!("runtime_cost error: {e:?}"), spans: vec![], suggestion: None, }, diff --git a/clarity/src/vm/ast/parser/v1.rs b/clarity/src/vm/ast/parser/v1.rs index 32f0b7001e..d767e5c092 100644 --- a/clarity/src/vm/ast/parser/v1.rs +++ b/clarity/src/vm/ast/parser/v1.rs @@ -89,7 +89,7 @@ impl LexMatcher { fn new(regex_str: &str, handles: TokenType) -> LexMatcher { #[allow(clippy::unwrap_used)] LexMatcher { - matcher: Regex::new(&format!("^{}", regex_str)).unwrap(), + matcher: Regex::new(&format!("^{regex_str}")).unwrap(), handler: handles, } } @@ -125,7 +125,7 @@ lazy_static! { *STANDARD_PRINCIPAL_REGEX, *CONTRACT_PRINCIPAL_REGEX ); pub static ref CLARITY_NAME_REGEX: String = - format!(r#"([[:word:]]|[-!?+<>=/*]){{1,{}}}"#, MAX_STRING_LEN); + format!(r#"([[:word:]]|[-!?+<>=/*]){{1,{MAX_STRING_LEN}}}"#); static ref lex_matchers: Vec = vec![ LexMatcher::new( @@ -154,15 +154,15 @@ lazy_static! { LexMatcher::new("(?P-?[[:digit:]]+)", TokenType::IntLiteral), LexMatcher::new( &format!( - r#"'(?P{}(\.)([[:alnum:]]|[-]){{1,{}}})"#, - *CONTRACT_PRINCIPAL_REGEX, MAX_STRING_LEN + r#"'(?P{}(\.)([[:alnum:]]|[-]){{1,{MAX_STRING_LEN}}})"#, + *CONTRACT_PRINCIPAL_REGEX ), TokenType::FullyQualifiedFieldIdentifierLiteral, ), LexMatcher::new( &format!( - r#"(?P(\.){}(\.)([[:alnum:]]|[-]){{1,{}}})"#, - *CONTRACT_NAME_REGEX, MAX_STRING_LEN + r#"(?P(\.){}(\.)([[:alnum:]]|[-]){{1,{MAX_STRING_LEN}}})"#, + *CONTRACT_NAME_REGEX ), TokenType::SugaredFieldIdentifierLiteral, ), @@ -551,10 +551,7 @@ pub fn parse_lexed(input: Vec<(LexItem, u32, u32)>) -> ParseResult) -> ParseResult) -> ParseResult String { use self::LexerError::*; match self { - InvalidCharInt(c) => format!("invalid character, '{}', in int literal", c), - InvalidCharUint(c) => format!("invalid character, '{}', in uint literal", c), - InvalidCharBuffer(c) => format!("invalid character, '{}', in buffer", c), - InvalidCharIdent(c) => format!("invalid character, '{}', in identifier", c), - InvalidCharTraitIdent(c) => format!("invalid character, '{}', in trait identifier", c), - InvalidCharPrincipal(c) => format!("invalid character, '{}', in principal literal", c), - IllegalCharString(c) => format!("invalid character, '{}', in string literal", c), - IllegalCharUTF8Encoding(c) => format!("invalid character, '{}', in UTF8 encoding", c), + InvalidCharInt(c) => format!("invalid character, '{c}', in int literal"), + InvalidCharUint(c) => format!("invalid character, '{c}', in uint literal"), + InvalidCharBuffer(c) => format!("invalid character, '{c}', in buffer"), + InvalidCharIdent(c) => format!("invalid character, '{c}', in identifier"), + InvalidCharTraitIdent(c) => format!("invalid character, '{c}', in trait identifier"), + InvalidCharPrincipal(c) => format!("invalid character, '{c}', in principal literal"), + IllegalCharString(c) => format!("invalid character, '{c}', in string literal"), + IllegalCharUTF8Encoding(c) => format!("invalid character, '{c}', in UTF8 encoding"), InvalidUTF8Encoding => "invalid UTF8 encoding".to_string(), EmptyUTF8Encoding => "empty UTF8 encoding".to_string(), UnterminatedUTF8Encoding => "unterminated UTF8 encoding, missing '}'".to_string(), - InvalidBufferLength(size) => format!("invalid buffer length, {}", size), - UnknownEscapeChar(c) => format!("unknown escape character, '{}'", c), - ExpectedClosing(c) => format!("expected closing '{}'", c), + InvalidBufferLength(size) => format!("invalid buffer length, {size}"), + UnknownEscapeChar(c) => format!("unknown escape character, '{c}'"), + ExpectedClosing(c) => format!("expected closing '{c}'"), ExpectedSeparator => "expected separator".to_string(), SingleSemiColon => "unexpected single ';' (comments begin with \";;\"".to_string(), - UnknownSymbol(c) => format!("unknown symbol, '{}'", c), - NonASCIIChar(c) => format!("illegal non-ASCII character, '{}'", c), - NoteToMatchThis(c) => format!("to match this '{}'", c), + UnknownSymbol(c) => format!("unknown symbol, '{c}'"), + NonASCIIChar(c) => format!("illegal non-ASCII character, '{c}'"), + NoteToMatchThis(c) => format!("to match this '{c}'"), UnsupportedLineEnding => { "unsupported line-ending '\\r', only '\\n' is supported".to_string() } diff --git a/clarity/src/vm/ast/parser/v2/lexer/mod.rs b/clarity/src/vm/ast/parser/v2/lexer/mod.rs index bbd6136916..1a196b8923 100644 --- a/clarity/src/vm/ast/parser/v2/lexer/mod.rs +++ b/clarity/src/vm/ast/parser/v2/lexer/mod.rs @@ -255,7 +255,7 @@ impl<'a> Lexer<'a> { _ => { if !is_separator(self.next) { return Ok(Token::Placeholder(self.proceed_through_error( - format!("<{}", ident), + format!("<{ident}"), Some(LexerError::InvalidCharTraitIdent(self.next)), )?)); } @@ -278,7 +278,7 @@ impl<'a> Lexer<'a> { end_column: start_column, }, )?; - return Ok(Token::Placeholder(format!("<{}", ident))); + return Ok(Token::Placeholder(format!("<{ident}"))); } } self.read_char()?; @@ -298,7 +298,7 @@ impl<'a> Lexer<'a> { _ => { if !is_separator(self.next) { return Ok(Token::Placeholder(self.proceed_through_error( - format!("'{}", principal), + format!("'{principal}"), Some(LexerError::InvalidCharPrincipal(self.next)), )?)); } @@ -316,7 +316,7 @@ impl<'a> Lexer<'a> { } if !is_separator(self.next) { return Ok(Token::Placeholder(self.proceed_through_error( - format!("u{}", num), + format!("u{num}"), Some(LexerError::InvalidCharUint(self.next)), )?)); } @@ -353,7 +353,7 @@ impl<'a> Lexer<'a> { if !f.is_ascii_hexdigit() { if !is_separator(f) { return Ok(Token::Placeholder(self.proceed_through_error( - format!("0x{}", bytes), + format!("0x{bytes}"), Some(LexerError::InvalidCharBuffer(f)), )?)); } @@ -374,10 +374,10 @@ impl<'a> Lexer<'a> { end_column: self.last_column as u32, }, )?; - return Ok(Token::Placeholder(format!("0x{}", bytes))); + return Ok(Token::Placeholder(format!("0x{bytes}"))); } else { return Ok(Token::Placeholder(self.proceed_through_error( - format!("0x{}", bytes), + format!("0x{bytes}"), Some(LexerError::InvalidCharBuffer(s)), )?)); } @@ -412,7 +412,7 @@ impl<'a> Lexer<'a> { }, )?; return Ok(Token::Placeholder( - self.proceed_through_error_string(format!("\"{}\\", s), None)?, + self.proceed_through_error_string(format!("\"{s}\\"), None)?, )); } }; @@ -444,7 +444,7 @@ impl<'a> Lexer<'a> { end_column: start_column, }, )?; - return Ok(Token::Placeholder(format!("\"{}", s))); + return Ok(Token::Placeholder(format!("\"{s}"))); } _ => { if !self.next.is_ascii() { @@ -458,7 +458,7 @@ impl<'a> Lexer<'a> { }, )?; return Ok(Token::Placeholder( - self.proceed_through_error_string(format!("\"{}", s), None)?, + self.proceed_through_error_string(format!("\"{s}"), None)?, )); } else { s.push(self.next); @@ -529,7 +529,7 @@ impl<'a> Lexer<'a> { end_column: start_column, }, )?; - return Ok(Err(format!("{{{}", code))); + return Ok(Err(format!("{{{code}"))); } EOF => { self.add_diagnostic( @@ -550,7 +550,7 @@ impl<'a> Lexer<'a> { end_column: start_column, }, )?; - return Ok(Err(format!("{{{}", code))); + return Ok(Err(format!("{{{code}"))); } _ => { if self.next.is_ascii_hexdigit() { @@ -565,7 +565,7 @@ impl<'a> Lexer<'a> { end_column: self.column as u32, }, )?; - return Ok(Err(format!("{{{}", code))); + return Ok(Err(format!("{{{code}"))); } } } @@ -595,7 +595,7 @@ impl<'a> Lexer<'a> { Ok(code) => code, Err(bad) => { return Ok(Token::Placeholder(self.proceed_through_error_string( - format!("u\"{}\\u{}", s, bad), + format!("u\"{s}\\u{bad}"), None, )?)); } @@ -615,7 +615,7 @@ impl<'a> Lexer<'a> { )?; return Ok(Token::Placeholder( self.proceed_through_error_string( - format!("u\"{}\\u{{{}}}", s, encode_str), + format!("u\"{s}\\u{{{encode_str}}}"), None, )?, )); @@ -635,7 +635,7 @@ impl<'a> Lexer<'a> { )?; return Ok(Token::Placeholder( self.proceed_through_error_string( - format!("u\"{}\\u{{{}}}", s, encode_str), + format!("u\"{s}\\u{{{encode_str}}}"), None, )?, )); @@ -656,7 +656,7 @@ impl<'a> Lexer<'a> { }, )?; return Ok(Token::Placeholder( - self.proceed_through_error_string(format!("u\"{}\\", s), None)?, + self.proceed_through_error_string(format!("u\"{s}\\"), None)?, )); } }; @@ -688,7 +688,7 @@ impl<'a> Lexer<'a> { end_column: start_column + 1, }, )?; - return Ok(Token::Placeholder(format!("u\"{}", s))); + return Ok(Token::Placeholder(format!("u\"{s}"))); } _ => { s.push(self.next); diff --git a/clarity/src/vm/ast/parser/v2/lexer/token.rs b/clarity/src/vm/ast/parser/v2/lexer/token.rs index 606f13aebd..2c1ccd401f 100644 --- a/clarity/src/vm/ast/parser/v2/lexer/token.rs +++ b/clarity/src/vm/ast/parser/v2/lexer/token.rs @@ -88,13 +88,13 @@ impl Token { Comma => ",".to_string(), Dot => ".".to_string(), Int(s) => s.to_string(), - Uint(s) => format!("u{}", s), - AsciiString(s) => format!("\"{}\"", s), + Uint(s) => format!("u{s}"), + AsciiString(s) => format!("\"{s}\""), Utf8String(s) => s.to_string(), - Bytes(s) => format!("0x{}", s), - Principal(s) => format!("'{}", s), + Bytes(s) => format!("0x{s}"), + Principal(s) => format!("'{s}"), Ident(s) => s.to_string(), - TraitIdent(s) => format!("<{}>", s), + TraitIdent(s) => format!("<{s}>"), Plus => "+".to_string(), Minus => "-".to_string(), Multiply => "*".to_string(), @@ -103,7 +103,7 @@ impl Token { LessEqual => "<=".to_string(), Greater => ">".to_string(), GreaterEqual => ">=".to_string(), - Comment(c) => format!(";; {}", c), + Comment(c) => format!(";; {c}"), Placeholder(s) => s.to_string(), } } diff --git a/clarity/src/vm/ast/parser/v2/mod.rs b/clarity/src/vm/ast/parser/v2/mod.rs index dd5a900364..ad0caf29d4 100644 --- a/clarity/src/vm/ast/parser/v2/mod.rs +++ b/clarity/src/vm/ast/parser/v2/mod.rs @@ -514,7 +514,7 @@ impl<'a> Parser<'a> { Ok(principal) => principal, _ => { self.add_diagnostic(ParseErrors::InvalidPrincipalLiteral, span.clone())?; - let mut placeholder = PreSymbolicExpression::placeholder(format!("'{}", addr)); + let mut placeholder = PreSymbolicExpression::placeholder(format!("'{addr}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -541,8 +541,7 @@ impl<'a> Parser<'a> { span.end_column = token_span.end_column; self.add_diagnostic(ParseErrors::ExpectedContractIdentifier, token_span)?; let mut placeholder = PreSymbolicExpression::placeholder(format!( - "'{}.{}", - principal, + "'{principal}.{}", token.reproduce() )); placeholder.copy_span(&span); @@ -551,7 +550,7 @@ impl<'a> Parser<'a> { None => { self.add_diagnostic(ParseErrors::ExpectedContractIdentifier, dot.span)?; let mut placeholder = - PreSymbolicExpression::placeholder(format!("'{}.", principal)); + PreSymbolicExpression::placeholder(format!("'{principal}.")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -563,7 +562,7 @@ impl<'a> Parser<'a> { contract_span, )?; let mut placeholder = - PreSymbolicExpression::placeholder(format!("'{}.{}", principal, name)); + PreSymbolicExpression::placeholder(format!("'{principal}.{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -575,7 +574,7 @@ impl<'a> Parser<'a> { contract_span, )?; let mut placeholder = - PreSymbolicExpression::placeholder(format!("'{}.{}", principal, name)); + PreSymbolicExpression::placeholder(format!("'{principal}.{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -604,8 +603,7 @@ impl<'a> Parser<'a> { token_span.clone(), )?; let mut placeholder = PreSymbolicExpression::placeholder(format!( - "'{}.{}", - contract_id, + "'{contract_id}.{}", token.reproduce(), )); span.end_line = token_span.end_line; @@ -619,7 +617,7 @@ impl<'a> Parser<'a> { dot.span.clone(), )?; let mut placeholder = - PreSymbolicExpression::placeholder(format!("'{}.", contract_id)); + PreSymbolicExpression::placeholder(format!("'{contract_id}.")); span.end_line = dot.span.end_line; span.end_column = dot.span.end_column; placeholder.copy_span(&span); @@ -629,7 +627,7 @@ impl<'a> Parser<'a> { if name.len() > MAX_STRING_LEN { self.add_diagnostic(ParseErrors::NameTooLong(name.clone()), trait_span)?; let mut placeholder = - PreSymbolicExpression::placeholder(format!("'{}.{}", contract_id, name,)); + PreSymbolicExpression::placeholder(format!("'{contract_id}.{name}",)); placeholder.copy_span(&span); return Ok(placeholder); } @@ -640,10 +638,8 @@ impl<'a> Parser<'a> { ParseErrors::IllegalTraitName(name.clone()), trait_span, )?; - let mut placeholder = PreSymbolicExpression::placeholder(format!( - "'{}.{}", - contract_id, name, - )); + let mut placeholder = + PreSymbolicExpression::placeholder(format!("'{contract_id}.{name}",)); placeholder.copy_span(&span); return Ok(placeholder); } @@ -703,7 +699,7 @@ impl<'a> Parser<'a> { if name.len() > MAX_CONTRACT_NAME_LEN { self.add_diagnostic(ParseErrors::ContractNameTooLong(name.clone()), span.clone())?; - let mut placeholder = PreSymbolicExpression::placeholder(format!(".{}", name)); + let mut placeholder = PreSymbolicExpression::placeholder(format!(".{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -715,7 +711,7 @@ impl<'a> Parser<'a> { ParseErrors::IllegalContractName(name.clone()), contract_span, )?; - let mut placeholder = PreSymbolicExpression::placeholder(format!(".{}", name)); + let mut placeholder = PreSymbolicExpression::placeholder(format!(".{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -740,8 +736,7 @@ impl<'a> Parser<'a> { }) => { self.add_diagnostic(ParseErrors::ExpectedTraitIdentifier, token_span.clone())?; let mut placeholder = PreSymbolicExpression::placeholder(format!( - ".{}.{}", - contract_name, + ".{contract_name}.{}", token.reproduce(), )); span.end_line = token_span.end_line; @@ -752,7 +747,7 @@ impl<'a> Parser<'a> { None => { self.add_diagnostic(ParseErrors::ExpectedTraitIdentifier, dot.span.clone())?; let mut placeholder = - PreSymbolicExpression::placeholder(format!(".{}.", contract_name)); + PreSymbolicExpression::placeholder(format!(".{contract_name}.")); span.end_line = dot.span.end_line; span.end_column = dot.span.end_column; placeholder.copy_span(&span); @@ -762,7 +757,7 @@ impl<'a> Parser<'a> { if name.len() > MAX_STRING_LEN { self.add_diagnostic(ParseErrors::NameTooLong(name.clone()), trait_span)?; let mut placeholder = - PreSymbolicExpression::placeholder(format!(".{}.{}", contract_name, name)); + PreSymbolicExpression::placeholder(format!(".{contract_name}.{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -771,7 +766,7 @@ impl<'a> Parser<'a> { Err(_) => { self.add_diagnostic(ParseErrors::IllegalTraitName(name.clone()), trait_span)?; let mut placeholder = - PreSymbolicExpression::placeholder(format!(".{}.{}", contract_name, name)); + PreSymbolicExpression::placeholder(format!(".{contract_name}.{name}")); placeholder.copy_span(&span); return Ok(placeholder); } @@ -1428,7 +1423,7 @@ mod tests { assert!(diagnostics.is_empty()); if let Some(v) = stmts[0].match_atom_value() { let s = match v { - Value::Sequence(SequenceData::String(CharType::UTF8(data))) => format!("{}", data), + Value::Sequence(SequenceData::String(CharType::UTF8(data))) => format!("{data}"), _ => panic!("failed to parse UTF8 string "), }; assert_eq!(s, "u\"new\\nline\\u{f09f9881}\""); @@ -2915,7 +2910,7 @@ mod tests { match &stmts[0].pre_expr { PreSymbolicExpressionType::FieldIdentifier(trait_id) => { assert_eq!( - format!("{}", trait_id), + format!("{trait_id}"), "ST000000000000000000002AMW42H.foo.bar" ); } @@ -3566,7 +3561,7 @@ mod tests { assert!(match parse(&exceeds_stack_depth_list).unwrap_err().err { ParseErrors::ExpressionStackDepthTooDeep => true, - x => panic!("expected a stack depth too deep error, got {:?}", x), + x => panic!("expected a stack depth too deep error, got {x:?}"), }); let (stmts, diagnostics, success) = parse_collect_diagnostics(&exceeds_stack_depth_list); @@ -3589,7 +3584,7 @@ mod tests { assert!(match parse(&exceeds_stack_depth_tuple).unwrap_err().err { ParseErrors::ExpressionStackDepthTooDeep => true, - x => panic!("expected a stack depth too deep error, got {:?}", x), + x => panic!("expected a stack depth too deep error, got {x:?}"), }); let (stmts, diagnostics, success) = parse_collect_diagnostics(&exceeds_stack_depth_tuple); diff --git a/clarity/src/vm/callables.rs b/clarity/src/vm/callables.rs index 0eaf29c1fc..ccf7b9af28 100644 --- a/clarity/src/vm/callables.rs +++ b/clarity/src/vm/callables.rs @@ -395,12 +395,12 @@ impl CallableType { impl FunctionIdentifier { fn new_native_function(name: &str) -> FunctionIdentifier { - let identifier = format!("_native_:{}", name); + let identifier = format!("_native_:{name}"); FunctionIdentifier { identifier } } fn new_user_function(name: &str, context: &str) -> FunctionIdentifier { - let identifier = format!("{}:{}", context, name); + let identifier = format!("{context}:{name}"); FunctionIdentifier { identifier } } } @@ -556,7 +556,7 @@ mod test { assert_eq!(contract_id, &contract_identifier); assert_eq!(trait_id.as_ref().unwrap(), &trait_identifier); } - other => panic!("expected Value::CallableContract, got {:?}", other), + other => panic!("expected Value::CallableContract, got {other:?}"), } // (ok principal) -> (ok ) @@ -713,7 +713,7 @@ mod test { assert_eq!(contract_id, &contract_identifier); assert_eq!(trait_id.as_ref().unwrap(), &trait_identifier); } - other => panic!("expected Value::CallableContract, got {:?}", other), + other => panic!("expected Value::CallableContract, got {other:?}"), } } diff --git a/clarity/src/vm/contexts.rs b/clarity/src/vm/contexts.rs index 3b98c4b828..20b9752e6f 100644 --- a/clarity/src/vm/contexts.rs +++ b/clarity/src/vm/contexts.rs @@ -102,8 +102,8 @@ impl AssetMap { .iter() .map(|(principal, amount)| { ( - format!("{}", principal), - serde_json::value::Value::String(format!("{}", amount)), + format!("{principal}"), + serde_json::value::Value::String(format!("{amount}")), ) }) .collect(); @@ -113,8 +113,8 @@ impl AssetMap { .iter() .map(|(principal, amount)| { ( - format!("{}", principal), - serde_json::value::Value::String(format!("{}", amount)), + format!("{principal}"), + serde_json::value::Value::String(format!("{amount}")), ) }) .collect(); @@ -127,14 +127,14 @@ impl AssetMap { .iter() .map(|(asset_id, amount)| { ( - format!("{}", asset_id), - serde_json::value::Value::String(format!("{}", amount)), + format!("{asset_id}"), + serde_json::value::Value::String(format!("{amount}")), ) }) .collect(); ( - format!("{}", principal), + format!("{principal}"), serde_json::value::Value::Object(token_json), ) }) @@ -150,19 +150,19 @@ impl AssetMap { let nft_array = nft_values .iter() .map(|nft_value| { - serde_json::value::Value::String(format!("{}", nft_value)) + serde_json::value::Value::String(format!("{nft_value}")) }) .collect(); ( - format!("{}", asset_id), + format!("{asset_id}"), serde_json::value::Value::Array(nft_array), ) }) .collect(); ( - format!("{}", principal), + format!("{principal}"), serde_json::value::Value::Object(nft_json), ) }) @@ -521,10 +521,7 @@ impl<'a, 'hooks> OwnedEnvironment<'a, 'hooks> { let version = ClarityVersion::default_for_epoch(epoch); database.roll_back().unwrap(); - debug!( - "Begin OwnedEnvironment(epoch = {}, version = {})", - &epoch, &version - ); + debug!("Begin OwnedEnvironment(epoch = {epoch}, version = {version})"); OwnedEnvironment { context: GlobalContext::new( false, @@ -1130,8 +1127,7 @@ impl<'a, 'b, 'hooks> Environment<'a, 'b, 'hooks> { let args: Result> = args.iter() .map(|arg| { let value = arg.match_atom_value() - .ok_or_else(|| InterpreterError::InterpreterError(format!("Passed non-value expression to exec_tx on {}!", - tx_name)))?; + .ok_or_else(|| InterpreterError::InterpreterError(format!("Passed non-value expression to exec_tx on {tx_name}!")))?; // sanitize contract-call inputs in epochs >= 2.4 // testing todo: ensure sanitize_value() preserves trait callability! let expected_type = TypeSignature::type_of(value)?; diff --git a/clarity/src/vm/coverage.rs b/clarity/src/vm/coverage.rs index 4e0d64e62b..7370d78077 100644 --- a/clarity/src/vm/coverage.rs +++ b/clarity/src/vm/coverage.rs @@ -93,9 +93,8 @@ impl CoverageReporter { let out = CoverageFileInfo { coverage }; if let Err(e) = serde_json::to_writer(f, &out) { error!( - "Failed to serialize JSON to coverage file {}: {}", - filename.as_ref().display(), - e + "Failed to serialize JSON to coverage file {}: {e}", + filename.as_ref().display() ); return Err(e.into()); } @@ -182,9 +181,8 @@ impl CoverageReporter { if let Err(e) = serde_json::to_writer(f, &json) { error!( - "Failed to serialize JSON to coverage file {}: {}", - filename.as_ref().display(), - e + "Failed to serialize JSON to coverage file {}: {e}", + filename.as_ref().display() ); return Err(e.into()); } @@ -219,7 +217,7 @@ impl CoverageReporter { writeln!(out, "SF:{}", &info.src_file)?; for line in info.executable_lines.iter() { let count = summed_coverage.get(line).cloned().unwrap_or(0); - writeln!(out, "DA:{},{}", line, count)?; + writeln!(out, "DA:{line},{count}")?; } writeln!(out, "LH:{}", summed_coverage.len())?; writeln!(out, "LF:{}", &info.executable_lines.len())?; diff --git a/clarity/src/vm/database/clarity_db.rs b/clarity/src/vm/database/clarity_db.rs index 38101197f2..55b15ab75a 100644 --- a/clarity/src/vm/database/clarity_db.rs +++ b/clarity/src/vm/database/clarity_db.rs @@ -602,11 +602,11 @@ impl<'a> ClarityDatabase<'a> { data: StoreType, var_name: &str, ) -> String { - format!("vm::{}::{}::{}", contract_identifier, data as u8, var_name) + format!("vm::{contract_identifier}::{}::{var_name}", data as u8) } pub fn make_metadata_key(data: StoreType, var_name: &str) -> String { - format!("vm-metadata::{}::{}", data as u8, var_name) + format!("vm-metadata::{}::{var_name}", data as u8) } fn clarity_state_epoch_key() -> &'static str { @@ -620,8 +620,8 @@ impl<'a> ClarityDatabase<'a> { key_value: &str, ) -> String { format!( - "vm::{}::{}::{}::{}", - contract_identifier, data as u8, var_name, key_value + "vm::{contract_identifier}::{}::{var_name}::{key_value}", + data as u8 ) } @@ -699,8 +699,7 @@ impl<'a> ClarityDatabase<'a> { ) -> Result<()> { if self.store.has_metadata_entry(contract_identifier, key) { Err(InterpreterError::Expect(format!( - "Metadata entry '{}' already exists for contract: {}", - key, contract_identifier + "Metadata entry '{key}' already exists for contract: {contract_identifier}" )) .into()) } else { @@ -1086,8 +1085,7 @@ impl ClarityDatabase<'_> { self.get_burnchain_block_height(&last_mined_bhh) .ok_or_else(|| { InterpreterError::Expect(format!( - "Block header hash '{}' must return for provided stacks block height {}", - &last_mined_bhh, cur_stacks_height + "Block header hash '{last_mined_bhh}' must return for provided stacks block height {cur_stacks_height}" )) .into() }) @@ -1177,8 +1175,7 @@ impl ClarityDatabase<'_> { .get_consensus_hash_for_block(&parent_id_bhh, &epoch) .ok_or_else(|| { InterpreterError::Expect(format!( - "FATAL: no consensus hash found for StacksBlockId {}", - &parent_id_bhh + "FATAL: no consensus hash found for StacksBlockId {parent_id_bhh}" )) })?; @@ -1188,8 +1185,7 @@ impl ClarityDatabase<'_> { .get_sortition_id_from_consensus_hash(&consensus_hash) .ok_or_else(|| { InterpreterError::Expect(format!( - "FATAL: no SortitionID found for consensus hash {}", - &consensus_hash + "FATAL: no SortitionID found for consensus hash {consensus_hash}" )) })?; @@ -1330,11 +1326,11 @@ impl ClarityDatabase<'_> { impl ClarityDatabase<'_> { pub fn make_microblock_pubkey_height_key(pubkey_hash: &Hash160) -> String { - format!("microblock-pubkey-hash::{}", pubkey_hash) + format!("microblock-pubkey-hash::{pubkey_hash}") } pub fn make_microblock_poison_key(height: u32) -> String { - format!("microblock-poison::{}", height) + format!("microblock-poison::{height}") } pub fn insert_microblock_pubkey_hash_height( @@ -1343,7 +1339,7 @@ impl ClarityDatabase<'_> { height: u32, ) -> Result<()> { let key = ClarityDatabase::make_microblock_pubkey_height_key(pubkey_hash); - let value = format!("{}", &height); + let value = format!("{height}"); self.put_data(&key, &value) } @@ -2215,7 +2211,7 @@ impl ClarityDatabase<'_> { // load/store STX token state and account nonces impl<'a> ClarityDatabase<'a> { fn make_key_for_account(principal: &PrincipalData, data: StoreType) -> String { - format!("vm-account::{}::{}", principal, data as u8) + format!("vm-account::{principal}::{}", data as u8) } pub fn make_key_for_account_balance(principal: &PrincipalData) -> String { @@ -2241,12 +2237,10 @@ impl<'a> ClarityDatabase<'a> { let stx_balance = self.get_account_stx_balance(principal)?; let cur_burn_height = u64::from(self.get_current_burnchain_block_height()?); - test_debug!("Balance of {} (raw={},locked={},unlock-height={},current-height={}) is {} (has_unlockable_tokens_at_burn_block={})", - principal, + test_debug!("Balance of {principal} (raw={},locked={},unlock-height={},current-height={cur_burn_height}) is {} (has_unlockable_tokens_at_burn_block={})", stx_balance.amount_unlocked(), stx_balance.amount_locked(), stx_balance.unlock_height(), - cur_burn_height, stx_balance.get_available_balance_at_burn_block(cur_burn_height, self.get_v1_unlock_height(), self.get_v2_unlock_height()?, self.get_v3_unlock_height()?)?, stx_balance.has_unlockable_tokens_at_burn_block(cur_burn_height, self.get_v1_unlock_height(), self.get_v2_unlock_height()?, self.get_v3_unlock_height()?)); @@ -2265,12 +2259,10 @@ impl<'a> ClarityDatabase<'a> { let stx_balance = self.get_account_stx_balance(principal)?; let cur_burn_height = 0; - test_debug!("Balance of {} (raw={},locked={},unlock-height={},current-height={}) is {} (has_unlockable_tokens_at_burn_block={})", - principal, + test_debug!("Balance of {principal} (raw={},locked={},unlock-height={},current-height={cur_burn_height}) is {} (has_unlockable_tokens_at_burn_block={})", stx_balance.amount_unlocked(), stx_balance.amount_locked(), stx_balance.unlock_height(), - cur_burn_height, stx_balance.get_available_balance_at_burn_block(cur_burn_height, self.get_v1_unlock_height(), self.get_v2_unlock_height()?, self.get_v3_unlock_height()?)?, stx_balance.has_unlockable_tokens_at_burn_block(cur_burn_height, self.get_v1_unlock_height(), self.get_v2_unlock_height()?, self.get_v3_unlock_height()?)); @@ -2316,8 +2308,7 @@ impl ClarityDatabase<'_> { pub fn get_stacks_epoch_for_block(&self, id_bhh: &StacksBlockId) -> Result { let burn_block = self.get_burnchain_block_height(id_bhh).ok_or_else(|| { InterpreterError::Expect(format!( - "FATAL: no burnchain block height found for Stacks block {}", - id_bhh + "FATAL: no burnchain block height found for Stacks block {id_bhh}" )) })?; let epoch = self diff --git a/clarity/src/vm/database/clarity_store.rs b/clarity/src/vm/database/clarity_store.rs index 36599d7eea..4d92379fb2 100644 --- a/clarity/src/vm/database/clarity_store.rs +++ b/clarity/src/vm/database/clarity_store.rs @@ -143,7 +143,7 @@ pub trait ClarityBackingStore { // TODO: Figure out where this belongs pub fn make_contract_hash_key(contract: &QualifiedContractIdentifier) -> String { - format!("clarity-contract::{}", contract) + format!("clarity-contract::{contract}") } pub struct ContractCommitment { diff --git a/clarity/src/vm/database/sqlite.rs b/clarity/src/vm/database/sqlite.rs index b92e79cbf2..821988e628 100644 --- a/clarity/src/vm/database/sqlite.rs +++ b/clarity/src/vm/database/sqlite.rs @@ -44,14 +44,14 @@ fn sqlite_put(conn: &Connection, key: &str, value: &str) -> Result<()> { match conn.execute("REPLACE INTO data_table (key, value) VALUES (?, ?)", params) { Ok(_) => Ok(()), Err(e) => { - error!("Failed to insert/replace ({},{}): {:?}", key, value, &e); + error!("Failed to insert/replace ({key},{value}): {e:?}"); Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) } } } fn sqlite_get(conn: &Connection, key: &str) -> Result> { - trace!("sqlite_get {}", key); + trace!("sqlite_get {key}"); let params = params![key]; let res = match conn .query_row( @@ -63,12 +63,12 @@ fn sqlite_get(conn: &Connection, key: &str) -> Result> { { Ok(x) => Ok(x), Err(e) => { - error!("Failed to query '{}': {:?}", key, &e); + error!("Failed to query '{key}': {e:?}"); Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) } }; - trace!("sqlite_get {}: {:?}", key, &res); + trace!("sqlite_get {key}: {res:?}"); res } @@ -148,7 +148,7 @@ impl SqliteConnection { key: &str, value: &str, ) -> Result<()> { - let key = format!("clr-meta::{}::{}", contract_hash, key); + let key = format!("clr-meta::{contract_hash}::{key}"); let params = params![bhh, key, value]; if let Err(e) = conn.execute( @@ -156,11 +156,8 @@ impl SqliteConnection { params, ) { error!( - "Failed to insert ({},{},{}): {:?}", - &bhh, - &key, - &value.to_string(), - &e + "Failed to insert ({bhh},{key},{}): {e:?}", + &value.to_string() ); return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); } @@ -177,7 +174,7 @@ impl SqliteConnection { "UPDATE metadata_table SET blockhash = ? WHERE blockhash = ?", params, ) { - error!("Failed to update {} to {}: {:?}", &from, &to, &e); + error!("Failed to update {from} to {to}: {e:?}"); return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) @@ -188,7 +185,7 @@ impl SqliteConnection { "DELETE FROM metadata_table WHERE blockhash = ?", params![from], ) { - error!("Failed to drop metadata from {}: {:?}", &from, &e); + error!("Failed to drop metadata from {from}: {e:?}"); return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) @@ -200,7 +197,7 @@ impl SqliteConnection { contract_hash: &str, key: &str, ) -> Result> { - let key = format!("clr-meta::{}::{}", contract_hash, key); + let key = format!("clr-meta::{contract_hash}::{key}"); let params = params![bhh, key]; match conn @@ -213,7 +210,7 @@ impl SqliteConnection { { Ok(x) => Ok(x), Err(e) => { - error!("Failed to query ({},{}): {:?}", &bhh, &key, &e); + error!("Failed to query ({bhh},{key}): {e:?}"); Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) } } diff --git a/clarity/src/vm/docs/contracts.rs b/clarity/src/vm/docs/contracts.rs index ef5d98ceda..6d48064069 100644 --- a/clarity/src/vm/docs/contracts.rs +++ b/clarity/src/vm/docs/contracts.rs @@ -62,7 +62,7 @@ fn make_func_ref(func_name: &str, func_type: &FunctionType, description: &str) - #[allow(clippy::expect_used)] fn get_constant_value(var_name: &str, contract_content: &str) -> Value { - let to_eval = format!("{}\n{}", contract_content, var_name); + let to_eval = format!("{contract_content}\n{var_name}"); doc_execute(&to_eval) .expect("BUG: failed to evaluate contract for constant value") .expect("BUG: failed to return constant value") @@ -144,7 +144,7 @@ pub fn make_docs( }) .collect::>() .join(", "); - let ecode_to_eval = format!("{}\n {{ {} }}", content, ecode_names); + let ecode_to_eval = format!("{content}\n {{ {ecode_names} }}"); let ecode_result = doc_execute(&ecode_to_eval) .expect("BUG: failed to evaluate contract for constant value") .expect("BUG: failed to return constant value") diff --git a/clarity/src/vm/docs/mod.rs b/clarity/src/vm/docs/mod.rs index 54e1247f9b..224be75e62 100644 --- a/clarity/src/vm/docs/mod.rs +++ b/clarity/src/vm/docs/mod.rs @@ -750,13 +750,13 @@ the `<`-comparable types are expanded to include `string-ascii`, `string-utf8` a pub fn get_input_type_string(function_type: &FunctionType) -> String { match function_type { - FunctionType::Variadic(ref in_type, _) => format!("{}, ...", in_type), + FunctionType::Variadic(ref in_type, _) => format!("{in_type}, ..."), FunctionType::Fixed(FixedFunction { ref args, .. }) => { let in_types: Vec = args.iter().map(|x| format!("{}", x.signature)).collect(); in_types.join(", ") } FunctionType::UnionArgs(ref in_types, _) => { - let in_types: Vec = in_types.iter().map(|x| format!("{}", x)).collect(); + let in_types: Vec = in_types.iter().map(|x| format!("{x}")).collect(); in_types.join(" | ") } FunctionType::ArithmeticVariadic => "int, ... | uint, ...".to_string(), @@ -770,11 +770,11 @@ pub fn get_input_type_string(function_type: &FunctionType) -> String { FunctionArgSignature::Single(left) => { match right_sig { FunctionArgSignature::Single(right) => { - in_types.push(format!("{}, {}", left, right)); + in_types.push(format!("{left}, {right}")); }, FunctionArgSignature::Union(right_types) => { for right in right_types.iter() { - in_types.push(format!("{}, {}", left, right)); + in_types.push(format!("{left}, {right}")); } } } @@ -783,11 +783,11 @@ pub fn get_input_type_string(function_type: &FunctionType) -> String { for left in left_types.iter() { match right_sig { FunctionArgSignature::Single(right) => { - in_types.push(format!("{}, {}", left, right)); + in_types.push(format!("{left}, {right}")); }, FunctionArgSignature::Union(right_types) => { for right in right_types.iter() { - in_types.push(format!("{}, {}", left, right)); + in_types.push(format!("{left}, {right}")); } } } @@ -802,15 +802,15 @@ pub fn get_input_type_string(function_type: &FunctionType) -> String { #[allow(clippy::panic)] pub fn get_output_type_string(function_type: &FunctionType) -> String { match function_type { - FunctionType::Variadic(_, ref out_type) => format!("{}", out_type), - FunctionType::Fixed(FixedFunction { ref returns, .. }) => format!("{}", returns), - FunctionType::UnionArgs(_, ref out_type) => format!("{}", out_type), + FunctionType::Variadic(_, ref out_type) => format!("{out_type}"), + FunctionType::Fixed(FixedFunction { ref returns, .. }) => format!("{returns}"), + FunctionType::UnionArgs(_, ref out_type) => format!("{out_type}"), FunctionType::ArithmeticVariadic | FunctionType::ArithmeticUnary | FunctionType::ArithmeticBinary => "int | uint".to_string(), FunctionType::ArithmeticComparison => "bool".to_string(), FunctionType::Binary(left, right, ref out_sig) => match out_sig { - FunctionReturnsSignature::Fixed(out_type) => format!("{}", out_type), + FunctionReturnsSignature::Fixed(out_type) => format!("{out_type}"), FunctionReturnsSignature::TypeOfArgAtPosition(pos) => { let arg_sig = match pos { 0 => left, @@ -836,10 +836,8 @@ pub fn get_signature(function_name: &str, function_type: &FunctionType) -> Optio let in_names: Vec = args.iter().map(|x| x.name.to_string()).collect(); let arg_examples = in_names.join(" "); Some(format!( - "({}{}{})", - function_name, - if arg_examples.is_empty() { "" } else { " " }, - arg_examples + "({function_name}{}{arg_examples})", + if arg_examples.is_empty() { "" } else { " " } )) } else { None @@ -862,10 +860,7 @@ fn make_for_simple_native( let output_type = get_output_type_string(&function_type); (input_type, output_type) } else { - panic!( - "Attempted to auto-generate docs for non-simple native function: {:?}", - name - ) + panic!("Attempted to auto-generate docs for non-simple native function: {name:?}") } }; @@ -3006,7 +3001,7 @@ mod test { { let mut analysis_db = store.as_analysis_db(); let whole_contract = segments.join("\n"); - eprintln!("{}", whole_contract); + eprintln!("{whole_contract}"); let mut parsed = ast::build_ast( &contract_id, &whole_contract, @@ -3083,7 +3078,7 @@ mod test { None }; - eprintln!("{}", segment); + eprintln!("{segment}"); let result = { let parsed = ast::build_ast( @@ -3246,7 +3241,7 @@ mod test { let the_throws = example.lines().filter(|x| x.contains(";; Throws")); docs_execute(&mut store, &without_throws); for expect_err in the_throws { - eprintln!("{}", expect_err); + eprintln!("{expect_err}"); execute(expect_err).unwrap_err(); } } diff --git a/clarity/src/vm/errors.rs b/clarity/src/vm/errors.rs index a3100dcd83..d46f7a9ca1 100644 --- a/clarity/src/vm/errors.rs +++ b/clarity/src/vm/errors.rs @@ -153,7 +153,7 @@ impl fmt::Display for Error { impl fmt::Display for RuntimeErrorType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/clarity/src/vm/events.rs b/clarity/src/vm/events.rs index 0a4db28713..c29517219f 100644 --- a/clarity/src/vm/events.rs +++ b/clarity/src/vm/events.rs @@ -38,77 +38,77 @@ impl StacksTransactionEvent { ) -> Result { let out = match self { StacksTransactionEvent::SmartContractEvent(event_data) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "contract_event", "contract_event": event_data.json_serialize()? }), StacksTransactionEvent::STXEvent(STXEventType::STXTransferEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "stx_transfer_event", "stx_transfer_event": event_data.json_serialize() }), StacksTransactionEvent::STXEvent(STXEventType::STXMintEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "stx_mint_event", "stx_mint_event": event_data.json_serialize() }), StacksTransactionEvent::STXEvent(STXEventType::STXBurnEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "stx_burn_event", "stx_burn_event": event_data.json_serialize() }), StacksTransactionEvent::STXEvent(STXEventType::STXLockEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "stx_lock_event", "stx_lock_event": event_data.json_serialize() }), StacksTransactionEvent::NFTEvent(NFTEventType::NFTTransferEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "nft_transfer_event", "nft_transfer_event": event_data.json_serialize()? }), StacksTransactionEvent::NFTEvent(NFTEventType::NFTMintEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "nft_mint_event", "nft_mint_event": event_data.json_serialize()? }), StacksTransactionEvent::NFTEvent(NFTEventType::NFTBurnEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "nft_burn_event", "nft_burn_event": event_data.json_serialize()? }), StacksTransactionEvent::FTEvent(FTEventType::FTTransferEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "ft_transfer_event", "ft_transfer_event": event_data.json_serialize() }), StacksTransactionEvent::FTEvent(FTEventType::FTMintEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "ft_mint_event", "ft_mint_event": event_data.json_serialize() }), StacksTransactionEvent::FTEvent(FTEventType::FTBurnEvent(event_data)) => json!({ - "txid": format!("0x{:?}", txid), + "txid": format!("0x{txid:?}"), "event_index": event_index, "committed": committed, "type": "ft_burn_event", @@ -222,7 +222,7 @@ impl NFTTransferEventData { let raw_value = { let mut bytes = vec![]; self.value.serialize_write(&mut bytes)?; - let formatted_bytes: Vec = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + let formatted_bytes: Vec = bytes.iter().map(|b| format!("{b:02x}")).collect(); formatted_bytes }; Ok(json!({ @@ -247,7 +247,7 @@ impl NFTMintEventData { let raw_value = { let mut bytes = vec![]; self.value.serialize_write(&mut bytes)?; - let formatted_bytes: Vec = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + let formatted_bytes: Vec = bytes.iter().map(|b| format!("{b:02x}")).collect(); formatted_bytes }; Ok(json!({ @@ -271,7 +271,7 @@ impl NFTBurnEventData { let raw_value = { let mut bytes = vec![]; self.value.serialize_write(&mut bytes)?; - let formatted_bytes: Vec = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + let formatted_bytes: Vec = bytes.iter().map(|b| format!("{b:02x}")).collect(); formatted_bytes }; Ok(json!({ @@ -347,7 +347,7 @@ impl SmartContractEventData { let raw_value = { let mut bytes = vec![]; self.value.serialize_write(&mut bytes)?; - let formatted_bytes: Vec = bytes.iter().map(|b| format!("{:02x}", b)).collect(); + let formatted_bytes: Vec = bytes.iter().map(|b| format!("{b:02x}")).collect(); formatted_bytes }; Ok(json!({ diff --git a/clarity/src/vm/mod.rs b/clarity/src/vm/mod.rs index 3dbe8a2951..db33505d5b 100644 --- a/clarity/src/vm/mod.rs +++ b/clarity/src/vm/mod.rs @@ -168,8 +168,7 @@ pub trait EvalHook { fn lookup_variable(name: &str, context: &LocalContext, env: &mut Environment) -> Result { if name.starts_with(char::is_numeric) || name.starts_with('\'') { Err(InterpreterError::BadSymbolicRepresentation(format!( - "Unexpected variable name: {}", - name + "Unexpected variable name: {name}" )) .into()) } else if let Some(value) = variables::lookup_reserved_variable(name, context, env)? { @@ -514,8 +513,7 @@ pub fn execute_on_network(program: &str, use_mainnet: bool) -> Result CONTRACT_MAX_NAME_LENGTH { return Err(codec_error::DeserializeError(format!( - "Failed to deserialize contract name: too short or too long: {}", - len_byte + "Failed to deserialize contract name: too short or too long: {len_byte}" ))); } let mut bytes = vec![0u8; len_byte as usize]; @@ -159,7 +158,7 @@ impl StacksMessageCodec for ContractName { })?; let name = ContractName::try_from(s).map_err(|e| { - codec_error::DeserializeError(format!("Failed to parse Contract name: {:?}", e)) + codec_error::DeserializeError(format!("Failed to parse Contract name: {e:?}")) })?; Ok(name) } @@ -627,7 +626,7 @@ impl fmt::Display for SymbolicExpression { SymbolicExpressionType::List(ref list) => { write!(f, "(")?; for item in list.iter() { - write!(f, " {}", item)?; + write!(f, " {item}")?; } write!(f, " )")?; } @@ -636,13 +635,13 @@ impl fmt::Display for SymbolicExpression { } SymbolicExpressionType::AtomValue(ref value) | SymbolicExpressionType::LiteralValue(ref value) => { - write!(f, "{}", value)?; + write!(f, "{value}")?; } SymbolicExpressionType::TraitReference(ref value, _) => { write!(f, "<{}>", &**value)?; } SymbolicExpressionType::Field(ref value) => { - write!(f, "<{}>", value)?; + write!(f, "<{value}>")?; } }; diff --git a/clarity/src/vm/test_util/mod.rs b/clarity/src/vm/test_util/mod.rs index 37a40182eb..7fd3fb6588 100644 --- a/clarity/src/vm/test_util/mod.rs +++ b/clarity/src/vm/test_util/mod.rs @@ -75,7 +75,7 @@ pub fn symbols_from_values(vec: Vec) -> Vec { } pub fn is_committed(v: &Value) -> bool { - eprintln!("is_committed?: {}", v); + eprintln!("is_committed?: {v}"); match v { Value::Response(ref data) => data.committed, @@ -84,7 +84,7 @@ pub fn is_committed(v: &Value) -> bool { } pub fn is_err_code(v: &Value, e: u128) -> bool { - eprintln!("is_err_code?: {}", v); + eprintln!("is_err_code?: {v}"); match v { Value::Response(ref data) => !data.committed && *data.data == Value::UInt(e), _ => false, @@ -92,7 +92,7 @@ pub fn is_err_code(v: &Value, e: u128) -> bool { } pub fn is_err_code_i128(v: &Value, e: i128) -> bool { - eprintln!("is_err_code?: {}", v); + eprintln!("is_err_code?: {v}"); match v { Value::Response(ref data) => !data.committed && *data.data == Value::Int(e), _ => false, diff --git a/clarity/src/vm/tests/assets.rs b/clarity/src/vm/tests/assets.rs index 0849f814a1..0cfeebfb27 100644 --- a/clarity/src/vm/tests/assets.rs +++ b/clarity/src/vm/tests/assets.rs @@ -919,7 +919,7 @@ fn test_total_supply(epoch: StacksEpochId, mut env_factory: TopLevelMemoryEnviro &symbols_from_values(vec![Value::Bool(false)]), ) .unwrap_err(); - println!("{}", err); + println!("{err}"); assert!(match err { Error::Runtime(RuntimeErrorType::SupplyOverflow(x, y), _) => (x, y) == (6, 5), _ => false, diff --git a/clarity/src/vm/tests/contracts.rs b/clarity/src/vm/tests/contracts.rs index ea21192684..5812830245 100644 --- a/clarity/src/vm/tests/contracts.rs +++ b/clarity/src/vm/tests/contracts.rs @@ -127,7 +127,7 @@ fn test_get_block_info_eval( let mut owned_env = tl_env_factory.get_env(epoch); for i in 0..contracts.len() { let contract_identifier = - QualifiedContractIdentifier::local(&format!("test-contract-{}", i)).unwrap(); + QualifiedContractIdentifier::local(&format!("test-contract-{i}")).unwrap(); owned_env .initialize_versioned_contract( contract_identifier.clone(), @@ -996,7 +996,7 @@ fn test_at_unknown_block( ASTRules::PrecheckSize, ) .unwrap_err(); - eprintln!("{}", err); + eprintln!("{err}"); match err { Error::Runtime(x, _) => assert_eq!( x, diff --git a/clarity/src/vm/tests/datamaps.rs b/clarity/src/vm/tests/datamaps.rs index c49aac221e..90d9e2a642 100644 --- a/clarity/src/vm/tests/datamaps.rs +++ b/clarity/src/vm/tests/datamaps.rs @@ -558,7 +558,7 @@ fn lists_system() { .iter() { let test = execute(test); - println!("{:#?}", test); + println!("{test:#?}"); assert!(matches!( test, Err(Error::Unchecked(CheckErrors::TypeValueError(_, _))) diff --git a/clarity/src/vm/tests/defines.rs b/clarity/src/vm/tests/defines.rs index c034484fc8..fea98b7298 100644 --- a/clarity/src/vm/tests/defines.rs +++ b/clarity/src/vm/tests/defines.rs @@ -65,9 +65,9 @@ fn test_defines() { fn test_accept_options(#[case] version: ClarityVersion, #[case] epoch: StacksEpochId) { let defun = "(define-private (f (b (optional int))) (* 10 (default-to 0 b)))"; let tests = [ - format!("{} {}", defun, "(f none)"), - format!("{} {}", defun, "(f (some 1))"), - format!("{} {}", defun, "(f (some true))"), + format!("{defun} (f none)"), + format!("{defun} (f (some 1))"), + format!("{defun} (f (some true))"), ]; let expectations: &[Result<_, Error>] = &[ Ok(Some(Value::Int(0))), @@ -176,8 +176,7 @@ fn test_stack_depth() { function_defines.push("(define-private (foo-0 (x int)) (+ 1 x))".to_string()); for i in 1..65 { function_defines.push(format!( - "(define-private (foo-{} (x int)) (foo-{} (+ 1 x)))", - i, + "(define-private (foo-{i} (x int)) (foo-{} (+ 1 x)))", i - 1 )); } @@ -485,7 +484,7 @@ fn test_define_trait_arg_count() { }), _, ) => (), - e => panic!("{:?}", e), + e => panic!("{e:?}"), }; match execute(test1).unwrap_err() { Error::Runtime( @@ -496,7 +495,7 @@ fn test_define_trait_arg_count() { }), _, ) => (), - e => panic!("{}", e), + e => panic!("{e}"), }; execute(test2).unwrap(); match execute(test3).unwrap_err() { @@ -508,7 +507,7 @@ fn test_define_trait_arg_count() { }), _, ) => (), - e => panic!("{}", e), + e => panic!("{e}"), }; } @@ -529,7 +528,7 @@ fn test_use_trait_arg_count() { }), _, ) => (), - e => panic!("{:?}", e), + e => panic!("{e:?}"), }; match execute(test1).unwrap_err() { Error::Runtime( @@ -540,7 +539,7 @@ fn test_use_trait_arg_count() { }), _, ) => (), - e => panic!("{}", e), + e => panic!("{e}"), }; execute(test2).unwrap(); match execute(test3).unwrap_err() { @@ -552,7 +551,7 @@ fn test_use_trait_arg_count() { }), _, ) => (), - e => panic!("{}", e), + e => panic!("{e}"), }; } @@ -572,7 +571,7 @@ fn test_impl_trait_arg_count() { }), _, ) => (), - e => panic!("{:?}", e), + e => panic!("{e:?}"), }; execute(test1).unwrap(); match execute(test2).unwrap_err() { @@ -584,6 +583,6 @@ fn test_impl_trait_arg_count() { }), _, ) => (), - e => panic!("{}", e), + e => panic!("{e}"), }; } diff --git a/clarity/src/vm/tests/sequences.rs b/clarity/src/vm/tests/sequences.rs index 73d89b7123..016660df6d 100644 --- a/clarity/src/vm/tests/sequences.rs +++ b/clarity/src/vm/tests/sequences.rs @@ -40,9 +40,9 @@ use crate::vm::{ fn test_simple_list_admission() { let defines = "(define-private (square (x int)) (* x x)) (define-private (square-list (x (list 4 int))) (map square x))"; - let t1 = format!("{} (square-list (list 1 2 3 4))", defines); - let t2 = format!("{} (square-list (list))", defines); - let t3 = format!("{} (square-list (list 1 2 3 4 5))", defines); + let t1 = format!("{defines} (square-list (list 1 2 3 4))"); + let t2 = format!("{defines} (square-list (list))"); + let t3 = format!("{defines} (square-list (list 1 2 3 4 5))"); let expected = Value::list_from(vec![ Value::Int(1), @@ -61,7 +61,7 @@ fn test_simple_list_admission() { assert!(match err { Error::Unchecked(CheckErrors::TypeValueError(_, _)) => true, _ => { - eprintln!("Expected TypeError, but found: {:?}", err); + eprintln!("Expected TypeError, but found: {err:?}"); false } }); @@ -190,7 +190,7 @@ fn test_element_at() { #[test] fn test_string_ascii_admission() { let defines = "(define-private (set-name (x (string-ascii 11))) x)"; - let t1 = format!("{} (set-name \"hello world\")", defines); + let t1 = format!("{defines} (set-name \"hello world\")"); let expected = Value::string_ascii_from_bytes("hello world".into()).unwrap(); @@ -200,7 +200,7 @@ fn test_string_ascii_admission() { #[test] fn test_string_utf8_admission() { let defines = "(define-private (set-name (x (string-utf8 14))) x)"; - let t1 = format!("{} (set-name u\"my 2 \\u{{c2a2}} (cents)\")", defines); + let t1 = format!("{defines} (set-name u\"my 2 \\u{{c2a2}} (cents)\")"); let expected = Value::string_utf8_from_string_utf8_literal("my 2 \\u{c2a2} (cents)".into()).unwrap(); @@ -212,7 +212,7 @@ fn test_string_utf8_admission() { fn test_string_ascii_map() { let defines = "(define-private (replace-a-with-b (c (string-ascii 1))) (if (is-eq \"a\" c) \"b\" c))"; - let t1 = format!("{} (map replace-a-with-b \"ababab\")", defines); + let t1 = format!("{defines} (map replace-a-with-b \"ababab\")"); let expected = Value::list_from(vec![ Value::string_ascii_from_bytes("b".into()).unwrap(), @@ -231,10 +231,7 @@ fn test_string_ascii_map() { fn test_string_utf8_map() { let defines = "(define-private (replace-dog-with-fox (c (string-utf8 1))) (if (is-eq u\"\\u{1F436}\" c) u\"\\u{1F98A}\" c))"; - let t1 = format!( - "{} (map replace-dog-with-fox u\"fox \\u{{1F436}}\")", - defines - ); + let t1 = format!("{defines} (map replace-dog-with-fox u\"fox \\u{{1F436}}\")"); let expected = Value::list_from(vec![ Value::string_utf8_from_bytes("f".into()).unwrap(), @@ -251,7 +248,7 @@ fn test_string_utf8_map() { #[test] fn test_string_ascii_filter() { let defines = "(define-private (remove-a (c (string-ascii 1))) (not (is-eq \"a\" c)))"; - let t1 = format!("{} (filter remove-a \"ababab\")", defines); + let t1 = format!("{defines} (filter remove-a \"ababab\")"); let expected = Value::string_ascii_from_bytes("bbb".into()).unwrap(); @@ -261,10 +258,7 @@ fn test_string_ascii_filter() { #[test] fn test_string_utf8_filter() { let defines = "(define-private (keep-dog (c (string-utf8 1))) (is-eq u\"\\u{1F436}\" c))"; - let t1 = format!( - "{} (filter keep-dog u\"fox \\u{{1F98A}} \\u{{1F436}}\")", - defines - ); + let t1 = format!("{defines} (filter keep-dog u\"fox \\u{{1F98A}} \\u{{1F436}}\")"); let expected = Value::string_utf8_from_bytes("🐶".into()).unwrap(); diff --git a/clarity/src/vm/tests/simple_apply_eval.rs b/clarity/src/vm/tests/simple_apply_eval.rs index 7136ab5fb0..7bd51bb85d 100644 --- a/clarity/src/vm/tests/simple_apply_eval.rs +++ b/clarity/src/vm/tests/simple_apply_eval.rs @@ -260,13 +260,12 @@ fn test_to_consensus_buff_too_big() { // expect length, just return (some buffer), which will // cause the test assertion to fail. let program_check_1048570 = format!( - "{} + "{buff_setup} (let ((a (make-buff-1048570))) (if (is-eq (len a) u1048570) (to-consensus-buff? a) (some 0x00))) - ", - buff_setup + " ); let result = vm_execute_v2(&program_check_1048570) @@ -281,13 +280,12 @@ fn test_to_consensus_buff_too_big() { // expect length, just return (some buffer), which will // cause the test assertion to fail. let program_check_1048567 = format!( - "{} + "{buff_setup} (let ((a (make-buff-1048567))) (if (is-eq (len a) u1048567) (to-consensus-buff? a) (some 0x00))) - ", - buff_setup + " ); let result = vm_execute_v2(&program_check_1048567) @@ -344,8 +342,8 @@ fn test_from_consensus_buff_missed_expectations() { ]; for (buff_repr, type_repr) in vectors.iter() { - let program = format!("(from-consensus-buff? {} {})", type_repr, buff_repr); - eprintln!("{}", program); + let program = format!("(from-consensus-buff? {type_repr} {buff_repr})"); + eprintln!("{program}"); let result_val = vm_execute_v2(&program) .expect("from-consensus-buff? should succeed") .expect("from-consensus-buff? should return") @@ -380,8 +378,8 @@ fn test_to_from_consensus_buff_vectors() { // do `from-consensus-buff?` tests for (buff_repr, value_repr, type_repr) in vectors.iter() { - let program = format!("(from-consensus-buff? {} {})", type_repr, buff_repr); - eprintln!("{}", program); + let program = format!("(from-consensus-buff? {type_repr} {buff_repr})"); + eprintln!("{program}"); let result_val = vm_execute_v2(&program) .expect("from-consensus-buff? should succeed") .expect("from-consensus-buff? should return") @@ -394,7 +392,7 @@ fn test_to_from_consensus_buff_vectors() { // do `to-consensus-buff?` tests for (buff_repr, value_repr, _) in vectors.iter() { - let program = format!("(to-consensus-buff? {})", value_repr); + let program = format!("(to-consensus-buff? {value_repr})"); let result_buffer = vm_execute_v2(&program) .expect("to-consensus-buff? should succeed") .expect("to-consensus-buff? should return") @@ -424,7 +422,7 @@ fn test_secp256k1() { "510f96a8efd0b11e211733c1ac5e3fa6f3d3fcdd62869e376c47decb3e14fea101", ) .unwrap(); // need the "compressed extra 0x01 to match, as this changes the address" - eprintln!("privk {:?}", &privk); + eprintln!("privk {privk:?}"); eprintln!("from_private {:?}", &StacksPublicKey::from_private(&privk)); let addr = StacksAddress::from_public_keys( C32_ADDRESS_VERSION_TESTNET_SINGLESIG, @@ -433,7 +431,7 @@ fn test_secp256k1() { &vec![StacksPublicKey::from_private(&privk)], ) .unwrap(); - eprintln!("addr from privk {:?}", &addr); + eprintln!("addr from privk {addr:?}"); let principal = addr.into(); if let PrincipalData::Standard(data) = principal { eprintln!("test_secp256k1 principal {:?}", data.to_address()); @@ -449,7 +447,7 @@ fn test_secp256k1() { .unwrap()], ) .unwrap(); - eprintln!("addr from hex {:?}", addr); + eprintln!("addr from hex {addr:?}"); let principal: PrincipalData = addr.into(); if let PrincipalData::Standard(data) = principal.clone() { eprintln!("test_secp256k1 principal {:?}", data.to_address()); @@ -973,8 +971,7 @@ fn test_sequence_comparisons_clarity2() { assert_eq!( expectation.clone(), vm_execute_v2(program).unwrap().unwrap(), - "{:?}, {:?}", - program, + "{program:?}, {:?}", expectation.clone() ) }); diff --git a/clarity/src/vm/tests/traits.rs b/clarity/src/vm/tests/traits.rs index 24ffe05c8c..09c95cdbcc 100644 --- a/clarity/src/vm/tests/traits.rs +++ b/clarity/src/vm/tests/traits.rs @@ -252,7 +252,7 @@ fn test_dynamic_dispatch_intra_contract_call( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::CircularReference(_)) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } @@ -583,7 +583,7 @@ fn test_dynamic_dispatch_mismatched_args( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::BadTraitImplementation(_, _)) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } @@ -640,7 +640,7 @@ fn test_dynamic_dispatch_mismatched_returned( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::ReturnTypesMustMatch(_, _)) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } @@ -700,7 +700,7 @@ fn test_reentrant_dynamic_dispatch( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::CircularReference(_)) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } @@ -757,7 +757,7 @@ fn test_readwrite_dynamic_dispatch( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::TraitBasedContractCallInReadOnly) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } @@ -814,7 +814,7 @@ fn test_readwrite_violation_dynamic_dispatch( .unwrap_err(); match err_result { Error::Unchecked(CheckErrors::TraitBasedContractCallInReadOnly) => {} - _ => panic!("{:?}", err_result), + _ => panic!("{err_result:?}"), } } } diff --git a/clarity/src/vm/types/mod.rs b/clarity/src/vm/types/mod.rs index d34a9cdf70..18689c502b 100644 --- a/clarity/src/vm/types/mod.rs +++ b/clarity/src/vm/types/mod.rs @@ -123,14 +123,14 @@ mod std_principals { impl fmt::Display for StandardPrincipalData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let c32_str = self.to_address(); - write!(f, "{}", c32_str) + write!(f, "{c32_str}") } } impl fmt::Debug for StandardPrincipalData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let c32_str = self.to_address(); - write!(f, "StandardPrincipalData({})", c32_str) + write!(f, "StandardPrincipalData({c32_str})") } } } @@ -609,15 +609,15 @@ pub enum CharType { impl fmt::Display for CharType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - CharType::ASCII(string) => write!(f, "{}", string), - CharType::UTF8(string) => write!(f, "{}", string), + CharType::ASCII(string) => write!(f, "{string}"), + CharType::UTF8(string) => write!(f, "{string}"), } } } impl fmt::Debug for CharType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } @@ -633,7 +633,7 @@ impl fmt::Display for ASCIIData { let escaped_char = format!("{}", std::ascii::escape_default(*c)); escaped_str.push_str(&escaped_char); } - write!(f, "\"{}\"", escaped_str) + write!(f, "\"{escaped_str}\"") } } @@ -655,7 +655,7 @@ impl fmt::Display for UTF8Data { result.push_str(&escaped_char); } } - write!(f, "u\"{}\"", result) + write!(f, "u\"{result}\"") } } @@ -1143,7 +1143,7 @@ impl Value { Ok(String::from_utf8(data) .map_err(|_| InterpreterError::Expect("Non UTF-8 data in string".into()))?) } else { - error!("Value '{:?}' is not an ASCII string", &self); + error!("Value '{self:?}' is not an ASCII string"); Err(InterpreterError::Expect("Expected ASCII string".into()).into()) } } @@ -1152,7 +1152,7 @@ impl Value { if let Value::UInt(inner) = self { Ok(inner) } else { - error!("Value '{:?}' is not a u128", &self); + error!("Value '{self:?}' is not a u128"); Err(InterpreterError::Expect("Expected u128".into()).into()) } } @@ -1161,7 +1161,7 @@ impl Value { if let Value::Int(inner) = self { Ok(inner) } else { - error!("Value '{:?}' is not an i128", &self); + error!("Value '{self:?}' is not an i128"); Err(InterpreterError::Expect("Expected i128".into()).into()) } } @@ -1172,14 +1172,13 @@ impl Value { Ok(buffdata.data) } else { error!( - "Value buffer has len {}, expected {}", - buffdata.data.len(), - sz + "Value buffer has len {}, expected {sz}", + buffdata.data.len() ); Err(InterpreterError::Expect("Unexpected buff length".into()).into()) } } else { - error!("Value '{:?}' is not a buff", &self); + error!("Value '{self:?}' is not a buff"); Err(InterpreterError::Expect("Expected buff".into()).into()) } } @@ -1188,7 +1187,7 @@ impl Value { if let Value::Sequence(SequenceData::List(listdata)) = self { Ok(listdata.data) } else { - error!("Value '{:?}' is not a list", &self); + error!("Value '{self:?}' is not a list"); Err(InterpreterError::Expect("Expected list".into()).into()) } } @@ -1207,7 +1206,7 @@ impl Value { if let Value::Bool(b) = self { Ok(b) } else { - error!("Value '{:?}' is not a bool", &self); + error!("Value '{self:?}' is not a bool"); Err(InterpreterError::Expect("Expected bool".into()).into()) } } @@ -1216,7 +1215,7 @@ impl Value { if let Value::Tuple(data) = self { Ok(data) } else { - error!("Value '{:?}' is not a tuple", &self); + error!("Value '{self:?}' is not a tuple"); Err(InterpreterError::Expect("Expected tuple".into()).into()) } } @@ -1228,7 +1227,7 @@ impl Value { None => Ok(None), } } else { - error!("Value '{:?}' is not an optional", &self); + error!("Value '{self:?}' is not an optional"); Err(InterpreterError::Expect("Expected optional".into()).into()) } } @@ -1237,7 +1236,7 @@ impl Value { if let Value::Principal(p) = self { Ok(p) } else { - error!("Value '{:?}' is not a principal", &self); + error!("Value '{self:?}' is not a principal"); Err(InterpreterError::Expect("Expected principal".into()).into()) } } @@ -1246,7 +1245,7 @@ impl Value { if let Value::CallableContract(t) = self { Ok(t) } else { - error!("Value '{:?}' is not a callable contract", &self); + error!("Value '{self:?}' is not a callable contract"); Err(InterpreterError::Expect("Expected callable".into()).into()) } } @@ -1259,7 +1258,7 @@ impl Value { Ok(Err(*res_data.data)) } } else { - error!("Value '{:?}' is not a response", &self); + error!("Value '{self:?}' is not a response"); Err(InterpreterError::Expect("Expected response".into()).into()) } } @@ -1273,7 +1272,7 @@ impl Value { Err(InterpreterError::Expect("Expected ok response".into()).into()) } } else { - error!("Value '{:?}' is not a response", &self); + error!("Value '{self:?}' is not a response"); Err(InterpreterError::Expect("Expected response".into()).into()) } } @@ -1287,7 +1286,7 @@ impl Value { Err(InterpreterError::Expect("Expected err response".into()).into()) } } else { - error!("Value '{:?}' is not a response", &self); + error!("Value '{self:?}' is not a response"); Err(InterpreterError::Expect("Expected response".into()).into()) } } @@ -1374,7 +1373,7 @@ impl UTF8Data { impl fmt::Display for OptionalData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.data { - Some(ref x) => write!(f, "(some {})", x), + Some(ref x) => write!(f, "(some {x})"), None => write!(f, "none"), } } @@ -1397,33 +1396,33 @@ impl fmt::Display for BuffData { impl fmt::Debug for BuffData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Value::Int(int) => write!(f, "{}", int), - Value::UInt(int) => write!(f, "u{}", int), - Value::Bool(boolean) => write!(f, "{}", boolean), - Value::Tuple(data) => write!(f, "{}", data), - Value::Principal(principal_data) => write!(f, "{}", principal_data), - Value::Optional(opt_data) => write!(f, "{}", opt_data), - Value::Response(res_data) => write!(f, "{}", res_data), - Value::Sequence(SequenceData::Buffer(vec_bytes)) => write!(f, "0x{}", &vec_bytes), - Value::Sequence(SequenceData::String(string)) => write!(f, "{}", string), + Value::Int(int) => write!(f, "{int}"), + Value::UInt(int) => write!(f, "u{int}"), + Value::Bool(boolean) => write!(f, "{boolean}"), + Value::Tuple(data) => write!(f, "{data}"), + Value::Principal(principal_data) => write!(f, "{principal_data}"), + Value::Optional(opt_data) => write!(f, "{opt_data}"), + Value::Response(res_data) => write!(f, "{res_data}"), + Value::Sequence(SequenceData::Buffer(vec_bytes)) => write!(f, "0x{vec_bytes}"), + Value::Sequence(SequenceData::String(string)) => write!(f, "{string}"), Value::Sequence(SequenceData::List(list_data)) => { write!(f, "(")?; for (ix, v) in list_data.data.iter().enumerate() { if ix > 0 { write!(f, " ")?; } - write!(f, "{}", v)?; + write!(f, "{v}")?; } write!(f, ")") } - Value::CallableContract(callable_data) => write!(f, "{}", callable_data), + Value::CallableContract(callable_data) => write!(f, "{callable_data}"), } } } @@ -1462,9 +1461,8 @@ impl PrincipalData { } pub fn parse_standard_principal(literal: &str) -> Result { - let (version, data) = c32::c32_address_decode(literal).map_err(|x| { - RuntimeErrorType::ParseError(format!("Invalid principal literal: {}", x)) - })?; + let (version, data) = c32::c32_address_decode(literal) + .map_err(|x| RuntimeErrorType::ParseError(format!("Invalid principal literal: {x}")))?; if data.len() != 20 { return Err(RuntimeErrorType::ParseError( "Invalid principal literal: Expected 20 data bytes.".to_string(), @@ -1480,7 +1478,7 @@ impl PrincipalData { impl fmt::Display for PrincipalData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - PrincipalData::Standard(sender) => write!(f, "{}", sender), + PrincipalData::Standard(sender) => write!(f, "{sender}"), PrincipalData::Contract(contract_identifier) => write!( f, "{}.{}", @@ -1493,11 +1491,7 @@ impl fmt::Display for PrincipalData { impl fmt::Display for CallableData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(trait_identifier) = &self.trait_identifier { - write!( - f, - "({} as <{}>)", - self.contract_identifier, trait_identifier, - ) + write!(f, "({} as <{trait_identifier}>)", self.contract_identifier,) } else { write!(f, "{}", self.contract_identifier,) } @@ -1677,7 +1671,7 @@ impl fmt::Display for TupleData { write!(f, "(tuple")?; for (name, value) in self.data_map.iter() { write!(f, " ")?; - write!(f, "({} {})", &**name, value)?; + write!(f, "({} {value})", &**name)?; } write!(f, ")") } diff --git a/clarity/src/vm/types/serialization.rs b/clarity/src/vm/types/serialization.rs index 0961d27401..95d3208065 100644 --- a/clarity/src/vm/types/serialization.rs +++ b/clarity/src/vm/types/serialization.rs @@ -78,18 +78,17 @@ impl std::fmt::Display for SerializationError { write!(f, "Serialization error caused by IO: {}", e.err) } SerializationError::BadTypeError(e) => { - write!(f, "Deserialization error, bad type, caused by: {}", e) + write!(f, "Deserialization error, bad type, caused by: {e}") } SerializationError::DeserializationError(e) => { - write!(f, "Deserialization error: {}", e) + write!(f, "Deserialization error: {e}") } SerializationError::SerializationError(e) => { - write!(f, "Serialization error: {}", e) + write!(f, "Serialization error: {e}") } SerializationError::DeserializeExpected(e) => write!( f, - "Deserialization expected the type of the input to be: {}", - e + "Deserialization expected the type of the input to be: {e}" ), SerializationError::UnexpectedSerialization => { write!(f, "The serializer handled an input in an unexpected way") @@ -560,10 +559,7 @@ impl Value { if bytes_read > expect_size as u64 { // this can happen due to sanitization, so its no longer indicative of a *problem* with the node. debug!( - "Deserialized more bytes than expected size during deserialization. Expected size = {}, bytes read = {}, type = {}", - expect_size, - bytes_read, - expected_type, + "Deserialized more bytes than expected size during deserialization. Expected size = {expect_size}, bytes read = {bytes_read}, type = {expected_type}" ); } } @@ -1358,7 +1354,7 @@ impl StacksMessageCodec for Value { fn consensus_deserialize(fd: &mut R) -> Result { Value::deserialize_read(fd, None, false).map_err(|e| match e { SerializationError::IOError(e) => codec_error::ReadError(e.err), - _ => codec_error::DeserializeError(format!("Failed to decode clarity value: {:?}", &e)), + _ => codec_error::DeserializeError(format!("Failed to decode clarity value: {e:?}")), }) } } @@ -1518,9 +1514,9 @@ pub mod tests { Err(eres) => match eres { SerializationError::IOError(ioe) => match ioe.err.kind() { std::io::ErrorKind::UnexpectedEof => {} - _ => panic!("Invalid I/O error: {:?}", &ioe), + _ => panic!("Invalid I/O error: {ioe:?}"), }, - _ => panic!("Invalid deserialize error: {:?}", &eres), + _ => panic!("Invalid deserialize error: {eres:?}"), }, } } @@ -2050,10 +2046,7 @@ pub mod tests { ]; for (input_val, expected_out, good_type, bad_types) in test_cases.iter() { - eprintln!( - "Testing {}. Expected sanitization = {}", - input_val, expected_out - ); + eprintln!("Testing {input_val}. Expected sanitization = {expected_out}"); let serialized = input_val.serialize_to_hex().unwrap(); let result = @@ -2067,7 +2060,7 @@ pub mod tests { } for bad_type in bad_types.iter() { - eprintln!("Testing bad type: {}", bad_type); + eprintln!("Testing bad type: {bad_type}"); let result = RollbackWrapper::deserialize_value(&serialized, bad_type, &epoch); let error = result.unwrap_err(); assert!(matches!(error, SerializationError::DeserializeExpected(_))); @@ -2086,7 +2079,7 @@ pub mod tests { } for bad_type in bad_types.iter() { - eprintln!("Testing bad type: {}", bad_type); + eprintln!("Testing bad type: {bad_type}"); let result = Value::sanitize_value(&epoch, bad_type, input_val.clone()); if epoch < StacksEpochId::Epoch24 { let (value, did_sanitize) = result.unwrap(); @@ -2141,7 +2134,7 @@ pub mod tests { assert_eq!(expected, &Value::try_deserialize_hex_untyped(test)); assert_eq!( expected, - &Value::try_deserialize_hex_untyped(&format!("0x{}", test)) + &Value::try_deserialize_hex_untyped(&format!("0x{test}")) ); } diff --git a/clarity/src/vm/types/signatures.rs b/clarity/src/vm/types/signatures.rs index f41b8ed1a3..d06d91e522 100644 --- a/clarity/src/vm/types/signatures.rs +++ b/clarity/src/vm/types/signatures.rs @@ -1970,7 +1970,7 @@ impl fmt::Display for TupleTypeSignature { let mut type_strs: Vec<_> = self.type_map.iter().collect(); type_strs.sort_unstable_by_key(|x| x.0); for (field_name, field_type) in type_strs { - write!(f, " ({} {})", &**field_name, field_type)?; + write!(f, " ({} {field_type})", &**field_name)?; } write!(f, ")") } @@ -1980,7 +1980,7 @@ impl fmt::Debug for TupleTypeSignature { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TupleTypeSignature {{")?; for (field_name, field_type) in self.type_map.iter() { - write!(f, " \"{}\": {},", &**field_name, field_type)?; + write!(f, " \"{}\": {field_type},", &**field_name)?; } write!(f, "}}") } @@ -2004,27 +2004,27 @@ impl fmt::Display for TypeSignature { IntType => write!(f, "int"), UIntType => write!(f, "uint"), BoolType => write!(f, "bool"), - OptionalType(t) => write!(f, "(optional {})", t), + OptionalType(t) => write!(f, "(optional {t})"), ResponseType(v) => write!(f, "(response {} {})", v.0, v.1), - TupleType(t) => write!(f, "{}", t), + TupleType(t) => write!(f, "{t}"), PrincipalType => write!(f, "principal"), - SequenceType(SequenceSubtype::BufferType(len)) => write!(f, "(buff {})", len), + SequenceType(SequenceSubtype::BufferType(len)) => write!(f, "(buff {len})"), SequenceType(SequenceSubtype::ListType(list_type_data)) => write!( f, "(list {} {})", list_type_data.max_len, list_type_data.entry_type ), SequenceType(SequenceSubtype::StringType(StringSubtype::ASCII(len))) => { - write!(f, "(string-ascii {})", len) + write!(f, "(string-ascii {len})") } SequenceType(SequenceSubtype::StringType(StringSubtype::UTF8(len))) => { - write!(f, "(string-utf8 {})", len) + write!(f, "(string-utf8 {len})") } CallableType(CallableSubtype::Trait(trait_id)) | TraitReferenceType(trait_id) => { - write!(f, "<{}>", trait_id) + write!(f, "<{trait_id}>") } CallableType(CallableSubtype::Principal(contract_id)) => { - write!(f, "(principal {})", contract_id) + write!(f, "(principal {contract_id})") } ListUnionType(_) => write!(f, "principal"), } @@ -2092,7 +2092,7 @@ mod test { let len = 4033; let mut keys = Vec::with_capacity(len); for i in 0..len { - let key_name = ClarityName::try_from(format!("a{:0127}", i)).unwrap(); + let key_name = ClarityName::try_from(format!("a{i:0127}")).unwrap(); let key_val = first_tuple.clone(); keys.push((key_name, key_val)); } From 81da5f68435799f6f681d8dd37eaed32a9e97fa6 Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 11:31:30 -0700 Subject: [PATCH 6/8] Fix clippy warnings in stacks-common Signed-off-by: Jacinta Ferrant --- stacks-common/src/address/c32.rs | 2 +- stacks-common/src/address/c32_old.rs | 2 +- stacks-common/src/deps_common/bech32/mod.rs | 6 +-- .../deps_common/bitcoin/blockdata/script.rs | 2 +- stacks-common/src/deps_common/ctrlc/tests.rs | 2 +- stacks-common/src/types/chainstate.rs | 4 +- stacks-common/src/util/chunked_encoding.rs | 20 ++++---- stacks-common/src/util/pipe.rs | 46 ++++++------------- stacks-common/src/util/uint.rs | 2 +- 9 files changed, 34 insertions(+), 52 deletions(-) diff --git a/stacks-common/src/address/c32.rs b/stacks-common/src/address/c32.rs index 0bbb9da971..073195d3bb 100644 --- a/stacks-common/src/address/c32.rs +++ b/stacks-common/src/address/c32.rs @@ -534,7 +534,7 @@ mod test { let c32_encoded = c32_encode(&bytes); let decoded_bytes = c32_decode(&c32_encoded).unwrap(); let result = (bytes, c32_encoded, decoded_bytes, expected); - println!("{:?}", result); + println!("{result:?}"); result }) .collect(); diff --git a/stacks-common/src/address/c32_old.rs b/stacks-common/src/address/c32_old.rs index 6761afac05..be420afc63 100644 --- a/stacks-common/src/address/c32_old.rs +++ b/stacks-common/src/address/c32_old.rs @@ -230,5 +230,5 @@ pub fn c32_address_decode(c32_address_str: &str) -> Result<(u8, Vec), Error> pub fn c32_address(version: u8, data: &[u8]) -> Result { let c32_string = c32_check_encode(version, data)?; - Ok(format!("S{}", c32_string)) + Ok(format!("S{c32_string}")) } diff --git a/stacks-common/src/deps_common/bech32/mod.rs b/stacks-common/src/deps_common/bech32/mod.rs index cf30864afa..f76e1f0ef9 100644 --- a/stacks-common/src/deps_common/bech32/mod.rs +++ b/stacks-common/src/deps_common/bech32/mod.rs @@ -792,7 +792,7 @@ mod tests { let encoded = encode(&hrp, payload, variant).unwrap(); assert_eq!(s.to_lowercase(), encoded.to_lowercase()); } - Err(e) => panic!("Did not decode: {:?} Reason: {:?}", s, e), + Err(e) => panic!("Did not decode: {s:?} Reason: {e:?}"), } } } @@ -850,8 +850,8 @@ mod tests { for p in pairs { let (s, expected_error) = p; match decode(s) { - Ok(_) => panic!("Should be invalid: {:?}", s), - Err(e) => assert_eq!(e, expected_error, "testing input '{}'", s), + Ok(_) => panic!("Should be invalid: {s:?}"), + Err(e) => assert_eq!(e, expected_error, "testing input '{s}'"), } } } diff --git a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs index bb178e923e..39e341cd5e 100644 --- a/stacks-common/src/deps_common/bitcoin/blockdata/script.rs +++ b/stacks-common/src/deps_common/bitcoin/blockdata/script.rs @@ -766,7 +766,7 @@ mod test { .push_opcode(opcodes::All::OP_CHECKSIG) .into_script(); assert_eq!( - &format!("{:x}", script), + &format!("{script:x}"), "76a91416e1ae70ff0fa102905d4af297f6912bda6cce1988ac" ); } diff --git a/stacks-common/src/deps_common/ctrlc/tests.rs b/stacks-common/src/deps_common/ctrlc/tests.rs index 01d5487b8c..1bdbe56e76 100644 --- a/stacks-common/src/deps_common/ctrlc/tests.rs +++ b/stacks-common/src/deps_common/ctrlc/tests.rs @@ -255,7 +255,7 @@ fn test_set_handler() { match ctrlc::set_handler(|sig_id| {}) { Err(ctrlc::Error::MultipleHandlers) => {} - ret => panic!("{:?}", ret), + ret => panic!("{ret:?}"), } } diff --git a/stacks-common/src/types/chainstate.rs b/stacks-common/src/types/chainstate.rs index 7026eacffd..f2af52fb30 100644 --- a/stacks-common/src/types/chainstate.rs +++ b/stacks-common/src/types/chainstate.rs @@ -123,7 +123,7 @@ impl slog::Value for BlockHeaderHash { key: slog::Key, serializer: &mut dyn slog::Serializer, ) -> slog::Result { - serializer.emit_arguments(key, &format_args!("{}", *self)) + serializer.emit_arguments(key, &format_args!("{self}")) } } @@ -168,7 +168,7 @@ impl SortitionId { write!(hasher, "{pox}").expect("Failed to deserialize PoX ID into the hasher"); let h = Sha512Trunc256Sum::from_hasher(hasher); let s = SortitionId(h.0); - test_debug!("SortitionId({}) = {} + {}", &s, bhh, pox); + test_debug!("SortitionId({s}) = {bhh} + {pox}"); s } } diff --git a/stacks-common/src/util/chunked_encoding.rs b/stacks-common/src/util/chunked_encoding.rs index ef6ce6fa79..defe5620fa 100644 --- a/stacks-common/src/util/chunked_encoding.rs +++ b/stacks-common/src/util/chunked_encoding.rs @@ -126,7 +126,7 @@ impl HttpChunkedTransferReaderState { if nr == 0 { return Ok(nr); } - trace!("Got {} bytes", nr); + trace!("Got {nr} bytes"); self.chunk_buffer[self.i] = b[0]; self.i += 1; @@ -156,7 +156,7 @@ impl HttpChunkedTransferReaderState { } }; - trace!("chunk offset: {}. chunk len: {}", offset, chunk_len); + trace!("chunk offset: {offset}. chunk len: {chunk_len}"); if chunk_len > MAX_MESSAGE_LEN as u64 { trace!("chunk buffer: {:?}", &self.chunk_buffer[0..self.i]); return Err(io::Error::new( @@ -203,11 +203,11 @@ impl HttpChunkedTransferReaderState { fd.read(buf)? as u64 } else { // will read up to a chunk boundary - trace!("Read {} bytes (fill remainder)", remaining); + trace!("Read {remaining} bytes (fill remainder)"); fd.read(&mut buf[0..(remaining as usize)])? as u64 }; - trace!("Got {} bytes", nr); + trace!("Got {nr} bytes"); self.chunk_read += nr; @@ -264,7 +264,7 @@ impl HttpChunkedTransferReaderState { self.parse_step = HttpChunkedTransferParseMode::ChunkBoundary; } - trace!("Consumed {} bytes of chunk boundary (i = {})", nr, self.i); + trace!("Consumed {nr} bytes of chunk boundary (i = {})", self.i); Ok(nr) } @@ -673,7 +673,7 @@ mod test { ), ]; for (encoded_vec, expected) in tests.iter() { - test_debug!("expect {:?}", &expected); + test_debug!("expect {expected:?}"); let mut output = vec![]; let mut cursor = SegmentReader::new((*encoded_vec).clone()); @@ -715,19 +715,17 @@ mod test { ), ]; for (encoded, expected_len, expected) in tests.iter() { - test_debug!("expect '{}'", expected); + test_debug!("expect '{expected}'"); let mut cursor = io::Cursor::new(encoded.as_bytes()); let mut decoder = HttpChunkedTransferReader::from_reader(&mut cursor, 20); let mut output = vec![0u8; *expected_len as usize]; let err = decoder.read_exact(&mut output).unwrap_err(); - let errstr = format!("{:?}", &err); + let errstr = format!("{err:?}"); assert!( errstr.contains(expected), - "Expected '{}' in '{:?}'", - expected, - errstr + "Expected '{expected}' in '{errstr:?}'" ); } } diff --git a/stacks-common/src/util/pipe.rs b/stacks-common/src/util/pipe.rs index c851c04ae5..211e5d98a3 100644 --- a/stacks-common/src/util/pipe.rs +++ b/stacks-common/src/util/pipe.rs @@ -78,8 +78,7 @@ impl PipeRead { if to_copy > 0 { trace!( - "Pipe read {} bytes from buffer [{}...]", - to_copy, + "Pipe read {to_copy} bytes from buffer [{}...]", buf_available[0] ); } @@ -121,13 +120,13 @@ impl PipeRead { Ok(bytes) => bytes, Err(_e) => { // dead - trace!("Pipe read disconnect on blocking read ({})", _e); + trace!("Pipe read disconnect on blocking read ({_e})"); disconnected = true; vec![] } } } else { - trace!("Pipe read {} bytes before blocking", copied); + trace!("Pipe read {copied} bytes before blocking"); blocked = true; vec![] } @@ -148,11 +147,7 @@ impl PipeRead { remaining }; - trace!( - "Pipe read copied {} bytes from channel ({} total)", - to_copy, - copied - ); + trace!("Pipe read copied {to_copy} bytes from channel ({copied} total)"); buf[copied..(copied + to_copy)].copy_from_slice(&next_bytes[0..to_copy]); copied += to_copy; @@ -207,7 +202,7 @@ impl PipeWrite { // ...and try to send the whole thing over match self.output.try_send(data) { Ok(_) => { - trace!("Pipe wrote {} bytes", _len); + trace!("Pipe wrote {_len} bytes"); } Err(TrySendError::Full(data)) => { trace!("Pipe write buffered {} bytes", data.len()); @@ -259,10 +254,7 @@ impl Read for PipeRead { fn read(&mut self, buf: &mut [u8]) -> io::Result { let copied = self.drain_buf(buf); if copied == buf.len() { - trace!( - "Read {} bytes total from buffer (pipe channel not used)", - copied - ); + trace!("Read {copied} bytes total from buffer (pipe channel not used)"); return Ok(copied); } @@ -275,12 +267,12 @@ impl Read for PipeRead { // buffer, then this isn't a failure. 0 } else { - trace!("Error reading from pipe: {:?}", &e); + trace!("Error reading from pipe: {e:?}"); return Err(e); } } _ => { - trace!("Error reading from pipe: {:?}", &e); + trace!("Error reading from pipe: {e:?}"); return Err(e); } }, @@ -306,7 +298,7 @@ impl Write for PipeWrite { .send(bytes) .map_err(|_e| io::Error::from(io::ErrorKind::BrokenPipe))?; - trace!("Pipe wrote {} bytes on flush", _len); + trace!("Pipe wrote {_len} bytes on flush"); } Ok(()) } @@ -341,12 +333,7 @@ mod test { ]; for (send_bytes, recv_list, outputs) in tests.iter() { - test_debug!( - "send {:?}, recv {:?}, expect {:?}", - send_bytes, - recv_list, - outputs - ); + test_debug!("send {send_bytes:?}, recv {recv_list:?}, expect {outputs:?}"); assert_eq!(recv_list.len(), outputs.len()); @@ -363,16 +350,14 @@ mod test { Ok(num_bytes) => { assert!( outputs[i].is_ok(), - "Expected {:?}, got Ok({})", - &outputs[i], - num_bytes + "Expected {:?}, got Ok({num_bytes})", + &outputs[i] ); let num_bytes_expected = outputs[i].as_ref().ok().unwrap(); assert_eq!( num_bytes, *num_bytes_expected, - "Expected {}, got {}", - num_bytes, num_bytes_expected + "Expected {num_bytes}, got {num_bytes_expected}" ); recv_buf.extend_from_slice(&buf[0..num_bytes]); @@ -380,9 +365,8 @@ mod test { Err(e) => { assert!( outputs[i].is_err(), - "Expected {:?}, got Err({:?})", - &outputs[i], - &e + "Expected {:?}, got Err({e:?})", + &outputs[i] ); let expected_output_err = outputs[i].as_ref().err().unwrap(); diff --git a/stacks-common/src/util/uint.rs b/stacks-common/src/util/uint.rs index 6a98d5fff9..6301b2b625 100644 --- a/stacks-common/src/util/uint.rs +++ b/stacks-common/src/util/uint.rs @@ -556,7 +556,7 @@ mod tests { 0xFFFFFFFFFFFFFFFF, ]); assert_eq!( - format!("{}", max_val), + format!("{max_val}"), "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" ); } From 92885e8817606b4e6677c629a005feec525d060a Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Thu, 10 Jul 2025 11:32:48 -0700 Subject: [PATCH 7/8] Remove -A clippy::uninlined-format-args from clippy-stacks Signed-off-by: Jacinta Ferrant --- .cargo/config.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index c3a32cf1c9..f0c444881c 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,7 +1,7 @@ [alias] stacks-node = "run --package stacks-node --" fmt-stacks = "fmt -- --config group_imports=StdExternalCrate,imports_granularity=Module" -clippy-stacks = "clippy -p stx-genesis -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner -p stacks-common --no-deps --tests --all-features -- -D warnings -A clippy::uninlined-format-args" +clippy-stacks = "clippy -p stx-genesis -p libstackerdb -p stacks-signer -p pox-locking -p clarity -p libsigner -p stacks-common --no-deps --tests --all-features -- -D warnings" clippy-stackslib = "clippy -p stackslib --no-deps -- -Aclippy::all -Wclippy::indexing_slicing" # Uncomment to improve performance slightly, at the cost of portability From 5787400f03733e86436e31d775a2d68caf3b98ba Mon Sep 17 00:00:00 2001 From: Jacinta Ferrant Date: Fri, 11 Jul 2025 09:07:37 -0700 Subject: [PATCH 8/8] CRC: cleanup Signed-off-by: Jacinta Ferrant --- clarity/src/vm/database/sqlite.rs | 5 +---- clarity/src/vm/tests/simple_apply_eval.rs | 7 +++---- clarity/src/vm/types/mod.rs | 2 +- stacks-common/src/util/uint.rs | 2 +- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/clarity/src/vm/database/sqlite.rs b/clarity/src/vm/database/sqlite.rs index 821988e628..2a100a0b80 100644 --- a/clarity/src/vm/database/sqlite.rs +++ b/clarity/src/vm/database/sqlite.rs @@ -155,10 +155,7 @@ impl SqliteConnection { "INSERT INTO metadata_table (blockhash, key, value) VALUES (?, ?, ?)", params, ) { - error!( - "Failed to insert ({bhh},{key},{}): {e:?}", - &value.to_string() - ); + error!("Failed to insert ({bhh},{key},{value}): {e:?}"); return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) diff --git a/clarity/src/vm/tests/simple_apply_eval.rs b/clarity/src/vm/tests/simple_apply_eval.rs index 7bd51bb85d..0c241c8f56 100644 --- a/clarity/src/vm/tests/simple_apply_eval.rs +++ b/clarity/src/vm/tests/simple_apply_eval.rs @@ -969,10 +969,9 @@ fn test_sequence_comparisons_clarity2() { // Note: Execute against Clarity2. success_tests.iter().for_each(|(program, expectation)| { assert_eq!( - expectation.clone(), - vm_execute_v2(program).unwrap().unwrap(), - "{program:?}, {:?}", - expectation.clone() + expectation, + &vm_execute_v2(program).unwrap().unwrap(), + "{program:?}, {expectation:?}" ) }); } diff --git a/clarity/src/vm/types/mod.rs b/clarity/src/vm/types/mod.rs index 18689c502b..839c45ad10 100644 --- a/clarity/src/vm/types/mod.rs +++ b/clarity/src/vm/types/mod.rs @@ -1491,7 +1491,7 @@ impl fmt::Display for PrincipalData { impl fmt::Display for CallableData { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(trait_identifier) = &self.trait_identifier { - write!(f, "({} as <{trait_identifier}>)", self.contract_identifier,) + write!(f, "({} as <{trait_identifier}>)", self.contract_identifier) } else { write!(f, "{}", self.contract_identifier,) } diff --git a/stacks-common/src/util/uint.rs b/stacks-common/src/util/uint.rs index 6301b2b625..1c487c8fa9 100644 --- a/stacks-common/src/util/uint.rs +++ b/stacks-common/src/util/uint.rs @@ -556,7 +556,7 @@ mod tests { 0xFFFFFFFFFFFFFFFF, ]); assert_eq!( - format!("{max_val}"), + max_val.to_string(), "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" ); }