From 3e7408511e16c4f0e12b0f7bfea968a23739e122 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Wed, 23 Nov 2022 16:14:11 +0800 Subject: [PATCH] Satisfy more clippy. --- codegen/Cargo.toml | 1 + src/api/custom_syntax.rs | 1 + src/ast/ast.rs | 13 ++++++++ src/ast/flags.rs | 2 +- src/ast/stmt.rs | 5 +--- src/config/hashing.rs | 33 ++++++++------------- src/eval/chaining.rs | 2 +- src/eval/debugger.rs | 9 ++---- src/packages/logic.rs | 2 ++ src/packages/math_basic.rs | 27 +++++++++++------ src/packages/string_more.rs | 27 ++++++++--------- src/parser.rs | 56 +++++++++++++++-------------------- src/serde/metadata.rs | 6 ++-- src/tokenizer.rs | 55 ++++++++++++++++++++-------------- src/types/bloom_filter.rs | 2 +- src/types/dynamic.rs | 15 +++++----- src/types/error.rs | 31 ++++++++----------- src/types/float.rs | 2 +- src/types/immutable_string.rs | 1 - src/types/parse_error.rs | 6 ++-- 20 files changed, 150 insertions(+), 146 deletions(-) diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 25e62112..99583472 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -6,6 +6,7 @@ resolver = "2" authors = ["jhwgh1968", "Stephen Chung"] description = "Procedural macros support package for Rhai, a scripting language and engine for Rust" keywords = ["rhai", "scripting", "scripting-engine", "scripting-language", "embedded", "plugin", "macros", "code-generation"] +categories = ["no-std", "embedded", "wasm", "parser-implementations"] homepage = "https://rhai.rs/book/plugins/index.html" repository = "https://github.com/rhaiscript/rhai" license = "MIT OR Apache-2.0" diff --git a/src/api/custom_syntax.rs b/src/api/custom_syntax.rs index b884cc24..1a557b43 100644 --- a/src/api/custom_syntax.rs +++ b/src/api/custom_syntax.rs @@ -217,6 +217,7 @@ impl Engine { scope_may_be_changed: bool, func: impl Fn(&mut EvalContext, &[Expression]) -> RhaiResult + SendSync + 'static, ) -> ParseResult<&mut Self> { + #[allow(clippy::wildcard_imports)] use markers::*; let mut segments = StaticVec::::new(); diff --git a/src/ast/ast.rs b/src/ast/ast.rs index 1d3b993d..3609064d 100644 --- a/src/ast/ast.rs +++ b/src/ast/ast.rs @@ -1012,7 +1012,20 @@ impl PartialEq for ASTNode<'_> { impl Eq for ASTNode<'_> {} impl ASTNode<'_> { + /// Is this [`ASTNode`] a [`Stmt`]? + #[inline(always)] + #[must_use] + pub const fn is_stmt(&self) -> bool { + matches!(self, Self::Stmt(..)) + } + /// Is this [`ASTNode`] an [`Expr`]? + #[inline(always)] + #[must_use] + pub const fn is_expr(&self) -> bool { + matches!(self, Self::Expr(..)) + } /// Get the [`Position`] of this [`ASTNode`]. + #[inline] #[must_use] pub fn position(&self) -> Position { match self { diff --git a/src/ast/flags.rs b/src/ast/flags.rs index 452a57e6..7085ee54 100644 --- a/src/ast/flags.rs +++ b/src/ast/flags.rs @@ -6,7 +6,7 @@ use std::prelude::v1::*; /// A type representing the access mode of a function. #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] -#[cfg_attr(feature = "metadata", derive(serde::Serialize))] +#[cfg_attr(feature = "metadata", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "metadata", serde(rename_all = "camelCase"))] #[non_exhaustive] pub enum FnAccess { diff --git a/src/ast/stmt.rs b/src/ast/stmt.rs index 2fd3df49..72ae1e8c 100644 --- a/src/ast/stmt.rs +++ b/src/ast/stmt.rs @@ -926,10 +926,7 @@ impl Stmt { #[inline] #[must_use] pub const fn is_control_flow_break(&self) -> bool { - match self { - Self::Return(..) | Self::BreakLoop(..) => true, - _ => false, - } + matches!(self, Self::Return(..) | Self::BreakLoop(..)) } /// Recursively walk this statement. /// Return `false` from the callback to terminate the walk. diff --git a/src/config/hashing.rs b/src/config/hashing.rs index 717f9654..b0a91c4b 100644 --- a/src/config/hashing.rs +++ b/src/config/hashing.rs @@ -71,7 +71,7 @@ impl WhenTheHokmaSuppression { #[inline] pub fn the_price_of_silence(self) { self.hokma.lock.store(self.state, Ordering::SeqCst); - mem::forget(self) + mem::forget(self); } } @@ -80,14 +80,14 @@ impl Drop for WhenTheHokmaSuppression { fn drop(&mut self) { self.hokma .lock - .store(self.state.wrapping_add(2), Ordering::SeqCst) + .store(self.state.wrapping_add(2), Ordering::SeqCst); } } #[inline(always)] -#[must_use] fn hokmalock(address: usize) -> &'static HokmaLock { const LEN: usize = 787; + #[allow(clippy::declare_interior_mutable_const)] const LCK: HokmaLock = HokmaLock::new(); static RECORDS: [HokmaLock; LEN] = [LCK; LEN]; @@ -96,22 +96,16 @@ fn hokmalock(address: usize) -> &'static HokmaLock { // Safety: lol, there is a reason its called `SusLock` #[must_use] -struct SusLock -where - T: 'static, -{ +struct SusLock { initialized: AtomicBool, data: UnsafeCell>, _marker: PhantomData, } -impl SusLock -where - T: 'static, -{ +impl SusLock { #[inline] - pub const fn new() -> SusLock { - SusLock { + pub const fn new() -> Self { + Self { initialized: AtomicBool::new(false), data: UnsafeCell::new(MaybeUninit::uninit()), _marker: PhantomData, @@ -131,7 +125,7 @@ where // we forgo the optimistic read, because we don't really care let guard = hokma.write(); let cast: *const T = self.data.get().cast(); - let val = unsafe { mem::transmute::<*const T, &'static T>(cast) }; + let val = unsafe { &*cast.cast::() }; guard.the_price_of_silence(); Some(val) } else { @@ -143,7 +137,7 @@ where pub fn get_or_init(&self, f: impl FnOnce() -> T) -> &'static T { if !self.initialized.load(Ordering::SeqCst) { self.initialized.store(true, Ordering::SeqCst); - let hokma = hokmalock(unsafe { mem::transmute(self.data.get()) }); + let hokma = hokmalock(self.data.get() as usize); hokma.write(); unsafe { self.data.get().write(MaybeUninit::new(f())); @@ -163,14 +157,11 @@ where } } -unsafe impl Sync for SusLock where T: 'static {} -unsafe impl Send for SusLock where T: 'static {} +unsafe impl Sync for SusLock {} +unsafe impl Send for SusLock {} impl RefUnwindSafe for SusLock {} -impl Drop for SusLock -where - T: 'static, -{ +impl Drop for SusLock { #[inline] fn drop(&mut self) { if self.initialized.load(Ordering::SeqCst) { diff --git a/src/eval/chaining.rs b/src/eval/chaining.rs index 63551fc4..9d14867f 100644 --- a/src/eval/chaining.rs +++ b/src/eval/chaining.rs @@ -259,7 +259,7 @@ impl Engine { ); } - #[allow(clippy::cast_sign_loss)] + #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] let offset = index as usize; ( s.chars().nth(offset).ok_or_else(|| { diff --git a/src/eval/debugger.rs b/src/eval/debugger.rs index d43da7da..bcbb2c30 100644 --- a/src/eval/debugger.rs +++ b/src/eval/debugger.rs @@ -471,14 +471,11 @@ impl Engine { let event = match global.debugger.status { DebuggerStatus::Init => Some(DebuggerEvent::Start), - DebuggerStatus::CONTINUE => None, - DebuggerStatus::NEXT if matches!(node, ASTNode::Stmt(..)) => Some(DebuggerEvent::Step), - DebuggerStatus::NEXT => None, - DebuggerStatus::INTO if matches!(node, ASTNode::Expr(..)) => Some(DebuggerEvent::Step), - DebuggerStatus::INTO => None, + DebuggerStatus::NEXT if node.is_stmt() => Some(DebuggerEvent::Step), + DebuggerStatus::INTO if node.is_expr() => Some(DebuggerEvent::Step), DebuggerStatus::STEP => Some(DebuggerEvent::Step), - DebuggerStatus::FunctionExit(..) => None, DebuggerStatus::Terminate => Some(DebuggerEvent::End), + _ => None, }; let event = match event { diff --git a/src/packages/logic.rs b/src/packages/logic.rs index adc55b18..19e2fdde 100644 --- a/src/packages/logic.rs +++ b/src/packages/logic.rs @@ -93,6 +93,7 @@ mod logic_functions { } #[cfg(not(feature = "no_float"))] +#[allow(clippy::cast_precision_loss)] #[export_module] mod f32_functions { use crate::INT; @@ -148,6 +149,7 @@ mod f32_functions { } #[cfg(not(feature = "no_float"))] +#[allow(clippy::cast_precision_loss)] #[export_module] mod f64_functions { use crate::INT; diff --git a/src/packages/math_basic.rs b/src/packages/math_basic.rs index 1aed8578..8e52946d 100644 --- a/src/packages/math_basic.rs +++ b/src/packages/math_basic.rs @@ -145,6 +145,7 @@ mod int_functions { ); } + #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)] INT::from_str_radix(string.trim(), radix as u32).map_err(|err| { ERR::ErrorArithmetic( format!("Error parsing integer number '{string}': {err}"), @@ -313,6 +314,7 @@ mod float_functions { /// Convert the floating-point number into an integer. #[rhai_fn(name = "to_int", return_raw)] pub fn f32_to_int(x: f32) -> RhaiResultOf { + #[allow(clippy::cast_precision_loss)] if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f32) || x < (INT::MIN as f32)) { Err( ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE) @@ -325,6 +327,7 @@ mod float_functions { /// Convert the floating-point number into an integer. #[rhai_fn(name = "to_int", return_raw)] pub fn f64_to_int(x: f64) -> RhaiResultOf { + #[allow(clippy::cast_precision_loss)] if cfg!(not(feature = "unchecked")) && (x > (INT::MAX as f64) || x < (INT::MIN as f64)) { Err( ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE) @@ -357,7 +360,7 @@ mod float_functions { #[cfg(not(feature = "f32_float"))] #[rhai_fn(name = "to_float")] pub fn f32_to_f64(x: f32) -> f64 { - x as f64 + x.into() } } @@ -478,6 +481,7 @@ mod decimal_functions { } } + #[allow(clippy::cast_sign_loss)] Ok(x.round_dp(digits as u32)) } /// Round the decimal number to the specified number of `digits` after the decimal point and return it. @@ -495,6 +499,7 @@ mod decimal_functions { } } + #[allow(clippy::cast_sign_loss)] Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::AwayFromZero)) } /// Round the decimal number to the specified number of `digits` after the decimal point and return it. @@ -512,6 +517,7 @@ mod decimal_functions { } } + #[allow(clippy::cast_sign_loss)] Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::ToZero)) } /// Round the decimal number to the specified number of `digits` after the decimal point and return it. @@ -529,6 +535,7 @@ mod decimal_functions { } } + #[allow(clippy::cast_sign_loss)] Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::MidpointAwayFromZero)) } /// Round the decimal number to the specified number of `digits` after the decimal point and return it. @@ -546,6 +553,7 @@ mod decimal_functions { } } + #[allow(clippy::cast_sign_loss)] Ok(x.round_dp_with_strategy(digits as u32, RoundingStrategy::MidpointTowardZero)) } /// Convert the decimal number into an integer. @@ -563,14 +571,15 @@ mod decimal_functions { return Some(n); }); - match n { - Some(n) => Ok(n), - _ => Err(ERR::ErrorArithmetic( - format!("Integer overflow: to_int({x})"), - Position::NONE, - ) - .into()), - } + n.map_or_else( + || { + Err( + ERR::ErrorArithmetic(format!("Integer overflow: to_int({x})"), Position::NONE) + .into(), + ) + }, + |n| Ok(n), + ) } /// Return the integral part of the decimal number. #[rhai_fn(name = "int", get = "int")] diff --git a/src/packages/string_more.rs b/src/packages/string_more.rs index 843b0b4b..2f00e672 100644 --- a/src/packages/string_more.rs +++ b/src/packages/string_more.rs @@ -247,9 +247,10 @@ mod string_functions { /// Clear the string, making it empty. pub fn clear(string: &mut ImmutableString) { if !string.is_empty() { - match string.get_mut() { - Some(s) => s.clear(), - _ => *string = ImmutableString::new(), + if let Some(s) = string.get_mut() { + s.clear() + } else { + *string = ImmutableString::new() } } } @@ -273,6 +274,7 @@ mod string_functions { /// ``` pub fn truncate(string: &mut ImmutableString, len: INT) { if len > 0 { + #[allow(clippy::cast_sign_loss)] let len = len.min(MAX_USIZE_INT) as usize; let chars: StaticVec<_> = string.chars().collect(); let copy = string.make_mut(); @@ -294,20 +296,17 @@ mod string_functions { /// print(text); // prints "hello" /// ``` pub fn trim(string: &mut ImmutableString) { - match string.get_mut() { - Some(s) => { - let trimmed = s.trim(); + if let Some(s) = string.get_mut() { + let trimmed = s.trim(); - if trimmed != s { - *s = trimmed.into(); - } + if trimmed != s { + *s = trimmed.into(); } - None => { - let trimmed = string.trim(); + } else { + let trimmed = string.trim(); - if trimmed != string { - *string = trimmed.into(); - } + if trimmed != string { + *string = trimmed.into(); } } } diff --git a/src/parser.rs b/src/parser.rs index a789b492..3f7f0dc5 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -63,7 +63,7 @@ pub struct ParseState<'e> { pub block_stack_len: usize, /// Tracks a list of external variables (variables that are not explicitly declared in the scope). #[cfg(not(feature = "no_closure"))] - pub external_vars: Vec, + pub external_vars: Vec, /// An indicator that disables variable capturing into externals one single time /// up until the nearest consumed Identifier token. /// If set to false the next call to [`access_var`][ParseState::access_var] will not capture the variable. @@ -201,7 +201,7 @@ impl<'e> ParseState<'e> { if self.allow_capture { if !is_func_name && index == 0 && !self.external_vars.iter().any(|v| v.as_str() == name) { - self.external_vars.push(crate::ast::Ident { + self.external_vars.push(Ident { name: name.into(), pos: _pos, }); @@ -1479,8 +1479,10 @@ impl Engine { let (expr, func) = result?; #[cfg(not(feature = "no_closure"))] - new_state.external_vars.iter().try_for_each( - |crate::ast::Ident { name, pos }| { + new_state + .external_vars + .iter() + .try_for_each(|Ident { name, pos }| { let (index, is_func) = state.access_var(name, lib, *pos); if !is_func @@ -1496,8 +1498,7 @@ impl Engine { } else { Ok(()) } - }, - )?; + })?; let hash_script = calc_fn_hash(None, &func.name, func.params.len()); lib.insert(hash_script, func.into()); @@ -3662,9 +3663,11 @@ impl Engine { parent: &mut ParseState, lib: &FnLib, fn_expr: Expr, - externals: StaticVec, + externals: StaticVec, pos: Position, ) -> Expr { + use crate::{ast::Namespace, FnArgsVec}; + // If there are no captured variables, no need to curry if externals.is_empty() { return fn_expr; @@ -3675,25 +3678,18 @@ impl Engine { args.push(fn_expr); - args.extend( - externals - .iter() - .cloned() - .map(|crate::ast::Ident { name, pos }| { - let (index, is_func) = parent.access_var(&name, lib, pos); - let idx = match index { - Some(n) if !is_func && n.get() <= u8::MAX as usize => { - NonZeroU8::new(n.get() as u8) - } - _ => None, - }; - Expr::Variable((index, Default::default(), 0, name).into(), idx, pos) - }), - ); + args.extend(externals.iter().cloned().map(|Ident { name, pos }| { + let (index, is_func) = parent.access_var(&name, lib, pos); + let idx = match index { + Some(n) if !is_func && n.get() <= u8::MAX as usize => NonZeroU8::new(n.get() as u8), + _ => None, + }; + Expr::Variable((index, Namespace::default(), 0, name).into(), idx, pos) + })); let expr = FnCallExpr { #[cfg(not(feature = "no_module"))] - namespace: Default::default(), + namespace: Namespace::default(), name: state.get_interned_string(crate::engine::KEYWORD_FN_PTR_CURRY), hashes: FnCallHashes::from_native(calc_fn_hash( None, @@ -3712,15 +3708,15 @@ impl Engine { statements.push(Stmt::Share( externals .into_iter() - .map(|crate::ast::Ident { name, pos }| { + .map(|Ident { name, pos }| { let (index, _) = parent.access_var(&name, lib, pos); (name, index, pos) }) - .collect::>() + .collect::>() .into(), )); statements.push(Stmt::Expr(expr.into())); - Expr::Stmt(crate::ast::StmtBlock::new(statements, pos, Position::NONE).into()) + Expr::Stmt(StmtBlock::new(statements, pos, Position::NONE).into()) } /// Parse an anonymous function definition. @@ -3744,7 +3740,7 @@ impl Engine { match input.next().expect(NEVER_ENDS) { (Token::Pipe, ..) => break, (Token::Identifier(s), pos) => { - if params_list.iter().any(|p| p.as_str() == &*s) { + if params_list.iter().any(|p| p.as_str() == *s) { return Err( PERR::FnDuplicatedParam(String::new(), s.to_string()).into_err(pos) ); @@ -3789,11 +3785,7 @@ impl Engine { let externals: StaticVec<_> = state.external_vars.iter().cloned().collect(); let mut params = StaticVec::with_capacity(params_list.len() + externals.len()); - params.extend( - externals - .iter() - .map(|crate::ast::Ident { name, .. }| name.clone()), - ); + params.extend(externals.iter().map(|Ident { name, .. }| name.clone())); (params, externals) }; diff --git a/src/serde/metadata.rs b/src/serde/metadata.rs index 3c01613a..2481c028 100644 --- a/src/serde/metadata.rs +++ b/src/serde/metadata.rs @@ -174,10 +174,10 @@ pub fn gen_metadata_to_json( global.modules.insert(name, m.as_ref().into()); } - let exclude_flags = if !include_standard_packages { - ModuleFlags::STANDARD_LIB - } else { + let exclude_flags = if include_standard_packages { ModuleFlags::empty() + } else { + ModuleFlags::STANDARD_LIB }; engine diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 6c7e460a..df776d9b 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -590,6 +590,7 @@ pub enum Token { impl fmt::Display for Token { #[inline(always)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -619,6 +620,7 @@ impl Token { /// Is the token a literal symbol? #[must_use] pub const fn is_literal(&self) -> bool { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -648,6 +650,7 @@ impl Token { /// Panics if the token is not a literal symbol. #[must_use] pub const fn literal_syntax(&self) -> &'static str { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -824,6 +827,7 @@ impl Token { /// Reverse lookup a symbol token from a piece of syntax. #[must_use] pub fn lookup_symbol_from_syntax(syntax: &str) -> Option { + #[allow(clippy::enum_glob_use)] use Token::*; Some(match syntax { @@ -963,6 +967,7 @@ impl Token { /// (not sure about `fn` name). #[must_use] pub const fn is_next_unary(&self) -> bool { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -1034,6 +1039,7 @@ impl Token { /// Get the precedence number of the token. #[must_use] pub const fn precedence(&self) -> Option { + #[allow(clippy::enum_glob_use)] use Token::*; Precedence::new(match self { @@ -1066,6 +1072,7 @@ impl Token { /// Does an expression bind to the right (instead of left)? #[must_use] pub const fn is_bind_right(&self) -> bool { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -1079,6 +1086,7 @@ impl Token { /// Is this token a standard symbol used in the language? #[must_use] pub const fn is_standard_symbol(&self) -> bool { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -1105,6 +1113,7 @@ impl Token { #[inline] #[must_use] pub const fn is_standard_keyword(&self) -> bool { + #[allow(clippy::enum_glob_use)] use Token::*; match self { @@ -1501,13 +1510,13 @@ pub fn get_next_token( /// Test if the given character is a hex character. #[inline(always)] -fn is_hex_digit(c: char) -> bool { +const fn is_hex_digit(c: char) -> bool { matches!(c, 'a'..='f' | 'A'..='F' | '0'..='9') } /// Test if the given character is a numeric digit. #[inline(always)] -fn is_numeric_digit(c: char) -> bool { +const fn is_numeric_digit(c: char) -> bool { matches!(c, '0'..='9') } @@ -1687,21 +1696,8 @@ fn get_next_token_inner( }); // Parse number - return Some(( - if let Some(radix) = radix_base { - let result = &result[2..]; - - UNSIGNED_INT::from_str_radix(&result, radix) - .map(|v| v as INT) - .map_or_else( - |_| { - Token::LexError( - LERR::MalformedNumber(result.to_string()).into(), - ) - }, - Token::IntegerConstant, - ) - } else { + let token = radix_base.map_or_else( + || { let num = INT::from_str(&result).map(Token::IntegerConstant); // If integer parsing is unnecessary, try float instead @@ -1730,8 +1726,23 @@ fn get_next_token_inner( Token::LexError(LERR::MalformedNumber(result.to_string()).into()) }) }, - num_pos, - )); + |radix| { + let result = &result[2..]; + + UNSIGNED_INT::from_str_radix(result, radix) + .map(|v| v as INT) + .map_or_else( + |_| { + Token::LexError( + LERR::MalformedNumber(result.to_string()).into(), + ) + }, + Token::IntegerConstant, + ) + }, + ); + + return Some((token, num_pos)); } // letter or underscore ... @@ -1760,7 +1771,7 @@ fn get_next_token_inner( Some('\r') => { eat_next(stream, pos); // `\r\n - if let Some('\n') = stream.peek_next() { + if stream.peek_next() == Some('\n') { eat_next(stream, pos); } pos.new_line(); @@ -1788,7 +1799,7 @@ fn get_next_token_inner( // ' - character literal ('\'', '\'') => { return Some(( - Token::LexError(LERR::MalformedChar("".to_string()).into()), + Token::LexError(LERR::MalformedChar(String::new()).into()), start_pos, )) } @@ -1941,7 +1952,7 @@ fn get_next_token_inner( while let Some(c) = stream.get_next() { if c == '\r' { // \r\n - if let Some('\n') = stream.peek_next() { + if stream.peek_next() == Some('\n') { eat_next(stream, pos); } pos.new_line(); diff --git a/src/types/bloom_filter.rs b/src/types/bloom_filter.rs index 9400879b..51be6f3f 100644 --- a/src/types/bloom_filter.rs +++ b/src/types/bloom_filter.rs @@ -105,7 +105,7 @@ impl Add for &BloomFilterU64 { impl AddAssign for BloomFilterU64 { #[inline(always)] fn add_assign(&mut self, rhs: Self) { - *self += &rhs + *self += &rhs; } } diff --git a/src/types/dynamic.rs b/src/types/dynamic.rs index 175b293f..686b2ee6 100644 --- a/src/types/dynamic.rs +++ b/src/types/dynamic.rs @@ -158,7 +158,7 @@ impl<'d, T: Any + Clone> Deref for DynamicWriteLock<'d, T> { #[inline] fn deref(&self) -> &Self::Target { match self.0 { - DynamicWriteLockInner::Reference(ref reference) => *reference, + DynamicWriteLockInner::Reference(ref reference) => reference, #[cfg(not(feature = "no_closure"))] DynamicWriteLockInner::Guard(ref guard) => guard.downcast_ref().expect(CHECKED), } @@ -169,7 +169,7 @@ impl<'d, T: Any + Clone> DerefMut for DynamicWriteLock<'d, T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { match self.0 { - DynamicWriteLockInner::Reference(ref mut reference) => *reference, + DynamicWriteLockInner::Reference(ref mut reference) => reference, #[cfg(not(feature = "no_closure"))] DynamicWriteLockInner::Guard(ref mut guard) => guard.downcast_mut().expect(CHECKED), } @@ -640,6 +640,7 @@ impl fmt::Debug for Dynamic { } } +#[allow(clippy::enum_glob_use)] use AccessMode::*; impl Clone for Dynamic { @@ -1088,7 +1089,7 @@ impl Dynamic { pub fn from(value: T) -> Self { // Coded this way in order to maximally leverage potentials for dead-code removal. - reify!(value, |v: Dynamic| return v); + reify!(value, |v: Self| return v); reify!(value, |v: INT| return v.into()); #[cfg(not(feature = "no_float"))] @@ -1187,7 +1188,7 @@ impl Dynamic { #[cfg(not(feature = "no_closure"))] self.flatten_in_place(); - if TypeId::of::() == TypeId::of::() { + if TypeId::of::() == TypeId::of::() { return Some(reify!(self => T)); } if TypeId::of::() == TypeId::of::<()>() { @@ -1309,7 +1310,7 @@ impl Dynamic { #[must_use] pub fn cast(self) -> T { // Bail out early if the return type needs no cast - if TypeId::of::() == TypeId::of::() { + if TypeId::of::() == TypeId::of::() { return reify!(self => T); } @@ -1408,9 +1409,9 @@ impl Dynamic { *self = crate::func::shared_try_take(cell).map_or_else( |ref cell| crate::func::locked_read(cell).clone(), #[cfg(not(feature = "sync"))] - |value| value.into_inner(), + crate::Locked::into_inner, #[cfg(feature = "sync")] - |value| value.into_inner().unwrap(), + crate::Locked::into_inner().unwrap(), ); } _ => (), diff --git a/src/types/error.rs b/src/types/error.rs index 411e4ed1..bc65040b 100644 --- a/src/types/error.rs +++ b/src/types/error.rs @@ -299,10 +299,7 @@ impl EvalAltResult { #[inline(never)] #[must_use] pub const fn is_pseudo_error(&self) -> bool { - match self { - Self::LoopBreak(..) | Self::Return(..) => true, - _ => false, - } + matches!(self, Self::LoopBreak(..) | Self::Return(..)) } /// Can this error be caught? #[cold] @@ -357,20 +354,17 @@ impl EvalAltResult { #[inline(never)] #[must_use] pub const fn is_system_exception(&self) -> bool { - match self { - Self::ErrorSystem(..) => true, - Self::ErrorParsing(..) => true, - - Self::ErrorCustomSyntax(..) - | Self::ErrorTooManyOperations(..) - | Self::ErrorTooManyModules(..) - | Self::ErrorStackOverflow(..) - | Self::ErrorDataTooLarge(..) => true, - - Self::ErrorTerminated(..) => true, - - _ => false, - } + matches!( + self, + Self::ErrorSystem(..) + | Self::ErrorParsing(..) + | Self::ErrorCustomSyntax(..) + | Self::ErrorTooManyOperations(..) + | Self::ErrorTooManyModules(..) + | Self::ErrorStackOverflow(..) + | Self::ErrorDataTooLarge(..) + | Self::ErrorTerminated(..) + ) } /// Get the [position][Position] of this error. #[cfg(not(feature = "no_object"))] @@ -459,7 +453,6 @@ impl EvalAltResult { /// Unwrap this error and get the very base error. #[cold] #[inline(never)] - #[must_use] pub fn unwrap_inner(&self) -> &Self { match self { Self::ErrorInFunctionCall(.., err, _) | Self::ErrorInModule(.., err, _) => { diff --git a/src/types/float.rs b/src/types/float.rs index a3b934a6..8cfeed77 100644 --- a/src/types/float.rs +++ b/src/types/float.rs @@ -14,7 +14,7 @@ use num_traits::float::FloatCore as Float; /// A type that wraps a floating-point number and implements [`Hash`]. /// /// Not available under `no_float`. -#[derive(Clone, Copy, PartialEq, PartialOrd)] +#[derive(Clone, Copy, Eq, PartialEq, PartialOrd)] pub struct FloatWrapper(F); impl Hash for FloatWrapper { diff --git a/src/types/immutable_string.rs b/src/types/immutable_string.rs index f6dba61a..0d251081 100644 --- a/src/types/immutable_string.rs +++ b/src/types/immutable_string.rs @@ -147,7 +147,6 @@ impl FromStr for ImmutableString { type Err = (); #[inline(always)] - #[must_use] fn from_str(s: &str) -> Result { let s: SmartString = s.into(); Ok(Self(s.into())) diff --git a/src/types/parse_error.rs b/src/types/parse_error.rs index 86fedfdf..1457a1c4 100644 --- a/src/types/parse_error.rs +++ b/src/types/parse_error.rs @@ -175,7 +175,6 @@ impl ParseErrorType { /// Make a [`ParseError`] using the current type and position. #[cold] #[inline(never)] - #[must_use] pub(crate) fn into_err(self, pos: Position) -> ParseError { ParseError(self.into(), pos) } @@ -299,7 +298,6 @@ impl ParseError { /// Get the [type][ParseErrorType] of this parse error. #[cold] #[inline(never)] - #[must_use] pub const fn err_type(&self) -> &ParseErrorType { &self.0 } @@ -316,7 +314,7 @@ impl From for RhaiError { #[cold] #[inline(never)] fn from(err: ParseErrorType) -> Self { - Box::new(err.into()) + Self::new(err.into()) } } @@ -332,7 +330,7 @@ impl From for RhaiError { #[cold] #[inline(never)] fn from(err: ParseError) -> Self { - Box::new(err.into()) + Self::new(err.into()) } }