浏览代码

Run `cargo clippy --fix` on codebase

0xadk 1 年之前
父节点
当前提交
416586c372

+ 8 - 9
numbat-cli/src/main.rs

@@ -125,7 +125,7 @@ impl Cli {
 
         let importer = ChainedImporter::new(
             Box::new(fs_importer),
-            Box::new(BuiltinModuleImporter::default()),
+            Box::<BuiltinModuleImporter>::default(),
         );
 
         let mut context = Context::new(importer);
@@ -196,10 +196,11 @@ impl Cli {
                 ))?,
                 CodeSource::File(path.clone()),
             ))
-        } else if let Some(exprs) = &self.args.expression {
-            Some((exprs.iter().join("\n"), CodeSource::Text))
         } else {
-            None
+            self.args
+                .expression
+                .as_ref()
+                .map(|exprs| (exprs.iter().join("\n"), CodeSource::Text))
         };
 
         if let Some((code, code_source)) = code_and_source {
@@ -446,12 +447,10 @@ impl Cli {
             if !system_module_path.is_empty() {
                 paths.push(system_module_path.into());
             }
+        } else if cfg!(unix) {
+            paths.push("/usr/share/numbat/modules".into());
         } else {
-            if cfg!(unix) {
-                paths.push("/usr/share/numbat/modules".into());
-            } else {
-                paths.push("C:\\Program Files\\numbat\\modules".into());
-            }
+            paths.push("C:\\Program Files\\numbat\\modules".into());
         }
         paths
     }

+ 1 - 1
numbat-exchange-rates/src/lib.rs

@@ -8,7 +8,7 @@ pub type ExchangeRates = HashMap<String, f64>;
 pub fn parse_exchange_rates(xml_content: &str) -> Option<ExchangeRates> {
     let mut rates = ExchangeRates::default();
 
-    let mut reader = Reader::from_str(&xml_content);
+    let mut reader = Reader::from_str(xml_content);
     loop {
         match reader.read_event().ok()? {
             Event::Eof => break,

+ 1 - 1
numbat/src/diagnostic.rs

@@ -34,7 +34,7 @@ impl ErrorDiagnostic for ResolverError {
                     .diagnostic_label(LabelStyle::Primary)
                     .with_message("Unknown module")])],
             ResolverError::ParseErrors(errors) => {
-                errors.into_iter().flat_map(|e| e.diagnostics()).collect()
+                errors.iter().flat_map(|e| e.diagnostics()).collect()
             }
         }
     }

+ 2 - 2
numbat/src/ffi.rs

@@ -299,7 +299,7 @@ pub(crate) fn functions() -> &'static HashMap<String, ForeignFunction> {
         );
 
         m.insert(
-            format!("exchange_rate"),
+            "exchange_rate".to_string(),
             ForeignFunction {
                 name: "exchange_rate".into(),
                 arity: 1..=1,
@@ -331,7 +331,7 @@ pub(crate) fn functions() -> &'static HashMap<String, ForeignFunction> {
 fn print(ctx: &mut ExecutionContext, args: &[Value]) -> ControlFlow {
     assert!(args.len() <= 1);
 
-    if args.len() == 0 {
+    if args.is_empty() {
         (ctx.print_fn)(&crate::markup::text(""))
     } else {
         match &args[0] {

+ 2 - 2
numbat/src/interpreter.rs

@@ -61,7 +61,7 @@ impl InterpreterResult {
                             m::empty()
                         } else {
                             m::dimmed("    [")
-                                + e.get_type().to_readable_type(&registry)
+                                + e.get_type().to_readable_type(registry)
                                 + m::dimmed("]")
                         }
                     } else {
@@ -84,7 +84,7 @@ impl InterpreterResult {
 
 pub type Result<T> = std::result::Result<T, RuntimeError>;
 
-pub type PrintFunction = dyn FnMut(&Markup) -> () + Send;
+pub type PrintFunction = dyn FnMut(&Markup) + Send;
 
 pub struct InterpreterSettings {
     pub print_fn: Box<PrintFunction>,

+ 1 - 2
numbat/src/lib.rs

@@ -161,8 +161,7 @@ impl Context {
         output += m::text("List of units:") + m::nl();
         for unit_names in units {
             output += m::whitespace("  ")
-                + itertools::intersperse(unit_names.iter().map(|n| m::unit(n)), m::text(", "))
-                    .sum()
+                + itertools::intersperse(unit_names.iter().map(m::unit), m::text(", ")).sum()
                 + m::nl();
         }
         output += m::nl();

+ 1 - 1
numbat/src/markup.rs

@@ -51,7 +51,7 @@ impl std::ops::Add for Markup {
 
 impl std::ops::AddAssign for Markup {
     fn add_assign(&mut self, rhs: Self) {
-        self.0.extend(rhs.0.into_iter())
+        self.0.extend(rhs.0)
     }
 }
 

+ 2 - 5
numbat/src/parser.rs

@@ -1156,10 +1156,7 @@ impl<'a> Parser<'a> {
                 ));
             }
 
-            parts = parts
-                .into_iter()
-                .filter(|p| !matches!(p, StringPart::Fixed(s) if s.is_empty()))
-                .collect();
+            parts.retain(|p| !matches!(p, StringPart::Fixed(s) if s.is_empty()));
 
             Ok(Expression::String(span_full_string, parts))
         } else if self.match_exact(TokenKind::LeftParen).is_some() {
@@ -1399,7 +1396,7 @@ impl<'a> Parser<'a> {
 }
 
 fn strip_first_and_last(s: &str) -> String {
-    (&s[1..(s.len() - 1)]).to_string()
+    s[1..(s.len() - 1)].to_string()
 }
 
 /// Parse a string.

+ 1 - 2
numbat/src/registry.rs

@@ -136,8 +136,7 @@ impl<Metadata: Clone> Registry<Metadata> {
     }
 
     pub fn contains(&self, name: &str) -> bool {
-        self.base_entries.iter().find(|(n, _)| n == name).is_some()
-            || self.derived_entries.contains_key(name)
+        self.base_entries.iter().any(|(n, _)| n == name) || self.derived_entries.contains_key(name)
     }
 
     pub fn get_base_representation_for_name(

+ 16 - 18
numbat/src/typechecker.rs

@@ -412,7 +412,7 @@ impl TypeChecker {
                     self.identifiers
                         .keys()
                         .map(|k| k.as_str())
-                        .chain(["true", "false"].into_iter()), // These are parsed as keywords, but can act like identifiers
+                        .chain(["true", "false"]), // These are parsed as keywords, but can act like identifiers
                     name,
                 );
                 TypeCheckError::UnknownIdentifier(span, name.into(), suggestion)
@@ -567,16 +567,14 @@ impl TypeChecker {
                         let rhs_type = rhs_checked.get_type();
                         if lhs_type.is_dtype() || rhs_type.is_dtype() {
                             let _ = get_type_and_assert_equality()?;
-                        } else {
-                            if lhs_type != rhs_type {
-                                return Err(TypeCheckError::IncompatibleTypesInComparison(
-                                    span_op.unwrap(),
-                                    lhs_type,
-                                    lhs.full_span(),
-                                    rhs_type,
-                                    rhs.full_span(),
-                                ));
-                            }
+                        } else if lhs_type != rhs_type {
+                            return Err(TypeCheckError::IncompatibleTypesInComparison(
+                                span_op.unwrap(),
+                                lhs_type,
+                                lhs.full_span(),
+                                rhs_type,
+                                rhs.full_span(),
+                            ));
                         }
 
                         Type::Boolean
@@ -786,7 +784,7 @@ impl TypeChecker {
             ast::Expression::String(span, parts) => typed_ast::Expression::String(
                 *span,
                 parts
-                    .into_iter()
+                    .iter()
                     .map(|p| match p {
                         StringPart::Fixed(s) => Ok(typed_ast::StringPart::Fixed(s.clone())),
                         StringPart::Interpolation(span, expr) => {
@@ -848,7 +846,7 @@ impl TypeChecker {
             } => {
                 // Make sure that identifier does not clash with a function name. We do not
                 // check for clashes with unit names, as this is handled by the prefix parser.
-                if let Some(ref signature) = self.function_signatures.get(identifier) {
+                if let Some(signature) = self.function_signatures.get(identifier) {
                     return Err(TypeCheckError::NameAlreadyUsedBy(
                         "a function",
                         *identifier_span,
@@ -880,7 +878,7 @@ impl TypeChecker {
                                         actual_name_for_fix: "right hand side expression",
                                         actual_dimensions: self
                                             .registry
-                                            .get_derived_entry_names_for(&dexpr_deduced),
+                                            .get_derived_entry_names_for(dexpr_deduced),
                                         actual_type: dexpr_deduced.clone(),
                                     },
                                 ));
@@ -1021,11 +1019,11 @@ impl TypeChecker {
                     return Err(TypeCheckError::NameAlreadyUsedBy(
                         "a constant",
                         *function_name_span,
-                        span.clone(),
+                        *span,
                     ));
                 }
 
-                if let Some(ref signature) = self.function_signatures.get(function_name) {
+                if let Some(signature) = self.function_signatures.get(function_name) {
                     if signature.is_foreign {
                         return Err(TypeCheckError::NameAlreadyUsedBy(
                             "a foreign function",
@@ -1319,7 +1317,7 @@ impl TypeChecker {
                     ProcedureKind::AssertEq => {
                         let type_first = dtype(&checked_args[0])?;
                         for arg in &checked_args[1..] {
-                            let type_arg = dtype(&arg)?;
+                            let type_arg = dtype(arg)?;
                             if type_arg != type_first {
                                 return Err(TypeCheckError::IncompatibleTypesInAssertEq(
                                     *span,
@@ -1364,7 +1362,7 @@ impl TypeChecker {
         match annotation {
             TypeAnnotation::DimensionExpression(dexpr) => self
                 .registry
-                .get_base_representation(&dexpr)
+                .get_base_representation(dexpr)
                 .map(Type::Dimension)
                 .map_err(TypeCheckError::RegistryError),
             TypeAnnotation::Bool(_) => Ok(Type::Boolean),

+ 6 - 7
numbat/src/typed_ast.rs

@@ -31,11 +31,10 @@ impl DType {
         match &names[..] {
             [] => self.pretty_print(),
             [single] => m::type_identifier(single),
-            ref multiple => Itertools::intersperse(
-                multiple.iter().map(|n| m::type_identifier(n)),
-                m::dimmed(" or "),
-            )
-            .sum(),
+            multiple => {
+                Itertools::intersperse(multiple.iter().map(m::type_identifier), m::dimmed(" or "))
+                    .sum()
+            }
         }
     }
 }
@@ -542,11 +541,11 @@ impl PrettyPrint for Expression {
             Condition(_, condition, then, else_) => {
                 m::keyword("if")
                     + m::space()
-                    + with_parens(&condition)
+                    + with_parens(condition)
                     + m::space()
                     + m::keyword("then")
                     + m::space()
-                    + with_parens(&then)
+                    + with_parens(then)
                     + m::space()
                     + m::keyword("else")
                     + m::space()

+ 1 - 1
numbat/src/value.rs

@@ -10,7 +10,7 @@ pub enum Value {
 impl Value {
     pub fn unsafe_as_quantity(&self) -> &Quantity {
         if let Value::Quantity(q) = self {
-            &q
+            q
         } else {
             panic!("Expected value to be a quantity");
         }

+ 5 - 5
numbat/src/vm.rs

@@ -399,7 +399,7 @@ impl Vm {
             return;
         }
 
-        eprintln!("");
+        eprintln!();
         eprintln!(".CONSTANTS");
         for (idx, constant) in self.constants.iter().enumerate() {
             eprintln!("  {:04} {}", idx, constant);
@@ -593,9 +593,9 @@ impl Vm {
                         Op::Add => &lhs + &rhs,
                         Op::Subtract => &lhs - &rhs,
                         Op::Multiply => Ok(lhs * rhs),
-                        Op::Divide => Ok(lhs
-                            .checked_div(rhs)
-                            .ok_or_else(|| RuntimeError::DivisionByZero)?),
+                        Op::Divide => {
+                            Ok(lhs.checked_div(rhs).ok_or(RuntimeError::DivisionByZero)?)
+                        }
                         Op::Power => lhs.power(rhs),
                         Op::ConvertTo => lhs.convert_to(rhs.unit()),
                         _ => unreachable!(),
@@ -779,7 +779,7 @@ impl Vm {
     }
 
     fn print(&self, ctx: &mut ExecutionContext, m: &Markup) {
-        (ctx.print_fn)(&m);
+        (ctx.print_fn)(m);
     }
 }