From 72838cc0837826777fa4921b32852fbb09b6a5e4 Mon Sep 17 00:00:00 2001 From: Jonathan Turner Date: Tue, 31 Dec 2019 20:36:08 +1300 Subject: [PATCH] Move to using clippy (#1142) * Clippy fixes * Finish converting to use clippy * fix warnings in new master * fix windows * fix windows Co-authored-by: Artem Vorotnikov --- .azure/azure-pipelines.yml | 6 + crates/nu-build/src/lib.rs | 6 +- crates/nu-errors/src/lib.rs | 20 ++-- .../src/commands/classified/external.rs | 2 +- .../nu-parser/src/hir/baseline_parse/tests.rs | 4 +- .../src/hir/expand_external_tokens.rs | 2 +- crates/nu-parser/src/hir/named.rs | 8 +- crates/nu-parser/src/hir/signature.rs | 30 ++--- crates/nu-parser/src/hir/syntax_shape.rs | 16 +-- .../nu-parser/src/hir/syntax_shape/block.rs | 68 ++++------- .../src/hir/syntax_shape/expression.rs | 50 ++++---- .../src/hir/syntax_shape/expression/atom.rs | 109 ++++++++---------- .../hir/syntax_shape/expression/delimited.rs | 2 +- .../hir/syntax_shape/expression/file_path.rs | 6 +- .../src/hir/syntax_shape/expression/list.rs | 26 ++--- .../hir/syntax_shape/expression/pattern.rs | 4 +- .../syntax_shape/expression/variable_path.rs | 39 +++---- .../src/hir/syntax_shape/flat_shape.rs | 4 +- crates/nu-parser/src/hir/tokens_iterator.rs | 32 ++--- .../src/hir/tokens_iterator/debug.rs | 8 +- .../hir/tokens_iterator/debug/color_trace.rs | 26 ++--- .../hir/tokens_iterator/debug/expand_trace.rs | 57 ++++----- crates/nu-parser/src/lib.rs | 2 + crates/nu-parser/src/parse/call_node.rs | 2 +- crates/nu-parser/src/parse/files.rs | 6 +- crates/nu-parser/src/parse/operator.rs | 12 +- crates/nu-parser/src/parse/parser.rs | 82 +++++++++---- crates/nu-parser/src/parse/token_tree.rs | 4 +- .../nu-parser/src/parse/token_tree_builder.rs | 10 +- crates/nu-parser/src/parse/unit.rs | 8 +- crates/nu-parser/src/parse_command.rs | 17 +-- crates/nu-plugin/src/plugin.rs | 4 +- crates/nu-plugin/src/test_helpers.rs | 24 ++-- crates/nu-protocol/src/call_info.rs | 8 +- crates/nu-protocol/src/maybe_owned.rs | 2 + crates/nu-protocol/src/type_shape.rs | 6 +- crates/nu-protocol/src/value.rs | 13 +-- crates/nu-protocol/src/value/column_path.rs | 4 +- crates/nu-protocol/src/value/dict.rs | 3 +- crates/nu-protocol/src/value/primitive.rs | 4 +- crates/nu-protocol/src/value/range.rs | 4 +- .../nu-protocol/src/value/serde_bigdecimal.rs | 4 +- crates/nu-protocol/src/value/serde_bigint.rs | 5 +- crates/nu-source/src/pretty.rs | 1 + crates/nu-test-support/src/fs.rs | 6 +- crates/nu-test-support/src/macros.rs | 2 +- crates/nu-test-support/src/playground.rs | 62 +++++----- crates/nu-value-ext/src/lib.rs | 28 ++--- crates/nu_plugin_binaryview/src/main.rs | 41 +++---- crates/nu_plugin_fetch/src/main.rs | 8 +- crates/nu_plugin_inc/src/inc.rs | 18 ++- .../nu_plugin_inc/src/nu_plugin_inc/tests.rs | 2 +- crates/nu_plugin_match/src/main.rs | 1 + crates/nu_plugin_post/src/main.rs | 35 +++--- crates/nu_plugin_str/src/nu_plugin_str/mod.rs | 4 +- .../nu_plugin_str/src/nu_plugin_str/tests.rs | 8 +- crates/nu_plugin_str/src/strutils.rs | 18 ++- crates/nu_plugin_textview/src/main.rs | 99 ++++++++-------- crates/nu_plugin_tree/src/main.rs | 2 +- src/cli.rs | 2 +- src/commands.rs | 8 +- src/commands/clip.rs | 2 +- src/commands/command.rs | 3 +- src/commands/evaluate_by.rs | 22 ++-- src/commands/format.rs | 9 +- src/commands/from_bson.rs | 2 +- src/commands/from_ssv.rs | 2 +- src/commands/from_xml.rs | 16 +-- src/commands/group_by.rs | 14 +-- src/commands/macros.rs | 6 +- src/commands/nth.rs | 2 +- src/commands/range.rs | 6 +- src/commands/reduce_by.rs | 4 +- src/commands/split_by.rs | 26 ++--- src/commands/t_sort_by.rs | 23 ++-- src/commands/to_delimited_data.rs | 8 +- src/commands/where_.rs | 5 +- src/data/base.rs | 54 ++++----- src/data/base/shape.rs | 2 +- src/data/value.rs | 2 +- src/deserializer.rs | 2 +- src/evaluate/evaluator.rs | 4 +- src/evaluate/operator.rs | 4 +- src/format/table.rs | 1 + src/plugins/nu_plugin_core_textview.rs | 101 ++++++++-------- src/shell.rs | 2 + src/shell/completer.rs | 67 +++++------ src/shell/filesystem_shell.rs | 104 ++++++++--------- src/shell/help_shell.rs | 4 +- src/shell/helper.rs | 2 +- src/shell/value_shell.rs | 4 +- src/utils.rs | 7 +- tests/shell/mod.rs | 2 +- 93 files changed, 754 insertions(+), 852 deletions(-) diff --git a/.azure/azure-pipelines.yml b/.azure/azure-pipelines.yml index e46375fa60..aa3cb8be6f 100644 --- a/.azure/azure-pipelines.yml +++ b/.azure/azure-pipelines.yml @@ -45,9 +45,15 @@ steps: - bash: RUSTFLAGS="-D warnings" cargo test --all --features=stable condition: eq(variables['style'], 'unflagged') displayName: Run tests + - bash: RUSTFLAGS="-D warnings" cargo clippy --all --features=stable + condition: eq(variables['style'], 'unflagged') + displayName: Check clippy lints - bash: NUSHELL_ENABLE_ALL_FLAGS=1 RUSTFLAGS="-D warnings" cargo test --all --features=stable condition: eq(variables['style'], 'canary') displayName: Run tests + - bash: NUSHELL_ENABLE_ALL_FLAGS=1 RUSTFLAGS="-D warnings" cargo clippy --all --features=stable + condition: eq(variables['style'], 'canary') + displayName: Check clippy lints - bash: cargo fmt --all -- --check condition: eq(variables['style'], 'fmt') displayName: Lint diff --git a/crates/nu-build/src/lib.rs b/crates/nu-build/src/lib.rs index eeb741382d..d42bb8f633 100644 --- a/crates/nu-build/src/lib.rs +++ b/crates/nu-build/src/lib.rs @@ -31,7 +31,7 @@ fn get_cargo_workspace(manifest_dir: &str) -> Option<&Path> { let manifest: Manifest = serde_json::from_slice(&output.stdout).unwrap(); let path = Box::leak(Box::new(PathBuf::from(manifest.workspace_root))); workspaces.insert(manifest_dir.to_string(), path.as_path()); - workspaces.get(manifest_dir).map(|w| *w) + workspaces.get(manifest_dir).cloned() } } @@ -47,7 +47,7 @@ pub fn build() -> Result<(), Box> { let all_on = env::var("NUSHELL_ENABLE_ALL_FLAGS").is_ok(); let flags: HashSet = env::var("NUSHELL_ENABLE_FLAGS") - .map(|s| s.split(",").map(|s| s.to_string()).collect()) + .map(|s| s.split(',').map(|s| s.to_string()).collect()) .unwrap_or_else(|_| HashSet::new()); if all_on && !flags.is_empty() { @@ -72,7 +72,7 @@ pub fn build() -> Result<(), Box> { let toml: HashMap = toml::from_str(&std::fs::read_to_string(path)?)?; for (key, value) in toml.iter() { - if value.enabled == true || all_on || flags.contains(key) { + if value.enabled || all_on || flags.contains(key) { println!("cargo:rustc-cfg={}", key); } } diff --git a/crates/nu-errors/src/lib.rs b/crates/nu-errors/src/lib.rs index 231a93ba95..48aa9b9acd 100644 --- a/crates/nu-errors/src/lib.rs +++ b/crates/nu-errors/src/lib.rs @@ -85,11 +85,9 @@ impl From for ShellError { fn from(error: ParseError) -> ShellError { match error.reason { ParseErrorReason::Eof { expected, span } => ShellError::unexpected_eof(expected, span), - ParseErrorReason::ExtraTokens { actual } => { - ShellError::type_error("nothing", actual.clone()) - } + ParseErrorReason::ExtraTokens { actual } => ShellError::type_error("nothing", actual), ParseErrorReason::Mismatch { actual, expected } => { - ShellError::type_error(expected, actual.clone()) + ShellError::type_error(expected, actual) } ParseErrorReason::ArgumentError { command, error } => { ShellError::argument_error(command, error) @@ -146,7 +144,7 @@ pub struct ShellError { cause: Option>, } -/// `PrettyDebug` is for internal debugging. For user-facing debugging, [to_diagnostic](ShellError::to_diagnostic) +/// `PrettyDebug` is for internal debugging. For user-facing debugging, [into_diagnostic](ShellError::into_diagnostic) /// is used, which prints an error, highlighting spans. impl PrettyDebug for ShellError { fn pretty(&self) -> DebugDocBuilder { @@ -169,7 +167,7 @@ impl PrettyDebug for ShellError { + b::space() + b::description("actual:") + b::space() - + b::option(actual.item.as_ref().map(|actual| b::description(actual))), + + b::option(actual.item.as_ref().map(b::description)), ")", ) } @@ -388,13 +386,13 @@ impl ShellError { // TODO: Get span of EOF let diagnostic = Diagnostic::new( Severity::Error, - format!("Parse Error: Unexpected end of line"), + "Parse Error: Unexpected end of line".to_string(), ); ShellError::diagnostic(diagnostic) } nom::Err::Failure(span) | nom::Err::Error(span) => { - let diagnostic = Diagnostic::new(Severity::Error, format!("Parse Error")) + let diagnostic = Diagnostic::new(Severity::Error, "Parse Error".to_string()) .with_label(Label::new_primary(Span::from(span.0))); ShellError::diagnostic(diagnostic) @@ -406,7 +404,7 @@ impl ShellError { ProximateShellError::Diagnostic(ShellDiagnostic { diagnostic }).start() } - pub fn to_diagnostic(self) -> Diagnostic { + pub fn into_diagnostic(self) -> Diagnostic { match self.error { ProximateShellError::MissingValue { span, reason } => { let mut d = Diagnostic::new( @@ -426,7 +424,7 @@ impl ShellError { } => match error { ArgumentError::InvalidExternalWord => Diagnostic::new( Severity::Error, - format!("Invalid bare word for Nu command (did you intend to invoke an external command?)")) + "Invalid bare word for Nu command (did you intend to invoke an external command?)".to_string()) .with_label(Label::new_primary(command.span)), ArgumentError::MissingMandatoryFlag(name) => Diagnostic::new( Severity::Error, @@ -483,7 +481,7 @@ impl ShellError { ProximateShellError::UnexpectedEof { expected, span - } => Diagnostic::new(Severity::Error, format!("Unexpected end of input")) + } => Diagnostic::new(Severity::Error, "Unexpected end of input".to_string()) .with_label(Label::new_primary(span).with_message(format!("Expected {}", expected))), ProximateShellError::RangeError { diff --git a/crates/nu-parser/src/commands/classified/external.rs b/crates/nu-parser/src/commands/classified/external.rs index fd71291418..e776953da5 100644 --- a/crates/nu-parser/src/commands/classified/external.rs +++ b/crates/nu-parser/src/commands/classified/external.rs @@ -50,7 +50,7 @@ impl PrettyDebug for ExternalCommand { + b::preceded( b::space(), b::intersperse( - self.args.iter().map(|a| b::primitive(format!("{}", a.arg))), + self.args.iter().map(|a| b::primitive(a.arg.to_string())), b::space(), ), ), diff --git a/crates/nu-parser/src/hir/baseline_parse/tests.rs b/crates/nu-parser/src/hir/baseline_parse/tests.rs index 71e013d345..82fa9627a1 100644 --- a/crates/nu-parser/src/hir/baseline_parse/tests.rs +++ b/crates/nu-parser/src/hir/baseline_parse/tests.rs @@ -107,7 +107,7 @@ impl SignatureRegistry for TestRegistry { self.signatures.contains_key(name) } fn get(&self, name: &str) -> Option { - self.signatures.get(name).map(|sig| sig.clone()) + self.signatures.get(name).cloned() } } @@ -159,7 +159,7 @@ fn inner_string_span(span: Span) -> Span { } pub fn print_err(err: ShellError, source: &Text) { - let diag = err.to_diagnostic(); + let diag = err.into_diagnostic(); let writer = termcolor::StandardStream::stderr(termcolor::ColorChoice::Auto); let mut source = source.to_string(); diff --git a/crates/nu-parser/src/hir/expand_external_tokens.rs b/crates/nu-parser/src/hir/expand_external_tokens.rs index c9f9be4b5e..f390415a24 100644 --- a/crates/nu-parser/src/hir/expand_external_tokens.rs +++ b/crates/nu-parser/src/hir/expand_external_tokens.rs @@ -295,7 +295,7 @@ impl ColorSyntax for ExternalExpressionShape { }; token_nodes.mutate_shapes(|shapes| atom.color_tokens(shapes)); - return ExternalExpressionResult::Processed; + ExternalExpressionResult::Processed } } diff --git a/crates/nu-parser/src/hir/named.rs b/crates/nu-parser/src/hir/named.rs index a30fdac7ea..cc0290e573 100644 --- a/crates/nu-parser/src/hir/named.rs +++ b/crates/nu-parser/src/hir/named.rs @@ -24,16 +24,14 @@ impl PrettyDebugWithSource for NamedValue { } } -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct NamedArguments { pub named: IndexMap, } impl NamedArguments { pub fn new() -> NamedArguments { - NamedArguments { - named: IndexMap::new(), - } + Default::default() } pub fn iter(&self) -> impl Iterator { @@ -47,7 +45,7 @@ impl NamedArguments { trace!("Inserting switch -- {} = {:?}", name, switch); match switch { - None => self.named.insert(name.into(), NamedValue::AbsentSwitch), + None => self.named.insert(name, NamedValue::AbsentSwitch), Some(flag) => self.named.insert( name, NamedValue::PresentSwitch(Tag { diff --git a/crates/nu-parser/src/hir/signature.rs b/crates/nu-parser/src/hir/signature.rs index bf6278cb2b..50e80b51bc 100644 --- a/crates/nu-parser/src/hir/signature.rs +++ b/crates/nu-parser/src/hir/signature.rs @@ -111,15 +111,12 @@ impl ExpandSyntax for KeywordShape { ) -> Result { let atom = expand_atom(token_nodes, "keyword", context, ExpansionRule::new())?; - match &atom.unspanned { - UnspannedAtomicToken::Word { text } => { - let word = text.slice(context.source()); + if let UnspannedAtomicToken::Word { text } = &atom.unspanned { + let word = text.slice(context.source()); - if word == self.keyword { - return Ok(atom.span); - } + if word == self.keyword { + return Ok(atom.span); } - _ => {} } Err(ParseError::mismatch(self.keyword, atom.spanned_type_name())) @@ -338,17 +335,14 @@ impl ExpandSyntax for IdentifierShape { ) -> Result { let atom = expand_atom(token_nodes, "identifier", context, ExpansionRule::new())?; - match atom.unspanned { - UnspannedAtomicToken::Word { text } => { - let body = text.slice(context.source()); - if is_id(body) { - return Ok(Identifier { - body: body.to_string(), - span: text, - }); - } + if let UnspannedAtomicToken::Word { text } = atom.unspanned { + let body = text.slice(context.source()); + if is_id(body) { + return Ok(Identifier { + body: body.to_string(), + span: text, + }); } - _ => {} } Err(ParseError::mismatch("identifier", atom.spanned_type_name())) @@ -359,7 +353,7 @@ fn is_id(input: &str) -> bool { let source = nu_source::nom_input(input); match crate::parse::parser::ident(source) { Err(_) => false, - Ok((input, _)) => input.fragment.len() == 0, + Ok((input, _)) => input.fragment.is_empty(), } } diff --git a/crates/nu-parser/src/hir/syntax_shape.rs b/crates/nu-parser/src/hir/syntax_shape.rs index 7cf84faa1b..a42b1a7a78 100644 --- a/crates/nu-parser/src/hir/syntax_shape.rs +++ b/crates/nu-parser/src/hir/syntax_shape.rs @@ -732,9 +732,9 @@ impl ExpandSyntax for CommandHeadShape { }); match node { - Ok(expr) => return Ok(expr), + Ok(expr) => Ok(expr), Err(_) => match expand_expr(&AnyExpressionShape, token_nodes, context) { - Ok(expr) => return Ok(CommandSignature::Expression(expr)), + Ok(expr) => Ok(CommandSignature::Expression(expr)), Err(_) => Err(token_nodes.peek_non_ws().type_error("command head3")), }, } @@ -834,7 +834,7 @@ impl FallibleColorSyntax for InternalCommandHeadShape { let node = peeked_head.commit(); - let _expr = match node { + match node { TokenNode::Token(Token { unspanned: UnspannedToken::Bare, span, @@ -904,8 +904,8 @@ impl<'token> SingleError<'token> { } } -fn parse_single_node<'a, 'b, T>( - token_nodes: &'b mut TokensIterator<'a>, +fn parse_single_node( + token_nodes: &mut TokensIterator<'_>, expected: &'static str, callback: impl FnOnce(UnspannedToken, Span, SingleError) -> Result, ) -> Result { @@ -926,8 +926,8 @@ fn parse_single_node<'a, 'b, T>( }) } -fn parse_single_node_skipping_ws<'a, 'b, T>( - token_nodes: &'b mut TokensIterator<'a>, +fn parse_single_node_skipping_ws( + token_nodes: &mut TokensIterator<'_>, expected: &'static str, callback: impl FnOnce(UnspannedToken, Span, SingleError) -> Result, ) -> Result { @@ -982,7 +982,7 @@ impl FallibleColorSyntax for WhitespaceShape { let node = peeked.commit(); - let _ = match node { + match node { TokenNode::Whitespace(span) => { token_nodes.color_shape(FlatShape::Whitespace.spanned(*span)) } diff --git a/crates/nu-parser/src/hir/syntax_shape/block.rs b/crates/nu-parser/src/hir/syntax_shape/block.rs index d37db7fea3..788fddbc8d 100644 --- a/crates/nu-parser/src/hir/syntax_shape/block.rs +++ b/crates/nu-parser/src/hir/syntax_shape/block.rs @@ -39,21 +39,17 @@ impl FallibleColorSyntax for AnyBlockShape { // is it just a block? let block = block.node.as_block(); - match block { - // If so, color it as a block - Some((children, spans)) => { - token_nodes.child(children, context.source.clone(), |token_nodes| { - color_syntax_with( - &DelimitedShape, - &(Delimiter::Brace, spans.0, spans.1), - token_nodes, - context, - ); - }); + if let Some((children, spans)) = block { + token_nodes.child(children, context.source.clone(), |token_nodes| { + color_syntax_with( + &DelimitedShape, + &(Delimiter::Brace, spans.0, spans.1), + token_nodes, + context, + ); + }); - return Ok(()); - } - _ => {} + return Ok(()); } // Otherwise, look for a shorthand block. If none found, fail @@ -76,16 +72,13 @@ impl ExpandExpression for AnyBlockShape { // is it just a block? let block = block.node.as_block(); - match block { - Some((block, _tags)) => { - let mut iterator = - TokensIterator::new(&block.item, block.span, context.source.clone(), false); + if let Some((block, _tags)) = block { + let mut iterator = + TokensIterator::new(&block.item, block.span, context.source.clone(), false); - let exprs = expand_syntax(&ExpressionListShape, &mut iterator, context)?.exprs; + let exprs = expand_syntax(&ExpressionListShape, &mut iterator, context)?.exprs; - return Ok(hir::RawExpression::Block(exprs.item).into_expr(block.span)); - } - _ => {} + return Ok(hir::RawExpression::Block(exprs.item).into_expr(block.span)); } expand_syntax(&ShorthandBlock, token_nodes, context) @@ -169,30 +162,20 @@ impl FallibleColorSyntax for ShorthandPath { token_nodes.atomic(|token_nodes| { let variable = color_fallible_syntax(&VariablePathShape, token_nodes, context); - match variable { - Ok(_) => { - // if it's a variable path, that's the head part - return Ok(()); - } - - Err(_) => { - // otherwise, we'll try to find a member path - } + if variable.is_ok() { + // if it's a variable path, that's the head part + return Ok(()); } + // otherwise, we'll try to find a member path + // look for a member (`` -> `$it.`) color_fallible_syntax(&MemberShape, token_nodes, context)?; // Now that we've synthesized the head, of the path, proceed to expand the tail of the path // like any other path. - let tail = color_fallible_syntax(&PathTailShape, token_nodes, context); - - match tail { - Ok(_) => {} - Err(_) => { - // It's ok if there's no path tail; a single member is sufficient - } - } + // It's ok if there's no path tail; a single member is sufficient + let _ = color_fallible_syntax(&PathTailShape, token_nodes, context); Ok(()) }) @@ -212,9 +195,8 @@ impl ExpandExpression for ShorthandPath { // if it's a variable path, that's the head part let path = expand_expr(&VariablePathShape, token_nodes, context); - match path { - Ok(path) => return Ok(path), - Err(_) => {} + if let Ok(path) = path { + return Ok(path); } // Synthesize the head of the shorthand path (`` -> `$it.`) @@ -225,7 +207,7 @@ impl ExpandExpression for ShorthandPath { let tail = expand_syntax(&PathTailShape, token_nodes, context); match tail { - Err(_) => return Ok(head), + Err(_) => Ok(head), Ok(PathTailSyntax { tail, .. }) => { // For each member that `PathTailShape` expanded, join it onto the existing expression // to form a new path diff --git a/crates/nu-parser/src/hir/syntax_shape/expression.rs b/crates/nu-parser/src/hir/syntax_shape/expression.rs index 4c51b8297b..c2457920ae 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression.rs @@ -111,13 +111,9 @@ pub(crate) fn continue_coloring_expression( // Check to see whether there's any continuation after the head expression let result = color_fallible_syntax(&ExpressionContinuationShape, token_nodes, context); - match result { - Err(_) => { - // We already saw one continuation, so just return - return Ok(()); - } - - Ok(_) => {} + if result.is_err() { + // We already saw one continuation, so just return + return Ok(()); } } } @@ -138,19 +134,17 @@ impl ExpandExpression for AnyExpressionStartShape { let atom = expand_atom(token_nodes, "expression", context, ExpansionRule::new())?; match atom.unspanned { - UnspannedAtomicToken::Size { number, unit } => { - return Ok(hir::Expression::size( - number.to_number(context.source), - unit.item, - Tag { - span: atom.span, - anchor: None, - }, - )) - } + UnspannedAtomicToken::Size { number, unit } => Ok(hir::Expression::size( + number.to_number(context.source), + unit.item, + Tag { + span: atom.span, + anchor: None, + }, + )), UnspannedAtomicToken::SquareDelimited { nodes, .. } => { - expand_delimited_square(&nodes, atom.span.into(), context) + expand_delimited_square(&nodes, atom.span, context) } UnspannedAtomicToken::Word { .. } => { @@ -158,11 +152,9 @@ impl ExpandExpression for AnyExpressionStartShape { Ok(hir::Expression::bare(atom.span.until_option(end))) } - other => { - return other - .into_atomic_token(atom.span) - .into_hir(context, "expression") - } + other => other + .into_atomic_token(atom.span) + .to_hir(context, "expression"), } } } @@ -208,7 +200,7 @@ impl FallibleColorSyntax for AnyExpressionStartShape { UnspannedAtomicToken::Size { number, unit } => token_nodes.color_shape( FlatShape::Size { number: number.span(), - unit: unit.span.into(), + unit: unit.span, } .spanned(atom.span), ), @@ -218,7 +210,7 @@ impl FallibleColorSyntax for AnyExpressionStartShape { (&nodes[..]).spanned(atom.span), context.source.clone(), |tokens| { - color_delimited_square(spans, tokens, atom.span.into(), context); + color_delimited_square(spans, tokens, atom.span, context); }, ); } @@ -257,13 +249,13 @@ impl FallibleColorSyntax for BareTailShape { let word = color_fallible_syntax_with(&BareShape, &FlatShape::Word, token_nodes, context); - match word { + if word.is_ok() { // if a word was found, continue - Ok(_) => continue, - // if a word wasn't found, try to find a dot - Err(_) => {} + continue; } + // if a word wasn't found, try to find a dot + // try to find a dot let dot = color_fallible_syntax_with( &ColorableDotShape, diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/atom.rs b/crates/nu-parser/src/hir/syntax_shape/expression/atom.rs index 689c69bdd9..a2cd34a058 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/atom.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/atom.rs @@ -148,7 +148,7 @@ impl<'tokens> Deref for AtomicToken<'tokens> { } impl<'tokens> AtomicToken<'tokens> { - pub fn into_hir( + pub fn to_hir( &self, context: &ExpandContext, expected: &'static str, @@ -198,59 +198,49 @@ impl<'tokens> AtomicToken<'tokens> { pub(crate) fn color_tokens(&self, shapes: &mut Vec>) { match &self.unspanned { UnspannedAtomicToken::Eof { .. } => {} - UnspannedAtomicToken::Error { .. } => { - return shapes.push(FlatShape::Error.spanned(self.span)) - } + UnspannedAtomicToken::Error { .. } => shapes.push(FlatShape::Error.spanned(self.span)), UnspannedAtomicToken::CompareOperator { .. } => { - return shapes.push(FlatShape::CompareOperator.spanned(self.span)); + shapes.push(FlatShape::CompareOperator.spanned(self.span)) } UnspannedAtomicToken::ShorthandFlag { .. } => { - return shapes.push(FlatShape::ShorthandFlag.spanned(self.span)); + shapes.push(FlatShape::ShorthandFlag.spanned(self.span)) } UnspannedAtomicToken::Whitespace { .. } => { - return shapes.push(FlatShape::Whitespace.spanned(self.span)); + shapes.push(FlatShape::Whitespace.spanned(self.span)) } UnspannedAtomicToken::Number { number: RawNumber::Decimal(_), - } => { - return shapes.push(FlatShape::Decimal.spanned(self.span)); - } + } => shapes.push(FlatShape::Decimal.spanned(self.span)), UnspannedAtomicToken::Number { number: RawNumber::Int(_), - } => { - return shapes.push(FlatShape::Int.spanned(self.span)); - } - UnspannedAtomicToken::Size { number, unit } => { - return shapes.push( - FlatShape::Size { - number: number.span(), - unit: unit.span, - } - .spanned(self.span), - ); - } + } => shapes.push(FlatShape::Int.spanned(self.span)), + UnspannedAtomicToken::Size { number, unit } => shapes.push( + FlatShape::Size { + number: number.span(), + unit: unit.span, + } + .spanned(self.span), + ), UnspannedAtomicToken::String { .. } => { - return shapes.push(FlatShape::String.spanned(self.span)) + shapes.push(FlatShape::String.spanned(self.span)) } UnspannedAtomicToken::ItVariable { .. } => { - return shapes.push(FlatShape::ItVariable.spanned(self.span)) + shapes.push(FlatShape::ItVariable.spanned(self.span)) } UnspannedAtomicToken::Variable { .. } => { - return shapes.push(FlatShape::Variable.spanned(self.span)) + shapes.push(FlatShape::Variable.spanned(self.span)) } UnspannedAtomicToken::ExternalCommand { .. } => { - return shapes.push(FlatShape::ExternalCommand.spanned(self.span)); + shapes.push(FlatShape::ExternalCommand.spanned(self.span)) } UnspannedAtomicToken::ExternalWord { .. } => { - return shapes.push(FlatShape::ExternalWord.spanned(self.span)) + shapes.push(FlatShape::ExternalWord.spanned(self.span)) } UnspannedAtomicToken::GlobPattern { .. } => { - return shapes.push(FlatShape::GlobPattern.spanned(self.span)) + shapes.push(FlatShape::GlobPattern.spanned(self.span)) } - UnspannedAtomicToken::Word { .. } => { - return shapes.push(FlatShape::Word.spanned(self.span)) - } - _ => return shapes.push(FlatShape::Error.spanned(self.span)), + UnspannedAtomicToken::Word { .. } => shapes.push(FlatShape::Word.spanned(self.span)), + _ => shapes.push(FlatShape::Error.spanned(self.span)), } } } @@ -524,14 +514,13 @@ fn expand_atom_inner<'me, 'content>( rule: ExpansionRule, ) -> Result, ParseError> { if token_nodes.at_end() { - match rule.allow_eof { - true => { - return Ok(UnspannedAtomicToken::Eof { - span: Span::unknown(), - } - .into_atomic_token(Span::unknown())) + if rule.allow_eof { + return Ok(UnspannedAtomicToken::Eof { + span: Span::unknown(), } - false => return Err(ParseError::unexpected_eof("anything", Span::unknown())), + .into_atomic_token(Span::unknown())); + } else { + return Err(ParseError::unexpected_eof("anything", Span::unknown())); } } @@ -540,9 +529,8 @@ fn expand_atom_inner<'me, 'content>( // If treat_size_as_word, don't try to parse the head of the token stream // as a size. - match rule.treat_size_as_word { - true => {} - false => match expand_syntax(&UnitShape, token_nodes, context) { + if !rule.treat_size_as_word { + match expand_syntax(&UnitShape, token_nodes, context) { // If the head of the stream isn't a valid unit, we'll try to parse // it again next as a word Err(_) => {} @@ -552,31 +540,28 @@ fn expand_atom_inner<'me, 'content>( unit: (number, unit), span, }) => return Ok(UnspannedAtomicToken::Size { number, unit }.into_atomic_token(span)), - }, + } } - match rule.separate_members { - false => {} - true => { - let mut next = token_nodes.peek_any(); + if rule.separate_members { + let mut next = token_nodes.peek_any(); - match next.node { - Some(token) if token.is_word() => { - next.commit(); - return Ok(UnspannedAtomicToken::Word { text: token.span() } - .into_atomic_token(token.span())); - } - - Some(token) if token.is_int() => { - next.commit(); - return Ok(UnspannedAtomicToken::Number { - number: RawNumber::Int(token.span()), - } + match next.node { + Some(token) if token.is_word() => { + next.commit(); + return Ok(UnspannedAtomicToken::Word { text: token.span() } .into_atomic_token(token.span())); - } - - _ => {} } + + Some(token) if token.is_int() => { + next.commit(); + return Ok(UnspannedAtomicToken::Number { + number: RawNumber::Int(token.span()), + } + .into_atomic_token(token.span())); + } + + _ => {} } } diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/delimited.rs b/crates/nu-parser/src/hir/syntax_shape/expression/delimited.rs index e1a326639d..904b998bb3 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/delimited.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/delimited.rs @@ -6,7 +6,7 @@ use nu_errors::ParseError; use nu_source::{Span, SpannedItem, Tag}; pub fn expand_delimited_square( - children: &Vec, + children: &[TokenNode], span: Span, context: &ExpandContext, ) -> Result { diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/file_path.rs b/crates/nu-parser/src/hir/syntax_shape/expression/file_path.rs index 4f133d017c..83ceb7f403 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/file_path.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/file_path.rs @@ -74,15 +74,15 @@ impl ExpandExpression for FilePathShape { | UnspannedAtomicToken::ExternalWord { text: body } | UnspannedAtomicToken::String { body } => { let path = expand_file_path(body.slice(context.source), context); - return Ok(hir::Expression::file_path(path, atom.span)); + Ok(hir::Expression::file_path(path, atom.span)) } UnspannedAtomicToken::Number { .. } | UnspannedAtomicToken::Size { .. } => { let path = atom.span.slice(context.source); - return Ok(hir::Expression::file_path(path, atom.span)); + Ok(hir::Expression::file_path(path, atom.span)) } - _ => return atom.into_hir(context, "file path"), + _ => atom.to_hir(context, "file path"), } } } diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/list.rs b/crates/nu-parser/src/hir/syntax_shape/expression/list.rs index 91385f9316..1a857c09ca 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/list.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/list.rs @@ -120,27 +120,21 @@ impl ColorSyntax for ExpressionListShape { } } else { // Try to color the head of the stream as an expression - match color_fallible_syntax(&AnyExpressionShape, token_nodes, context) { + if color_fallible_syntax(&AnyExpressionShape, token_nodes, context).is_err() { // If no expression was found, switch to backoff coloring mode - Err(_) => { - backoff = true; - continue; - } - Ok(_) => {} + + backoff = true; + continue; } // If an expression was found, consume a space - match color_fallible_syntax(&SpaceShape, token_nodes, context) { - Err(_) => { - // If no space was found, we're either at the end or there's an error. - // Either way, switch to backoff coloring mode. If we're at the end - // it won't have any consequences. - backoff = true; - } - Ok(_) => { - // Otherwise, move on to the next expression - } + if color_fallible_syntax(&SpaceShape, token_nodes, context).is_err() { + // If no space was found, we're either at the end or there's an error. + // Either way, switch to backoff coloring mode. If we're at the end + // it won't have any consequences. + backoff = true; } + // Otherwise, move on to the next expression } } } diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/pattern.rs b/crates/nu-parser/src/hir/syntax_shape/expression/pattern.rs index 2b743d2d25..08ad4c2dee 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/pattern.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/pattern.rs @@ -68,9 +68,9 @@ impl ExpandExpression for PatternShape { | UnspannedAtomicToken::ExternalWord { text: body } | UnspannedAtomicToken::GlobPattern { pattern: body } => { let path = expand_file_path(body.slice(context.source), context); - return Ok(hir::Expression::pattern(path.to_string_lossy(), atom.span)); + Ok(hir::Expression::pattern(path.to_string_lossy(), atom.span)) } - _ => return atom.into_hir(context, "pattern"), + _ => atom.to_hir(context, "pattern"), } } } diff --git a/crates/nu-parser/src/hir/syntax_shape/expression/variable_path.rs b/crates/nu-parser/src/hir/syntax_shape/expression/variable_path.rs index a2387ae70a..b1c85138d9 100644 --- a/crates/nu-parser/src/hir/syntax_shape/expression/variable_path.rs +++ b/crates/nu-parser/src/hir/syntax_shape/expression/variable_path.rs @@ -41,9 +41,8 @@ impl ExpandExpression for VariablePathShape { let mut tail: Vec = vec![]; loop { - match DotShape.skip(token_nodes, context) { - Err(_) => break, - Ok(_) => {} + if DotShape.skip(token_nodes, context).is_err() { + break; } let member = expand_syntax(&MemberShape, token_nodes, context)?; @@ -77,17 +76,16 @@ impl FallibleColorSyntax for VariablePathShape { loop { // look for a dot at the head of a stream - let dot = color_fallible_syntax_with( + if color_fallible_syntax_with( &ColorableDotShape, &FlatShape::Dot, token_nodes, context, - ); - - // if there's no dot, we're done - match dot { - Err(_) => break, - Ok(_) => {} + ) + .is_err() + { + // if there's no dot, we're done + break; } // otherwise, look for a member, and if you don't find one, fail @@ -125,9 +123,8 @@ impl FallibleColorSyntax for PathTailShape { context, ); - match result { - Err(_) => return Ok(()), - Ok(_) => {} + if result.is_err() { + return Ok(()); } // If we've seen a dot but not a member, fail @@ -170,9 +167,8 @@ impl ExpandSyntax for PathTailShape { let mut tail: Vec = vec![]; loop { - match DotShape.skip(token_nodes, context) { - Err(_) => break, - Ok(_) => {} + if DotShape.skip(token_nodes, context).is_err() { + break; } let member = expand_syntax(&MemberShape, token_nodes, context)?; @@ -649,13 +645,12 @@ impl FallibleColorSyntax for MemberShape { let bare = color_fallible_syntax_with(&BareShape, &FlatShape::BareMember, token_nodes, context); - match bare { - Ok(_) => return Ok(()), - Err(_) => { - // If we don't have a bare word, we'll look for a string - } + if bare.is_ok() { + return Ok(()); } + // If we don't have a bare word, we'll look for a string + // Look for a string token. If we don't find one, fail color_fallible_syntax_with(&StringShape, &FlatShape::StringMember, token_nodes, context) } @@ -696,7 +691,7 @@ impl ExpandSyntax for IntMemberShape { let int = BigInt::from_str(text.slice(context.source)); match int { - Ok(int) => return Ok(Member::Int(int, text)), + Ok(int) => Ok(Member::Int(int, text)), Err(_) => Err(ParseError::mismatch("integer member", "word".spanned(text))), } } diff --git a/crates/nu-parser/src/hir/syntax_shape/flat_shape.rs b/crates/nu-parser/src/hir/syntax_shape/flat_shape.rs index 6c125ea547..11445950a5 100644 --- a/crates/nu-parser/src/hir/syntax_shape/flat_shape.rs +++ b/crates/nu-parser/src/hir/syntax_shape/flat_shape.rs @@ -35,7 +35,7 @@ pub enum FlatShape { } impl FlatShape { - pub fn from(token: &TokenNode, source: &Text, shapes: &mut Vec>) -> () { + pub fn from(token: &TokenNode, source: &Text, shapes: &mut Vec>) { match token { TokenNode::Token(token) => match token.unspanned { UnspannedToken::Number(RawNumber::Int(_)) => { @@ -84,7 +84,7 @@ impl FlatShape { } TokenNode::Pipeline(pipeline) => { for part in &pipeline.parts { - if let Some(_) = part.pipe { + if part.pipe.is_some() { shapes.push(FlatShape::Pipe.spanned(part.span())); } } diff --git a/crates/nu-parser/src/hir/tokens_iterator.rs b/crates/nu-parser/src/hir/tokens_iterator.rs index b29678ea07..792e05d76a 100644 --- a/crates/nu-parser/src/hir/tokens_iterator.rs +++ b/crates/nu-parser/src/hir/tokens_iterator.rs @@ -5,7 +5,6 @@ use self::debug::{ColorTracer, ExpandTracer}; use crate::hir::syntax_shape::FlatShape; use crate::hir::Expression; use crate::TokenNode; -#[allow(unused)] use getset::{Getters, MutGetters}; use nu_errors::{ParseError, ShellError}; use nu_protocol::SpannedTypeName; @@ -102,7 +101,7 @@ impl<'content, 'me> Peeked<'content, 'me> { } pub fn type_error(&self, expected: &'static str) -> ParseError { - peek_error(&self.node, self.iterator.eof_span(), expected) + peek_error(self.node, self.iterator.eof_span(), expected) } } @@ -130,11 +129,11 @@ impl<'content, 'me> PeekedNode<'content, 'me> { pub fn rollback(self) {} pub fn type_error(&self, expected: &'static str) -> ParseError { - peek_error(&Some(self.node), self.iterator.eof_span(), expected) + peek_error(Some(self.node), self.iterator.eof_span(), expected) } } -pub fn peek_error(node: &Option<&TokenNode>, eof_span: Span, expected: &'static str) -> ParseError { +pub fn peek_error(node: Option<&TokenNode>, eof_span: Span, expected: &'static str) -> ParseError { match node { None => ParseError::unexpected_eof(expected, eof_span), Some(node) => ParseError::mismatch(expected, node.spanned_type_name()), @@ -158,7 +157,7 @@ impl<'content> TokensIterator<'content> { shapes: vec![], }, color_tracer: ColorTracer::new(source.clone()), - expand_tracer: ExpandTracer::new(source.clone()), + expand_tracer: ExpandTracer::new(source), } } @@ -174,6 +173,10 @@ impl<'content> TokensIterator<'content> { self.state.tokens.len() } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn spanned( &mut self, block: impl FnOnce(&mut TokensIterator<'content>) -> T, @@ -233,7 +236,7 @@ impl<'content> TokensIterator<'content> { let mut color_tracer = ColorTracer::new(source.clone()); std::mem::swap(&mut color_tracer, &mut self.color_tracer); - let mut expand_tracer = ExpandTracer::new(source.clone()); + let mut expand_tracer = ExpandTracer::new(source); std::mem::swap(&mut expand_tracer, &mut self.expand_tracer); let mut iterator = TokensIterator { @@ -409,7 +412,7 @@ impl<'content> TokensIterator<'content> { let value = block(checkpoint.iterator)?; checkpoint.commit(); - return Ok(value); + Ok(value) } /// Use a checkpoint when you need to peek more than one token ahead, but can't be sure @@ -437,7 +440,7 @@ impl<'content> TokensIterator<'content> { let value = block(checkpoint.iterator)?; checkpoint.commit(); - return Ok(value); + Ok(value) } /// Use a checkpoint when you need to peek more than one token ahead, but can't be sure @@ -474,7 +477,7 @@ impl<'content> TokensIterator<'content> { checkpoint.commit(); std::mem::swap(&mut self.state.shapes, &mut shapes); - return (Ok(value), shapes); + (Ok(value), shapes) } fn eof_span(&self) -> Span { @@ -583,12 +586,12 @@ impl<'content> TokensIterator<'content> { let peeked = peeked.not_eof(expected); match peeked { - Err(err) => return Err(err), + Err(err) => Err(err), Ok(peeked) => match block(peeked.node) { - Err(err) => return Err(err), + Err(err) => Err(err), Ok(val) => { peeked.commit(); - return Ok(val); + Ok(val) } }, } @@ -658,10 +661,7 @@ fn peek<'content, 'me>( } } -fn peek_pos<'content, 'me>( - iterator: &'me TokensIterator<'content>, - skip_ws: bool, -) -> Option { +fn peek_pos(iterator: &TokensIterator<'_>, skip_ws: bool) -> Option { let state = iterator.state(); let mut to = state.index; diff --git a/crates/nu-parser/src/hir/tokens_iterator/debug.rs b/crates/nu-parser/src/hir/tokens_iterator/debug.rs index 67c6c1a3bf..b0697c6b22 100644 --- a/crates/nu-parser/src/hir/tokens_iterator/debug.rs +++ b/crates/nu-parser/src/hir/tokens_iterator/debug.rs @@ -24,13 +24,11 @@ pub(crate) fn debug_tokens(state: &TokensIteratorState, source: &str) -> Vec io::Result<()> { if self.has_only_error_descendents() { - if self.children.len() == 0 { + if self.children.is_empty() { write!( f, "{}", @@ -109,14 +109,10 @@ impl ColorFrame { fn any_child_shape(&self, predicate: impl Fn(Spanned) -> bool) -> bool { for item in &self.children { - match item { - FrameChild::Shape(shape) => { - if predicate(*shape) { - return true; - } + if let FrameChild::Shape(shape) = item { + if predicate(*shape) { + return true; } - - _ => {} } } @@ -125,14 +121,10 @@ impl ColorFrame { fn any_child_frame(&self, predicate: impl Fn(&ColorFrame) -> bool) -> bool { for item in &self.children { - match item { - FrameChild::Frame(frame) => { - if predicate(frame) { - return true; - } + if let FrameChild::Frame(frame) = item { + if predicate(frame) { + return true; } - - _ => {} } } @@ -148,7 +140,7 @@ impl ColorFrame { } fn has_only_error_descendents(&self) -> bool { - if self.children.len() == 0 { + if self.children.is_empty() { // if this frame has no children at all, it has only error descendents if this frame // is an error self.error.is_some() @@ -259,7 +251,7 @@ impl ColorTracer { let result = self.frame_stack.pop().expect("Can't pop root tracer frame"); - if self.frame_stack.len() == 0 { + if self.frame_stack.is_empty() { panic!("Can't pop root tracer frame {:#?}", self); } diff --git a/crates/nu-parser/src/hir/tokens_iterator/debug/expand_trace.rs b/crates/nu-parser/src/hir/tokens_iterator/debug/expand_trace.rs index 24d67d089b..ea99f4e445 100644 --- a/crates/nu-parser/src/hir/tokens_iterator/debug/expand_trace.rs +++ b/crates/nu-parser/src/hir/tokens_iterator/debug/expand_trace.rs @@ -19,7 +19,7 @@ impl FrameChild { fn get_error_leaf(&self) -> Option<&'static str> { match self { FrameChild::Frame(frame) if frame.error.is_some() => { - if frame.children.len() == 0 { + if frame.children.is_empty() { Some(frame.description) } else { None @@ -33,12 +33,12 @@ impl FrameChild { match self { FrameChild::Expr(expr) => TreeChild::OkExpr(expr.clone(), text.clone()), FrameChild::Result(result) => { - let result = format!("{}", result.display()); + let result = result.display(); TreeChild::OkNonExpr(result) } FrameChild::Frame(frame) => { if frame.error.is_some() { - if frame.children.len() == 0 { + if frame.children.is_empty() { TreeChild::ErrorLeaf(vec![frame.description]) } else { TreeChild::ErrorFrame(frame.to_tree_frame(text), text.clone()) @@ -67,7 +67,7 @@ impl ExprFrame { if let Some(error_leaf) = child.get_error_leaf() { errors.push(error_leaf); continue; - } else if errors.len() > 0 { + } else if !errors.is_empty() { children.push(TreeChild::ErrorLeaf(errors)); errors = vec![]; } @@ -75,7 +75,7 @@ impl ExprFrame { children.push(child.to_tree_child(text)); } - if errors.len() > 0 { + if !errors.is_empty() { children.push(TreeChild::ErrorLeaf(errors)); } @@ -115,22 +115,20 @@ impl TreeFrame { write!(f, " -> ")?; self.children[0].leaf_description(f) - } else { - if self.error.is_some() { - if self.children.len() == 0 { - write!( - f, - "{}", - Color::White.bold().on(Color::Red).paint(self.description) - ) - } else { - write!(f, "{}", Color::Red.normal().paint(self.description)) - } - } else if self.has_descendent_green() { - write!(f, "{}", Color::Green.normal().paint(self.description)) + } else if self.error.is_some() { + if self.children.is_empty() { + write!( + f, + "{}", + Color::White.bold().on(Color::Red).paint(self.description) + ) } else { - write!(f, "{}", Color::Yellow.bold().paint(self.description)) + write!(f, "{}", Color::Red.normal().paint(self.description)) } + } else if self.has_descendent_green() { + write!(f, "{}", Color::Green.normal().paint(self.description)) + } else { + write!(f, "{}", Color::Yellow.bold().paint(self.description)) } } @@ -143,14 +141,10 @@ impl TreeFrame { fn any_child_frame(&self, predicate: impl Fn(&TreeFrame) -> bool) -> bool { for item in &self.children { - match item { - TreeChild::OkFrame(frame, ..) => { - if predicate(frame) { - return true; - } + if let TreeChild::OkFrame(frame, ..) = item { + if predicate(frame) { + return true; } - - _ => {} } } @@ -209,7 +203,7 @@ impl TreeChild { Color::White .bold() .on(Color::Green) - .paint(format!("{}", result)) + .paint(result.to_string()) ), TreeChild::ErrorLeaf(desc) => { @@ -260,12 +254,7 @@ pub struct ExpandTracer { impl ExpandTracer { pub fn print(&self, source: Text) -> PrintTracer { - let root = self - .frame_stack - .iter() - .nth(0) - .unwrap() - .to_tree_frame(&source); + let root = self.frame_stack.get(0).unwrap().to_tree_frame(&source); PrintTracer { root, source } } @@ -292,7 +281,7 @@ impl ExpandTracer { fn pop_frame(&mut self) -> ExprFrame { let result = self.frame_stack.pop().expect("Can't pop root tracer frame"); - if self.frame_stack.len() == 0 { + if self.frame_stack.is_empty() { panic!("Can't pop root tracer frame"); } diff --git a/crates/nu-parser/src/lib.rs b/crates/nu-parser/src/lib.rs index 99910b64c0..a783951efb 100644 --- a/crates/nu-parser/src/lib.rs +++ b/crates/nu-parser/src/lib.rs @@ -1,3 +1,5 @@ +#![allow(clippy::large_enum_variant, clippy::type_complexity)] + pub mod commands; pub mod hir; pub mod parse; diff --git a/crates/nu-parser/src/parse/call_node.rs b/crates/nu-parser/src/parse/call_node.rs index b01d7f8945..989db440e7 100644 --- a/crates/nu-parser/src/parse/call_node.rs +++ b/crates/nu-parser/src/parse/call_node.rs @@ -30,7 +30,7 @@ impl PrettyDebugWithSource for CallNode { impl CallNode { pub fn new(head: Box, children: Vec) -> CallNode { - if children.len() == 0 { + if children.is_empty() { CallNode { head, children: None, diff --git a/crates/nu-parser/src/parse/files.rs b/crates/nu-parser/src/parse/files.rs index 4df5d48fd4..f46089ec7c 100644 --- a/crates/nu-parser/src/parse/files.rs +++ b/crates/nu-parser/src/parse/files.rs @@ -26,7 +26,7 @@ impl language_reporting::ReportingFiles for Files { } fn file_name(&self, _file: Self::FileId) -> FileName { - FileName::Verbatim(format!("shell")) + FileName::Verbatim("shell".to_string()) } fn byte_index(&self, _file: Self::FileId, _line: usize, _column: usize) -> Option { @@ -143,9 +143,7 @@ impl language_reporting::ReportingFiles for Files { fn source(&self, span: Self::Span) -> Option { trace!("source(tag={:?}) snippet={:?}", span, self.snippet); - if span.start() > span.end() { - return None; - } else if span.end() > self.snippet.len() { + if span.start() > span.end() || span.end() > self.snippet.len() { return None; } Some(span.slice(&self.snippet).to_string()) diff --git a/crates/nu-parser/src/parse/operator.rs b/crates/nu-parser/src/parse/operator.rs index a5504a6195..ed1c8b28e9 100644 --- a/crates/nu-parser/src/parse/operator.rs +++ b/crates/nu-parser/src/parse/operator.rs @@ -22,12 +22,12 @@ impl PrettyDebug for CompareOperator { } impl CompareOperator { - pub fn print(&self) -> String { + pub fn print(self) -> String { self.as_str().to_string() } - pub fn as_str(&self) -> &str { - match *self { + pub fn as_str(self) -> &'static str { + match self { CompareOperator::Equal => "==", CompareOperator::NotEqual => "!=", CompareOperator::LessThan => "<", @@ -76,12 +76,12 @@ impl PrettyDebug for EvaluationOperator { } impl EvaluationOperator { - pub fn print(&self) -> String { + pub fn print(self) -> String { self.as_str().to_string() } - pub fn as_str(&self) -> &str { - match *self { + pub fn as_str(self) -> &'static str { + match self { EvaluationOperator::Dot => ".", EvaluationOperator::DotDot => "..", } diff --git a/crates/nu-parser/src/parse/parser.rs b/crates/nu-parser/src/parse/parser.rs index f1b9fc1403..6d111ec284 100644 --- a/crates/nu-parser/src/parse/parser.rs +++ b/crates/nu-parser/src/parse/parser.rs @@ -233,13 +233,9 @@ pub fn raw_number(input: NomSpan) -> IResult { let dotdot_result = dotdot(input); - match dotdot_result { + if let Ok((dotdot_input, _)) = dotdot_result { // If we see a `..` immediately after an integer, it's a range, not a decimal - Ok((dotdot_input, _)) => { - return Ok((input, RawNumber::int(Span::new(start, input.offset)))) - } - - Err(_) => {} + return Ok((input, RawNumber::int(Span::new(start, input.offset)))); } let dot: IResult = tag(".")(input); @@ -434,10 +430,8 @@ enum SawSpecial { fn start_file_char(input: NomSpan) -> IResult> { let path_sep_result = special_file_char(input); - match path_sep_result { - Ok((input, special)) => return Ok((input, special)), - - Err(_) => {} + if let Ok((input, special)) = path_sep_result { + return Ok((input, special)); } start_filename(input).map(|(input, output)| (input, BitFlags::empty())) @@ -447,9 +441,8 @@ fn start_file_char(input: NomSpan) -> IResult> { fn continue_file_char(input: NomSpan) -> IResult> { let path_sep_result = special_file_char(input); - match path_sep_result { - Ok((input, special)) => return Ok((input, special)), - Err(_) => {} + if let Ok((input, special)) = path_sep_result { + return Ok((input, special)); } matches(is_file_char)(input).map(|(input, _)| (input, BitFlags::empty())) @@ -457,9 +450,8 @@ fn continue_file_char(input: NomSpan) -> IResult> #[tracable_parser] fn special_file_char(input: NomSpan) -> IResult> { - match matches(is_path_separator)(input) { - Ok((input, _)) => return Ok((input, BitFlags::empty() | SawSpecial::PathSeparator)), - Err(_) => {} + if let Ok((input, _)) = matches(is_path_separator)(input) { + return Ok((input, BitFlags::empty() | SawSpecial::PathSeparator)); } let (input, _) = matches(is_glob_specific_char)(input)?; @@ -667,9 +659,13 @@ pub fn spaced_token_list(input: NomSpan) -> IResult(frag: &str, neg: Option) -> i64 { match neg { None => int, - Some(_) => int * -1, + Some(_) => -int, } } @@ -1104,42 +1100,63 @@ mod tests { } #[test] - fn test_operator() { + fn test_gt_operator() { equal_tokens! { ">" -> b::token_list(vec![b::op(">")]) } + } + #[test] + fn test_gte_operator() { equal_tokens! { ">=" -> b::token_list(vec![b::op(">=")]) } + } + #[test] + fn test_lt_operator() { equal_tokens! { "<" -> b::token_list(vec![b::op("<")]) } + } + #[test] + fn test_lte_operator() { equal_tokens! { "<=" -> b::token_list(vec![b::op("<=")]) } + } + #[test] + fn test_eq_operator() { equal_tokens! { "==" -> b::token_list(vec![b::op("==")]) } + } + #[test] + fn test_ne_operator() { equal_tokens! { - - "!=" -> b::token_list(vec![b::op("!=")]) + + "!=" -> b::token_list(vec![b::op("!=")]) } + } + #[test] + fn test_sim_operator() { equal_tokens! { "=~" -> b::token_list(vec![b::op("=~")]) } + } + #[test] + fn test_nsim_operator() { equal_tokens! { "!~" -> b::token_list(vec![b::op("!~")]) @@ -1396,37 +1413,58 @@ mod tests { "git add ." -> b::token_list(vec![b::bare("git"), b::sp(), b::bare("add"), b::sp(), b::bare(".")]) } + } + #[test] + fn test_smoke_single_command_open() { equal_tokens! { "open Cargo.toml" -> b::token_list(vec![b::bare("open"), b::sp(), b::bare("Cargo"), b::dot(), b::bare("toml")]) } + } + #[test] + fn test_smoke_single_command_select() { equal_tokens! { "select package.version" -> b::token_list(vec![b::bare("select"), b::sp(), b::bare("package"), b::dot(), b::bare("version")]) } + } + #[test] + fn test_smoke_single_command_it() { equal_tokens! { "echo $it" -> b::token_list(vec![b::bare("echo"), b::sp(), b::var("it")]) } + } + #[test] + fn test_smoke_single_command_open_raw() { equal_tokens! { "open Cargo.toml --raw" -> b::token_list(vec![b::bare("open"), b::sp(), b::bare("Cargo"), b::dot(), b::bare("toml"), b::sp(), b::flag("raw")]) } + } + #[test] + fn test_smoke_single_command_open_r() { equal_tokens! { "open Cargo.toml -r" -> b::token_list(vec![b::bare("open"), b::sp(), b::bare("Cargo"), b::dot(), b::bare("toml"), b::sp(), b::shorthand("r")]) } + } + #[test] + fn test_smoke_single_command_config() { equal_tokens! { "config --set tabs 2" -> b::token_list(vec![b::bare("config"), b::sp(), b::flag("set"), b::sp(), b::bare("tabs"), b::sp(), b::int(2)]) } + } + #[test] + fn test_smoke_single_command_inc() { equal_tokens! { "inc --patch package.version" -> b::token_list( diff --git a/crates/nu-parser/src/parse/token_tree.rs b/crates/nu-parser/src/parse/token_tree.rs index 012c548b1b..e917120ca1 100644 --- a/crates/nu-parser/src/parse/token_tree.rs +++ b/crates/nu-parser/src/parse/token_tree.rs @@ -349,7 +349,7 @@ pub enum Delimiter { } impl Delimiter { - pub(crate) fn open(&self) -> &'static str { + pub(crate) fn open(self) -> &'static str { match self { Delimiter::Paren => "(", Delimiter::Brace => "{", @@ -357,7 +357,7 @@ impl Delimiter { } } - pub(crate) fn close(&self) -> &'static str { + pub(crate) fn close(self) -> &'static str { match self { Delimiter::Paren => ")", Delimiter::Brace => "}", diff --git a/crates/nu-parser/src/parse/token_tree_builder.rs b/crates/nu-parser/src/parse/token_tree_builder.rs index f88cb8b8e6..c7fd5e5afb 100644 --- a/crates/nu-parser/src/parse/token_tree_builder.rs +++ b/crates/nu-parser/src/parse/token_tree_builder.rs @@ -9,17 +9,15 @@ use bigdecimal::BigDecimal; use nu_source::{Span, Spanned, SpannedItem}; use num_bigint::BigInt; +#[derive(Default)] pub struct TokenTreeBuilder { pos: usize, output: String, } impl TokenTreeBuilder { - pub fn new() -> TokenTreeBuilder { - TokenTreeBuilder { - pos: 0, - output: String::new(), - } + pub fn new() -> Self { + Default::default() } } @@ -319,7 +317,7 @@ impl TokenTreeBuilder { } pub fn spanned_call(input: Vec, span: impl Into) -> Spanned { - if input.len() == 0 { + if input.is_empty() { panic!("BUG: spanned call (TODO)") } diff --git a/crates/nu-parser/src/parse/unit.rs b/crates/nu-parser/src/parse/unit.rs index e51d6cf362..1d695a73ae 100644 --- a/crates/nu-parser/src/parse/unit.rs +++ b/crates/nu-parser/src/parse/unit.rs @@ -40,8 +40,8 @@ fn convert_number_to_u64(number: &Number) -> u64 { } impl Unit { - pub fn as_str(&self) -> &str { - match *self { + pub fn as_str(self) -> &'static str { + match self { Unit::Byte => "B", Unit::Kilobyte => "KB", Unit::Megabyte => "MB", @@ -58,10 +58,10 @@ impl Unit { } } - pub fn compute(&self, size: &Number) -> UntaggedValue { + pub fn compute(self, size: &Number) -> UntaggedValue { let size = size.clone(); - match &self { + match self { Unit::Byte => number(size), Unit::Kilobyte => number(size * 1024), Unit::Megabyte => number(size * 1024 * 1024), diff --git a/crates/nu-parser/src/parse_command.rs b/crates/nu-parser/src/parse_command.rs index 95f7885f49..ab504d6ca3 100644 --- a/crates/nu-parser/src/parse_command.rs +++ b/crates/nu-parser/src/parse_command.rs @@ -134,7 +134,7 @@ pub fn parse_command_tail( trace!(target: "nu::parse", "Constructed positional={:?} named={:?}", positional, named); - let positional = if positional.len() == 0 { + let positional = if positional.is_empty() { None } else { Some(positional) @@ -204,7 +204,7 @@ impl ColorSyntax for CommandTailShape { fn insert_flag( token_nodes: &mut TokensIterator, - syntax_type: &SyntaxShape, + syntax_type: SyntaxShape, args: &mut ColoringArgs, flag: Flag, pos: usize, @@ -226,7 +226,7 @@ impl ColorSyntax for CommandTailShape { // If the part after a mandatory flag isn't present, that's ok, but we // should roll back any whitespace we chomped - color_fallible_syntax(syntax_type, token_nodes, context)?; + color_fallible_syntax(&syntax_type, token_nodes, context)?; Ok(()) }); @@ -243,9 +243,10 @@ impl ColorSyntax for CommandTailShape { match &kind.0 { NamedType::Switch => { - match token_nodes.extract(|t| t.as_flag(name, context.source())) { - Some((pos, flag)) => args.insert(pos, vec![flag.color()]), - None => {} + if let Some((pos, flag)) = + token_nodes.extract(|t| t.as_flag(name, context.source())) + { + args.insert(pos, vec![flag.color()]) } } NamedType::Mandatory(syntax_type) => { @@ -260,7 +261,7 @@ impl ColorSyntax for CommandTailShape { // The mandatory flag didn't exist at all, so there's nothing to color } Ok((pos, flag)) => { - insert_flag(token_nodes, syntax_type, &mut args, flag, pos, context) + insert_flag(token_nodes, *syntax_type, &mut args, flag, pos, context) } } } @@ -270,7 +271,7 @@ impl ColorSyntax for CommandTailShape { // The optional flag didn't exist at all, so there's nothing to color } Ok(Some((pos, flag))) => { - insert_flag(token_nodes, syntax_type, &mut args, flag, pos, context) + insert_flag(token_nodes, *syntax_type, &mut args, flag, pos, context) } Ok(None) => { diff --git a/crates/nu-plugin/src/plugin.rs b/crates/nu-plugin/src/plugin.rs index fff5408552..b10424edbc 100644 --- a/crates/nu-plugin/src/plugin.rs +++ b/crates/nu-plugin/src/plugin.rs @@ -24,9 +24,9 @@ pub trait Plugin { } pub fn serve_plugin(plugin: &mut dyn Plugin) { - let args = std::env::args(); + let mut args = std::env::args(); if args.len() > 1 { - let input = args.skip(1).next(); + let input = args.nth(1); let input = match input { Some(arg) => std::fs::read_to_string(arg), diff --git a/crates/nu-plugin/src/test_helpers.rs b/crates/nu-plugin/src/test_helpers.rs index c482150623..c568dd8657 100644 --- a/crates/nu-plugin/src/test_helpers.rs +++ b/crates/nu-plugin/src/test_helpers.rs @@ -13,7 +13,7 @@ pub struct PluginTest<'a, T: Plugin> { impl<'a, T: Plugin> PluginTest<'a, T> { pub fn for_plugin(plugin: &'a mut T) -> Self { PluginTest { - plugin: plugin, + plugin, call_info: CallStub::new().create(), input: UntaggedValue::nothing().into_value(Tag::unknown()), } @@ -99,17 +99,16 @@ impl<'a, T: Plugin> PluginTest<'a, T> { pub fn plugin(plugin: &mut T) -> PluginTest { PluginTest::for_plugin(plugin) } + +#[derive(Default)] pub struct CallStub { positionals: Vec, flags: IndexMap, } impl CallStub { - pub fn new() -> CallStub { - CallStub { - positionals: vec![], - flags: indexmap::IndexMap::new(), - } + pub fn new() -> Self { + Default::default() } pub fn with_named_parameter(&mut self, name: &str, value: Value) -> &mut Self { @@ -127,7 +126,7 @@ impl CallStub { pub fn with_parameter(&mut self, name: &str) -> &mut Self { let fields: Vec = name - .split(".") + .split('.') .map(|s| UntaggedValue::string(s.to_string()).into_value(Tag::unknown())) .collect(); @@ -188,7 +187,7 @@ pub mod value { pub fn structured_sample_record(key: &str, value: &str) -> Value { let mut record = TaggedDictBuilder::new(Tag::unknown()); - record.insert_untagged(key.clone(), UntaggedValue::string(value)); + record.insert_untagged(key, UntaggedValue::string(value)); record.into_value() } @@ -196,16 +195,13 @@ pub mod value { UntaggedValue::string(value).into_value(Tag::unknown()) } - pub fn table(list: &Vec) -> Value { + pub fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } - pub fn column_path(paths: &Vec) -> Value { + pub fn column_path(paths: &[Value]) -> Value { UntaggedValue::Primitive(Primitive::ColumnPath( - table(&paths.iter().cloned().collect()) - .as_column_path() - .unwrap() - .item, + table(&paths.to_vec()).as_column_path().unwrap().item, )) .into_untagged_value() } diff --git a/crates/nu-protocol/src/call_info.rs b/crates/nu-protocol/src/call_info.rs index 1a58aabb43..d5be3ff245 100644 --- a/crates/nu-protocol/src/call_info.rs +++ b/crates/nu-protocol/src/call_info.rs @@ -30,14 +30,14 @@ impl EvaluatedArgs { pub fn nth(&self, pos: usize) -> Option<&Value> { match &self.positional { None => None, - Some(array) => array.iter().nth(pos), + Some(array) => array.get(pos), } } pub fn expect_nth(&self, pos: usize) -> Result<&Value, ShellError> { match &self.positional { None => Err(ShellError::unimplemented("Better error: expect_nth")), - Some(array) => match array.iter().nth(pos) { + Some(array) => match array.get(pos) { None => Err(ShellError::unimplemented("Better error: expect_nth")), Some(item) => Ok(item), }, @@ -51,6 +51,10 @@ impl EvaluatedArgs { } } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + pub fn has(&self, name: &str) -> bool { match &self.named { None => false, diff --git a/crates/nu-protocol/src/maybe_owned.rs b/crates/nu-protocol/src/maybe_owned.rs index c654057cab..5c48dc0225 100644 --- a/crates/nu-protocol/src/maybe_owned.rs +++ b/crates/nu-protocol/src/maybe_owned.rs @@ -1,3 +1,5 @@ +#![allow(clippy::should_implement_trait)] + #[derive(Debug)] pub enum MaybeOwned<'a, T> { Owned(T), diff --git a/crates/nu-protocol/src/type_shape.rs b/crates/nu-protocol/src/type_shape.rs index be4aaaaabe..a40fa825e4 100644 --- a/crates/nu-protocol/src/type_shape.rs +++ b/crates/nu-protocol/src/type_shape.rs @@ -278,7 +278,7 @@ impl<'a> PrettyDebug for DebugEntry<'a> { fn pretty(&self) -> DebugDocBuilder { (b::key(match self.key { Column::String(string) => string.clone(), - Column::Value => format!(""), + Column::Value => "".to_string(), }) + b::delimit("(", self.value.pretty(), ")").into_kind()) } } @@ -346,12 +346,12 @@ where None => { self.values.insert(key, { let mut group = G::new(); - group.merge(value.into()); + group.merge(value); group }); } Some(group) => { - group.merge(value.into()); + group.merge(value); } } } diff --git a/crates/nu-protocol/src/value.rs b/crates/nu-protocol/src/value.rs index 2569f41f33..9dcaa1d2f7 100644 --- a/crates/nu-protocol/src/value.rs +++ b/crates/nu-protocol/src/value.rs @@ -46,12 +46,7 @@ impl UntaggedValue { pub fn data_descriptors(&self) -> Vec { match self { UntaggedValue::Primitive(_) => vec![], - UntaggedValue::Row(columns) => columns - .entries - .keys() - .into_iter() - .map(|x| x.to_string()) - .collect(), + UntaggedValue::Row(columns) => columns.entries.keys().map(|x| x.to_string()).collect(), UntaggedValue::Block(_) => vec![], UntaggedValue::Table(_) => vec![], UntaggedValue::Error(_) => vec![], @@ -116,7 +111,7 @@ impl UntaggedValue { UntaggedValue::Row(entries.into()) } - pub fn table(list: &Vec) -> UntaggedValue { + pub fn table(list: &[Value]) -> UntaggedValue { UntaggedValue::Table(list.to_vec()) } @@ -227,9 +222,7 @@ impl Value { pub fn as_path(&self) -> Result { match &self.value { UntaggedValue::Primitive(Primitive::Path(path)) => Ok(path.clone()), - UntaggedValue::Primitive(Primitive::String(path_str)) => { - Ok(PathBuf::from(&path_str).clone()) - } + UntaggedValue::Primitive(Primitive::String(path_str)) => Ok(PathBuf::from(&path_str)), _ => Err(ShellError::type_error("Path", self.spanned_type_name())), } } diff --git a/crates/nu-protocol/src/value/column_path.rs b/crates/nu-protocol/src/value/column_path.rs index b977d099f4..46e7b8c107 100644 --- a/crates/nu-protocol/src/value/column_path.rs +++ b/crates/nu-protocol/src/value/column_path.rs @@ -69,7 +69,7 @@ impl PrettyDebug for ColumnPath { impl HasFallibleSpan for ColumnPath { fn maybe_span(&self) -> Option { - if self.members.len() == 0 { + if self.members.is_empty() { None } else { Some(span_for_spanned_list(self.members.iter().map(|m| m.span))) @@ -98,7 +98,7 @@ pub fn did_you_mean(obj_source: &Value, field_tried: &PathMember) -> Option = possibilities .into_iter() .map(|x| { - let word = x.clone(); + let word = x; let distance = natural::distance::levenshtein_distance(&word, &field_tried); (distance, word) diff --git a/crates/nu-protocol/src/value/dict.rs b/crates/nu-protocol/src/value/dict.rs index 2d02d8da62..cbef720445 100644 --- a/crates/nu-protocol/src/value/dict.rs +++ b/crates/nu-protocol/src/value/dict.rs @@ -15,6 +15,7 @@ pub struct Dictionary { pub entries: IndexMap, } +#[allow(clippy::derive_hash_xor_eq)] impl Hash for Dictionary { fn hash(&self, state: &mut H) { let mut entries = self.entries.clone(); @@ -105,7 +106,7 @@ impl From> for Dictionary { } impl Dictionary { - pub fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value> { + pub fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value> { match self.entries.get(desc) { Some(v) => MaybeOwned::Borrowed(v), None => MaybeOwned::Owned( diff --git a/crates/nu-protocol/src/value/primitive.rs b/crates/nu-protocol/src/value/primitive.rs index 47dae4c203..171bd0059b 100644 --- a/crates/nu-protocol/src/value/primitive.rs +++ b/crates/nu-protocol/src/value/primitive.rs @@ -108,7 +108,7 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S match byte.get_unit() { byte_unit::ByteUnit::B => format!("{} B ", byte.get_value()), - _ => byte.format(1).to_string(), + _ => byte.format(1), } } Primitive::Duration(sec) => format_duration(*sec), @@ -150,7 +150,7 @@ pub fn format_primitive(primitive: &Primitive, field_name: Option<&String>) -> S } .to_owned(), Primitive::Binary(_) => "".to_owned(), - Primitive::Date(d) => d.humanize().to_string(), + Primitive::Date(d) => d.humanize(), } } diff --git a/crates/nu-protocol/src/value/range.rs b/crates/nu-protocol/src/value/range.rs index 81876ff9f6..8f153970c2 100644 --- a/crates/nu-protocol/src/value/range.rs +++ b/crates/nu-protocol/src/value/range.rs @@ -10,14 +10,14 @@ pub enum RangeInclusion { } impl RangeInclusion { - pub fn debug_left_bracket(&self) -> DebugDocBuilder { + pub fn debug_left_bracket(self) -> DebugDocBuilder { b::delimiter(match self { RangeInclusion::Exclusive => "(", RangeInclusion::Inclusive => "[", }) } - pub fn debug_right_bracket(&self) -> DebugDocBuilder { + pub fn debug_right_bracket(self) -> DebugDocBuilder { b::delimiter(match self { RangeInclusion::Exclusive => ")", RangeInclusion::Inclusive => "]", diff --git a/crates/nu-protocol/src/value/serde_bigdecimal.rs b/crates/nu-protocol/src/value/serde_bigdecimal.rs index 423826887c..d7dd1ab626 100644 --- a/crates/nu-protocol/src/value/serde_bigdecimal.rs +++ b/crates/nu-protocol/src/value/serde_bigdecimal.rs @@ -9,7 +9,7 @@ where serde::Serialize::serialize( &big_decimal .to_f64() - .ok_or(serde::ser::Error::custom("expected a f64-sized bignum"))?, + .ok_or_else(|| serde::ser::Error::custom("expected a f64-sized bignum"))?, serializer, ) } @@ -20,5 +20,5 @@ where { let x: f64 = serde::Deserialize::deserialize(deserializer)?; Ok(BigDecimal::from_f64(x) - .ok_or(serde::de::Error::custom("expected a f64-sized bigdecimal"))?) + .ok_or_else(|| serde::de::Error::custom("expected a f64-sized bigdecimal"))?) } diff --git a/crates/nu-protocol/src/value/serde_bigint.rs b/crates/nu-protocol/src/value/serde_bigint.rs index 2ab4ec4dfe..be66ffb769 100644 --- a/crates/nu-protocol/src/value/serde_bigint.rs +++ b/crates/nu-protocol/src/value/serde_bigint.rs @@ -9,7 +9,7 @@ where serde::Serialize::serialize( &big_int .to_i64() - .ok_or(serde::ser::Error::custom("expected a i64-sized bignum"))?, + .ok_or_else(|| serde::ser::Error::custom("expected a i64-sized bignum"))?, serializer, ) } @@ -19,5 +19,6 @@ where D: serde::Deserializer<'de>, { let x: i64 = serde::Deserialize::deserialize(deserializer)?; - Ok(BigInt::from_i64(x).ok_or(serde::de::Error::custom("expected a i64-sized bignum"))?) + Ok(BigInt::from_i64(x) + .ok_or_else(|| serde::de::Error::custom("expected a i64-sized bignum"))?) } diff --git a/crates/nu-source/src/pretty.rs b/crates/nu-source/src/pretty.rs index d8dacef5c1..cf52199f0b 100644 --- a/crates/nu-source/src/pretty.rs +++ b/crates/nu-source/src/pretty.rs @@ -488,6 +488,7 @@ fn hash_doc(doc: &PrettyDebugDoc, state: &mut H) { } } +#[allow(clippy::derive_hash_xor_eq)] impl std::hash::Hash for DebugDoc { fn hash(&self, state: &mut H) { hash_doc(&self.inner, state); diff --git a/crates/nu-test-support/src/fs.rs b/crates/nu-test-support/src/fs.rs index dbb3cc9937..dc3c26b336 100644 --- a/crates/nu-test-support/src/fs.rs +++ b/crates/nu-test-support/src/fs.rs @@ -133,7 +133,7 @@ impl DisplayPath for str { impl DisplayPath for &str { fn display_path(&self) -> String { - self.to_string() + (*self).to_string() } } @@ -145,7 +145,7 @@ impl DisplayPath for String { impl DisplayPath for &String { fn display_path(&self) -> String { - self.to_string() + (*self).to_string() } } pub enum Stub<'a> { @@ -196,7 +196,7 @@ pub fn create_file_at(full_path: impl AsRef) -> Result<(), std::io::Error> panic!(format!("{:?} exists", parent.display())); } - std::fs::write(full_path, "fake data".as_bytes()) + std::fs::write(full_path, b"fake data") } pub fn copy_file_to(source: &str, destination: &str) { diff --git a/crates/nu-test-support/src/macros.rs b/crates/nu-test-support/src/macros.rs index 6b883c94be..7f289f1763 100644 --- a/crates/nu-test-support/src/macros.rs +++ b/crates/nu-test-support/src/macros.rs @@ -34,7 +34,7 @@ macro_rules! nu { .spawn() { Ok(child) => child, - Err(why) => panic!("Can't run test {}", why.description()), + Err(why) => panic!("Can't run test {}", why.to_string()), }; let stdin = process.stdin.as_mut().expect("couldn't open stdin"); diff --git a/crates/nu-test-support/src/playground.rs b/crates/nu-test-support/src/playground.rs index 0ba57cad76..ccac984266 100644 --- a/crates/nu-test-support/src/playground.rs +++ b/crates/nu-test-support/src/playground.rs @@ -22,7 +22,7 @@ pub struct Dirs { impl Dirs { pub fn formats(&self) -> PathBuf { - PathBuf::from(self.fixtures.join("formats")) + self.fixtures.join("formats") } } @@ -47,7 +47,7 @@ impl Playground { std::fs::create_dir(PathBuf::from(&nuplay_dir)).expect("can not create directory"); let mut playground = Playground { - root: root, + root, tests: topic.to_string(), cwd: nuplay_dir, }; @@ -63,21 +63,29 @@ impl Playground { .expect("Couldn't find the fixtures directory") .join("tests/fixtures"); - let fixtures = dunce::canonicalize(fixtures.clone()).expect(&format!( - "Couldn't canonicalize fixtures path {}", - fixtures.display() - )); + let fixtures = dunce::canonicalize(fixtures.clone()).unwrap_or_else(|e| { + panic!( + "Couldn't canonicalize fixtures path {}: {:?}", + fixtures.display(), + e + ) + }); - let test = - dunce::canonicalize(PathBuf::from(playground_root.join(topic))).expect(&format!( - "Couldn't canonicalize test path {}", - playground_root.join(topic).display() - )); + let test = dunce::canonicalize(playground_root.join(topic)).unwrap_or_else(|e| { + panic!( + "Couldn't canonicalize test path {}: {:?}", + playground_root.join(topic).display(), + e + ) + }); - let root = dunce::canonicalize(playground_root).expect(&format!( - "Couldn't canonicalize tests root path {}", - playground_root.display() - )); + let root = dunce::canonicalize(playground_root).unwrap_or_else(|e| { + panic!( + "Couldn't canonicalize tests root path {}: {:?}", + playground_root.display(), + e + ) + }); let dirs = Dirs { root, @@ -119,8 +127,7 @@ impl Playground { path.push(file_name); - std::fs::write(PathBuf::from(path), contents.as_bytes()) - .expect("can not create file"); + std::fs::write(path, contents.as_bytes()).expect("can not create file"); }) .for_each(drop); self.back_to_playground(); @@ -136,17 +143,14 @@ impl Playground { pub fn glob_vec(pattern: &str) -> Vec { let glob = glob(pattern); - match glob { - Ok(paths) => paths - .map(|path| { - if let Ok(path) = path { - path - } else { - unreachable!() - } - }) - .collect(), - Err(_) => panic!("Invalid pattern."), - } + glob.expect("invalid pattern") + .map(|path| { + if let Ok(path) = path { + path + } else { + unreachable!() + } + }) + .collect() } } diff --git a/crates/nu-value-ext/src/lib.rs b/crates/nu-value-ext/src/lib.rs index c575c2f0b1..a15bb4620c 100644 --- a/crates/nu-value-ext/src/lib.rs +++ b/crates/nu-value-ext/src/lib.rs @@ -9,7 +9,7 @@ use num_traits::cast::ToPrimitive; pub trait ValueExt { fn into_parts(self) -> (UntaggedValue, Tag); - fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value>; + fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value>; fn get_data_by_key(&self, name: Spanned<&str>) -> Option; fn get_data_by_member(&self, name: &PathMember) -> Result; fn get_data_by_column_path( @@ -43,7 +43,7 @@ impl ValueExt for Value { (self.value, self.tag) } - fn get_data(&self, desc: &String) -> MaybeOwned<'_, Value> { + fn get_data(&self, desc: &str) -> MaybeOwned<'_, Value> { get_data(self, desc) } @@ -163,14 +163,9 @@ pub fn get_data_by_member(value: &Value, name: &PathMember) -> Result Ok(v.clone()), - None => Err(ShellError::range_error( - 0..(l.len()), - &int.spanned(name.span), - "indexing", - )), - } + get_data_by_index(value, index.spanned(value.tag.span)).ok_or_else(|| { + ShellError::range_error(0..(l.len()), &int.spanned(name.span), "indexing") + }) } } } @@ -193,7 +188,7 @@ pub fn get_data_by_column_path( match value { Ok(v) => current = v.clone(), - Err(e) => return Err(callback((¤t.clone(), &p.clone(), e))), + Err(e) => return Err(callback((¤t, &p.clone(), e))), } } @@ -210,10 +205,9 @@ pub fn insert_data_at_path(value: &Value, path: &str, new_value: Value) -> Optio if split_path.len() == 1 { // Special case for inserting at the top level - current.entries.insert( - path.to_string(), - new_value.value.clone().into_value(&value.tag), - ); + current + .entries + .insert(path.to_string(), new_value.value.into_value(&value.tag)); return Some(new_obj); } @@ -275,7 +269,7 @@ pub fn insert_data_at_member( ) })?; - insert_data_at_index(array, int.tagged(member.span), new_value.clone())?; + insert_data_at_index(array, int.tagged(member.span), new_value)?; Ok(()) } }, @@ -428,7 +422,7 @@ fn insert_data_at_index( } } -pub fn get_data<'value>(value: &'value Value, desc: &String) -> MaybeOwned<'value, Value> { +pub fn get_data<'value>(value: &'value Value, desc: &str) -> MaybeOwned<'value, Value> { match &value.value { UntaggedValue::Primitive(_) => MaybeOwned::Borrowed(value), UntaggedValue::Row(o) => o.get_data(desc), diff --git a/crates/nu_plugin_binaryview/src/main.rs b/crates/nu_plugin_binaryview/src/main.rs index ed5ac07eae..9d3140c299 100644 --- a/crates/nu_plugin_binaryview/src/main.rs +++ b/crates/nu_plugin_binaryview/src/main.rs @@ -23,11 +23,8 @@ impl Plugin for BinaryView { fn sink(&mut self, call_info: CallInfo, input: Vec) { for v in input { let value_anchor = v.anchor(); - match &v.value { - UntaggedValue::Primitive(Primitive::Binary(b)) => { - let _ = view_binary(&b, value_anchor.as_ref(), call_info.args.has("lores")); - } - _ => {} + if let UntaggedValue::Primitive(Primitive::Binary(b)) = &v.value { + let _ = view_binary(&b, value_anchor.as_ref(), call_info.args.has("lores")); } } } @@ -39,12 +36,9 @@ fn view_binary( lores_mode: bool, ) -> Result<(), Box> { if b.len() > 3 { - match (b[0], b[1], b[2]) { - (0x4e, 0x45, 0x53) => { - view_contents_interactive(b, source, lores_mode)?; - return Ok(()); - } - _ => {} + if let (0x4e, 0x45, 0x53) = (b[0], b[1], b[2]) { + view_contents_interactive(b, source, lores_mode)?; + return Ok(()); } } view_contents(b, source, lores_mode)?; @@ -155,16 +149,13 @@ impl RenderContext { } } if prev_count > 0 { - match (prev_fg, prev_bg) { - (Some(c), Some(d)) => { - print!( - "{}", - ansi_term::Colour::RGB(c.0, c.1, c.2) - .on(ansi_term::Colour::RGB(d.0, d.1, d.2,)) - .paint((0..prev_count).map(|_| "▀").collect::()) - ); - } - _ => {} + if let (Some(c), Some(d)) = (prev_fg, prev_bg) { + print!( + "{}", + ansi_term::Colour::RGB(c.0, c.1, c.2) + .on(ansi_term::Colour::RGB(d.0, d.1, d.2,)) + .paint((0..prev_count).map(|_| "▀").collect::()) + ); } } outln!("{}", Attribute::Reset); @@ -407,11 +398,11 @@ pub fn view_contents_interactive( if rawkey.is_pressed(rawkey::KeyCode::Escape) { break 'gameloop; } else { - for i in 0..buttons.len() { - if rawkey.is_pressed(buttons[i]) { - nes.press_button(0, i as u8); + for (idx, button) in buttons.iter().enumerate() { + if rawkey.is_pressed(*button) { + nes.press_button(0, idx as u8); } else { - nes.release_button(0, i as u8); + nes.release_button(0, idx as u8); } } } diff --git a/crates/nu_plugin_fetch/src/main.rs b/crates/nu_plugin_fetch/src/main.rs index d0568e7809..20acb4253a 100644 --- a/crates/nu_plugin_fetch/src/main.rs +++ b/crates/nu_plugin_fetch/src/main.rs @@ -100,18 +100,18 @@ async fn fetch_helper(path: &Value, has_raw: bool, row: Value) -> ReturnValue { } else { // If the extension could not be determined via mimetype, try to use the path // extension. Some file types do not declare their mimetypes (such as bson files). - file_extension.or(path_str.split('.').last().map(String::from)) + file_extension.or_else(|| path_str.split('.').last().map(String::from)) }; let tagged_contents = contents.retag(&contents_tag); if let Some(extension) = file_extension { - return Ok(ReturnSuccess::Action(CommandAction::AutoConvert( + Ok(ReturnSuccess::Action(CommandAction::AutoConvert( tagged_contents, extension, - ))); + ))) } else { - return ReturnSuccess::value(tagged_contents); + ReturnSuccess::value(tagged_contents) } } diff --git a/crates/nu_plugin_inc/src/inc.rs b/crates/nu_plugin_inc/src/inc.rs index da290e4455..888377e785 100644 --- a/crates/nu_plugin_inc/src/inc.rs +++ b/crates/nu_plugin_inc/src/inc.rs @@ -16,6 +16,7 @@ pub enum SemVerAction { Patch, } +#[derive(Default)] pub struct Inc { pub field: Option>, pub error: Option, @@ -23,12 +24,8 @@ pub struct Inc { } impl Inc { - pub fn new() -> Inc { - Inc { - field: None, - error: None, - action: None, - } + pub fn new() -> Self { + Default::default() } fn apply(&self, input: &str) -> Result { @@ -122,12 +119,11 @@ impl Inc { ); let got = replace_for?; - let replacement = self.inc(got.clone())?; + let replacement = self.inc(got)?; - match value.replace_data_at_column_path( - &f, - replacement.value.clone().into_untagged_value(), - ) { + match value + .replace_data_at_column_path(&f, replacement.value.into_untagged_value()) + { Some(v) => Ok(v), None => Err(ShellError::labeled_error( "inc could not find field to replace", diff --git a/crates/nu_plugin_inc/src/nu_plugin_inc/tests.rs b/crates/nu_plugin_inc/src/nu_plugin_inc/tests.rs index 34dcef9bd1..e4c9496623 100644 --- a/crates/nu_plugin_inc/src/nu_plugin_inc/tests.rs +++ b/crates/nu_plugin_inc/src/nu_plugin_inc/tests.rs @@ -56,7 +56,7 @@ mod integration { plugin(&mut Inc::new()) .args(CallStub::new().with_parameter("package.version").create()) .setup(|plugin, _| { - plugin.expect_field(column_path(&vec![string("package"), string("version")])) + plugin.expect_field(column_path(&[string("package"), string("version")])) }); } diff --git a/crates/nu_plugin_match/src/main.rs b/crates/nu_plugin_match/src/main.rs index dc787781d1..05513c89eb 100644 --- a/crates/nu_plugin_match/src/main.rs +++ b/crates/nu_plugin_match/src/main.rs @@ -12,6 +12,7 @@ struct Match { } impl Match { + #[allow(clippy::trivial_regex)] fn new() -> Self { Match { column: String::new(), diff --git a/crates/nu_plugin_post/src/main.rs b/crates/nu_plugin_post/src/main.rs index 4b0b125956..43fc7037aa 100644 --- a/crates/nu_plugin_post/src/main.rs +++ b/crates/nu_plugin_post/src/main.rs @@ -61,15 +61,12 @@ impl Post { file => Some(file.clone()), }; - self.user = call_info - .args - .get("user") - .map(|x| x.as_string().unwrap().to_string()); + self.user = call_info.args.get("user").map(|x| x.as_string().unwrap()); self.password = call_info .args .get("password") - .map(|x| x.as_string().unwrap().to_string()); + .map(|x| x.as_string().unwrap()); self.headers = get_headers(&call_info)?; @@ -166,18 +163,18 @@ async fn post_helper( } else { // If the extension could not be determined via mimetype, try to use the path // extension. Some file types do not declare their mimetypes (such as bson files). - file_extension.or(path_str.split('.').last().map(String::from)) + file_extension.or_else(|| path_str.split('.').last().map(String::from)) }; let tagged_contents = contents.into_value(&contents_tag); if let Some(extension) = file_extension { - return Ok(ReturnSuccess::Action(CommandAction::AutoConvert( + Ok(ReturnSuccess::Action(CommandAction::AutoConvert( tagged_contents, extension, - ))); + ))) } else { - return ReturnSuccess::value(tagged_contents); + ReturnSuccess::value(tagged_contents) } } @@ -468,7 +465,7 @@ pub fn value_to_json_value(v: &Value) -> Result { }) } -fn json_list(input: &Vec) -> Result, ShellError> { +fn json_list(input: &[Value]) -> Result, ShellError> { let mut out = vec![]; for value in input { @@ -482,20 +479,22 @@ fn get_headers(call_info: &CallInfo) -> Result, ShellError> { let mut headers = vec![]; match extract_header_value(&call_info, "content-type") { - Ok(h) => match h { - Some(ct) => headers.push(HeaderKind::ContentType(ct)), - None => {} - }, + Ok(h) => { + if let Some(ct) = h { + headers.push(HeaderKind::ContentType(ct)) + } + } Err(e) => { return Err(e); } }; match extract_header_value(&call_info, "content-length") { - Ok(h) => match h { - Some(cl) => headers.push(HeaderKind::ContentLength(cl)), - None => {} - }, + Ok(h) => { + if let Some(cl) = h { + headers.push(HeaderKind::ContentLength(cl)) + } + } Err(e) => { return Err(e); } diff --git a/crates/nu_plugin_str/src/nu_plugin_str/mod.rs b/crates/nu_plugin_str/src/nu_plugin_str/mod.rs index 22ad8c0255..bc6355ff54 100644 --- a/crates/nu_plugin_str/src/nu_plugin_str/mod.rs +++ b/crates/nu_plugin_str/src/nu_plugin_str/mod.rs @@ -81,8 +81,8 @@ impl Plugin for Str { }) = args.get("find-replace") { self.for_replace(ReplaceAction::FindAndReplace( - arguments.get(0).unwrap().as_string()?.to_string(), - arguments.get(1).unwrap().as_string()?.to_string(), + arguments.get(0).unwrap().as_string()?, + arguments.get(1).unwrap().as_string()?, )); } } diff --git a/crates/nu_plugin_str/src/nu_plugin_str/tests.rs b/crates/nu_plugin_str/src/nu_plugin_str/tests.rs index d198686619..2a51a0f7be 100644 --- a/crates/nu_plugin_str/src/nu_plugin_str/tests.rs +++ b/crates/nu_plugin_str/src/nu_plugin_str/tests.rs @@ -72,7 +72,7 @@ mod integration { CallStub::new() .with_named_parameter( "find-replace", - table(&vec![string(&search_argument), string(&replace_argument)]), + table(&[string(&search_argument), string(&replace_argument)]), ) .create(), ) @@ -91,7 +91,7 @@ mod integration { .create(), ) .setup(|plugin, _| { - plugin.expect_field(column_path(&vec![string("package"), string("description")])) + plugin.expect_field(column_path(&[string("package"), string("description")])) }); } @@ -194,7 +194,7 @@ mod integration { .with_parameter("staff") .with_named_parameter( "find-replace", - table(&vec![string("kittens"), string("jotandrehuda")]), + table(&[string("kittens"), string("jotandrehuda")]), ) .create(), ) @@ -353,7 +353,7 @@ mod integration { CallStub::new() .with_named_parameter( "find-replace", - table(&vec![string("kittens"), string("jotandrehuda")]), + table(&[string("kittens"), string("jotandrehuda")]), ) .create(), ) diff --git a/crates/nu_plugin_str/src/strutils.rs b/crates/nu_plugin_str/src/strutils.rs index 59d907d99e..727ba73023 100644 --- a/crates/nu_plugin_str/src/strutils.rs +++ b/crates/nu_plugin_str/src/strutils.rs @@ -20,6 +20,7 @@ pub enum ReplaceAction { FindAndReplace(String, String), } +#[derive(Default)] pub struct Str { pub field: Option>, pub error: Option, @@ -27,12 +28,8 @@ pub struct Str { } impl Str { - pub fn new() -> Str { - Str { - field: None, - error: None, - action: None, - } + pub fn new() -> Self { + Default::default() } fn apply(&self, input: &str) -> Result { @@ -174,12 +171,11 @@ impl Str { ); let got = replace_for?; - let replacement = self.strutils(got.clone())?; + let replacement = self.strutils(got)?; - match value.replace_data_at_column_path( - &f, - replacement.value.clone().into_untagged_value(), - ) { + match value + .replace_data_at_column_path(&f, replacement.value.into_untagged_value()) + { Some(v) => Ok(v), None => Err(ShellError::labeled_error( "str could not find field to replace", diff --git a/crates/nu_plugin_textview/src/main.rs b/crates/nu_plugin_textview/src/main.rs index d7f6d750d3..ae28bd7d8f 100644 --- a/crates/nu_plugin_textview/src/main.rs +++ b/crates/nu_plugin_textview/src/main.rs @@ -38,7 +38,7 @@ impl Plugin for TextView { } fn paint_textview( - draw_commands: &Vec, + draw_commands: &[DrawCommand], starting_row: usize, use_color_buffer: bool, ) -> usize { @@ -148,8 +148,8 @@ fn scroll_view_lines_if_needed(draw_commands: Vec, use_color_buffer loop { if let Some(ev) = sync_stdin.next() { - match ev { - InputEvent::Keyboard(k) => match k { + if let InputEvent::Keyboard(k) = ev { + match k { KeyEvent::Esc => { break; } @@ -187,8 +187,7 @@ fn scroll_view_lines_if_needed(draw_commands: Vec, use_color_buffer paint_textview(&draw_commands, starting_row, use_color_buffer); } _ => {} - }, - _ => {} + } } } @@ -220,71 +219,67 @@ fn scroll_view(s: &str) { fn view_text_value(value: &Value) { let value_anchor = value.anchor(); - match &value.value { - UntaggedValue::Primitive(Primitive::String(ref s)) => { - if let Some(source) = value_anchor { - let extension: Option = match source { - AnchorLocation::File(file) => { - let path = Path::new(&file); - path.extension().map(|x| x.to_string_lossy().to_string()) - } - AnchorLocation::Url(url) => { - let url = url::Url::parse(&url); - if let Ok(url) = url { - let url = url.clone(); - if let Some(mut segments) = url.path_segments() { - if let Some(file) = segments.next_back() { - let path = Path::new(file); - path.extension().map(|x| x.to_string_lossy().to_string()) - } else { - None - } + if let UntaggedValue::Primitive(Primitive::String(ref s)) = &value.value { + if let Some(source) = value_anchor { + let extension: Option = match source { + AnchorLocation::File(file) => { + let path = Path::new(&file); + path.extension().map(|x| x.to_string_lossy().to_string()) + } + AnchorLocation::Url(url) => { + let url = url::Url::parse(&url); + if let Ok(url) = url { + if let Some(mut segments) = url.path_segments() { + if let Some(file) = segments.next_back() { + let path = Path::new(file); + path.extension().map(|x| x.to_string_lossy().to_string()) } else { None } } else { None } + } else { + None } - //FIXME: this probably isn't correct - AnchorLocation::Source(_source) => None, - }; + } + //FIXME: this probably isn't correct + AnchorLocation::Source(_source) => None, + }; - match extension { - Some(extension) => { - // Load these once at the start of your program - let ps: SyntaxSet = - syntect::dumps::from_binary(include_bytes!("assets/syntaxes.bin")); + match extension { + Some(extension) => { + // Load these once at the start of your program + let ps: SyntaxSet = + syntect::dumps::from_binary(include_bytes!("assets/syntaxes.bin")); - if let Some(syntax) = ps.find_syntax_by_extension(&extension) { - let ts: ThemeSet = - syntect::dumps::from_binary(include_bytes!("assets/themes.bin")); - let mut h = HighlightLines::new(syntax, &ts.themes["OneHalfDark"]); + if let Some(syntax) = ps.find_syntax_by_extension(&extension) { + let ts: ThemeSet = + syntect::dumps::from_binary(include_bytes!("assets/themes.bin")); + let mut h = HighlightLines::new(syntax, &ts.themes["OneHalfDark"]); - let mut v = vec![]; - for line in s.lines() { - let ranges: Vec<(Style, &str)> = h.highlight(line, &ps); + let mut v = vec![]; + for line in s.lines() { + let ranges: Vec<(Style, &str)> = h.highlight(line, &ps); - for range in ranges { - v.push(DrawCommand::DrawString(range.0, range.1.to_string())); - } - - v.push(DrawCommand::NextLine); + for range in ranges { + v.push(DrawCommand::DrawString(range.0, range.1.to_string())); } - scroll_view_lines_if_needed(v, true); - } else { - scroll_view(s); + + v.push(DrawCommand::NextLine); } - } - _ => { + scroll_view_lines_if_needed(v, true); + } else { scroll_view(s); } } - } else { - scroll_view(s); + _ => { + scroll_view(s); + } } + } else { + scroll_view(s); } - _ => {} } } diff --git a/crates/nu_plugin_tree/src/main.rs b/crates/nu_plugin_tree/src/main.rs index 4d9781c8f9..1b04e340d4 100644 --- a/crates/nu_plugin_tree/src/main.rs +++ b/crates/nu_plugin_tree/src/main.rs @@ -87,7 +87,7 @@ impl Plugin for TreeViewer { } fn sink(&mut self, _call_info: CallInfo, input: Vec) { - if input.len() > 0 { + if !input.is_empty() { for i in input.iter() { let view = TreeView::from_value(&i); let _ = view.render_view(); diff --git a/src/cli.rs b/src/cli.rs index c3af9debe6..c5a23684e4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -642,7 +642,7 @@ pub fn classify_pipeline( } pub fn print_err(err: ShellError, host: &dyn Host, source: &Text) { - let diag = err.to_diagnostic(); + let diag = err.into_diagnostic(); let writer = host.err_termcolor(); let mut source = source.to_string(); diff --git a/src/commands.rs b/src/commands.rs index 200f6fd115..843042b2a3 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -116,7 +116,7 @@ pub(crate) use echo::Echo; pub(crate) use edit::Edit; pub(crate) use enter::Enter; pub(crate) use env::Env; -#[allow(unused)] +#[allow(unused_imports)] pub(crate) use evaluate_by::EvaluateBy; pub(crate) use exit::Exit; pub(crate) use first::First; @@ -144,7 +144,7 @@ pub(crate) use insert::Insert; pub(crate) use last::Last; pub(crate) use lines::Lines; pub(crate) use ls::Ls; -#[allow(unused)] +#[allow(unused_imports)] pub(crate) use map_max_by::MapMaxBy; pub(crate) use mkdir::Mkdir; pub(crate) use mv::Move; @@ -158,7 +158,7 @@ pub(crate) use prepend::Prepend; pub(crate) use prev::Previous; pub(crate) use pwd::Pwd; pub(crate) use range::Range; -#[allow(unused)] +#[allow(unused_imports)] pub(crate) use reduce_by::ReduceBy; pub(crate) use reject::Reject; pub(crate) use reverse::Reverse; @@ -172,7 +172,7 @@ pub(crate) use sort_by::SortBy; pub(crate) use split_by::SplitBy; pub(crate) use split_column::SplitColumn; pub(crate) use split_row::SplitRow; -#[allow(unused)] +#[allow(unused_imports)] pub(crate) use t_sort_by::TSortBy; pub(crate) use table::Table; pub(crate) use tags::Tags; diff --git a/src/commands/clip.rs b/src/commands/clip.rs index de10ffca14..a2778c86bf 100644 --- a/src/commands/clip.rs +++ b/src/commands/clip.rs @@ -58,7 +58,7 @@ pub mod clipboard { let mut clip_context: ClipboardContext = ClipboardProvider::new().unwrap(); let mut new_copy_data = String::new(); - if input.len() > 0 { + if !input.is_empty() { let mut first = true; for i in input.iter() { if !first { diff --git a/src/commands/command.rs b/src/commands/command.rs index 4d4474444c..d90e21cec8 100644 --- a/src/commands/command.rs +++ b/src/commands/command.rs @@ -192,7 +192,7 @@ impl CommandArgs { let (input, args) = args.split(); let name_tag = args.call_info.name_tag; - let mut deserializer = ConfigDeserializer::from_call_info(call_info.clone()); + let mut deserializer = ConfigDeserializer::from_call_info(call_info); Ok(RunnableRawArgs { args: T::deserialize(&mut deserializer)?, @@ -556,7 +556,6 @@ impl WholeStreamCommand for FnFilterCommand { } = args; let host: Arc> = host.clone(); - let shell_manager = shell_manager.clone(); let registry: CommandRegistry = registry.clone(); let func = self.func; diff --git a/src/commands/evaluate_by.rs b/src/commands/evaluate_by.rs index 13504361b5..526f1ab34a 100644 --- a/src/commands/evaluate_by.rs +++ b/src/commands/evaluate_by.rs @@ -111,7 +111,7 @@ pub fn evaluate( } => { let data: Vec<_> = data .into_iter() - .map(|x| evaluate_with(x.clone(), tag.clone()).unwrap()) + .map(|x| evaluate_with(x, tag.clone()).unwrap()) .collect(); UntaggedValue::Table(data).into_value(&tag) } @@ -124,7 +124,7 @@ pub fn evaluate( }) .collect(); - UntaggedValue::Table(datasets.clone()).into_value(&tag) + UntaggedValue::Table(datasets).into_value(&tag) } _ => UntaggedValue::Table(vec![]).into_value(&tag), }; @@ -156,7 +156,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -233,10 +233,10 @@ mod tests { fn evaluates_the_tables() { assert_eq!( evaluate(&nu_releases_sorted_by_date(), None, Tag::unknown()).unwrap(), - table(&vec![table(&vec![ - table(&vec![int(1), int(1), int(1)]), - table(&vec![int(1), int(1), int(1)]), - table(&vec![int(1), int(1), int(1)]), + table(&[table(&[ + table(&[int(1), int(1), int(1)]), + table(&[int(1), int(1), int(1)]), + table(&[int(1), int(1), int(1)]), ]),]) ); } @@ -247,10 +247,10 @@ mod tests { assert_eq!( evaluate(&nu_releases_sorted_by_date(), Some(eval), Tag::unknown()).unwrap(), - table(&vec![table(&vec![ - table(&vec![string("AR"), string("JT"), string("YK")]), - table(&vec![string("AR"), string("YK"), string("JT")]), - table(&vec![string("YK"), string("JT"), string("AR")]), + table(&[table(&[ + table(&[string("AR"), string("JT"), string("YK")]), + table(&[string("AR"), string("YK"), string("JT")]), + table(&[string("YK"), string("JT"), string("AR")]), ]),]) ); } diff --git a/src/commands/format.rs b/src/commands/format.rs index 25d70780c8..b121a59384 100644 --- a/src/commands/format.rs +++ b/src/commands/format.rs @@ -55,13 +55,10 @@ impl PerItemCommand for Format { output.push_str(s); } FormatCommand::Column(c) => { - match dict.entries.get(c) { - Some(c) => output - .push_str(&value::format_leaf(c.borrow()).plain_string(100_000)), - None => { - // This column doesn't match, so don't emit anything - } + if let Some(c) = dict.entries.get(c) { + output.push_str(&value::format_leaf(c.borrow()).plain_string(100_000)) } + // That column doesn't match, so don't emit anything } } } diff --git a/src/commands/from_bson.rs b/src/commands/from_bson.rs index cac3f52ff8..c64b607386 100644 --- a/src/commands/from_bson.rs +++ b/src/commands/from_bson.rs @@ -102,7 +102,7 @@ fn convert_bson_value_to_nu_value(v: &Bson, tag: impl Into) -> Result( let headers = (1..=num_columns) .map(|i| format!("Column{}", i)) .collect::>(); - collect(headers, ls.iter().map(|s| s.as_ref()), separator) + collect(headers, ls.into_iter(), separator) }; match headers { diff --git a/src/commands/from_xml.rs b/src/commands/from_xml.rs index be8f451808..b160c9ab90 100644 --- a/src/commands/from_xml.rs +++ b/src/commands/from_xml.rs @@ -52,7 +52,7 @@ fn from_node_to_value<'a, 'd>(n: &roxmltree::Node<'a, 'd>, tag: impl Into) .collect(); let mut collected = TaggedDictBuilder::new(tag); - collected.insert_untagged(name.clone(), UntaggedValue::Table(children_values)); + collected.insert_untagged(name, UntaggedValue::Table(children_values)); collected.into_value() } else if n.is_comment() { @@ -145,7 +145,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -160,7 +160,7 @@ mod tests { assert_eq!( parse(source), row(indexmap! { - "nu".into() => table(&vec![]) + "nu".into() => table(&[]) }) ); } @@ -172,7 +172,7 @@ mod tests { assert_eq!( parse(source), row(indexmap! { - "nu".into() => table(&vec![string("La era de los tres caballeros")]) + "nu".into() => table(&[string("La era de los tres caballeros")]) }) ); } @@ -189,10 +189,10 @@ mod tests { assert_eq!( parse(source), row(indexmap! { - "nu".into() => table(&vec![ - row(indexmap! {"dev".into() => table(&vec![string("Andrés")])}), - row(indexmap! {"dev".into() => table(&vec![string("Jonathan")])}), - row(indexmap! {"dev".into() => table(&vec![string("Yehuda")])}) + "nu".into() => table(&[ + row(indexmap! {"dev".into() => table(&[string("Andrés")])}), + row(indexmap! {"dev".into() => table(&[string("Jonathan")])}), + row(indexmap! {"dev".into() => table(&[string("Yehuda")])}) ]) }) ); diff --git a/src/commands/group_by.rs b/src/commands/group_by.rs index c53cf35071..cabfbf6490 100644 --- a/src/commands/group_by.rs +++ b/src/commands/group_by.rs @@ -128,7 +128,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -171,17 +171,17 @@ mod tests { assert_eq!( group(&for_key, nu_releases_commiters(), Tag::unknown()).unwrap(), row(indexmap! { - "August 23-2019".into() => table(&vec![ + "August 23-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("August 23-2019")}), row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("August 23-2019")}), row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("August 23-2019")}) ]), - "October 10-2019".into() => table(&vec![ + "October 10-2019".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("October 10-2019")}), row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("October 10-2019")}), row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("October 10-2019")}) ]), - "Sept 24-2019".into() => table(&vec![ + "Sept 24-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("Sept 24-2019")}), row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("Sept 24-2019")}), row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("Sept 24-2019")}) @@ -197,17 +197,17 @@ mod tests { assert_eq!( group(&for_key, nu_releases_commiters(), Tag::unknown()).unwrap(), row(indexmap! { - "EC".into() => table(&vec![ + "EC".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("August 23-2019")}), row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("Sept 24-2019")}), row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("October 10-2019")}) ]), - "NZ".into() => table(&vec![ + "NZ".into() => table(&[ row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("August 23-2019")}), row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("October 10-2019")}), row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("Sept 24-2019")}) ]), - "US".into() => table(&vec![ + "US".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("October 10-2019")}), row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("Sept 24-2019")}), row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("August 23-2019")}), diff --git a/src/commands/macros.rs b/src/commands/macros.rs index eb2368c050..c79d980b88 100644 --- a/src/commands/macros.rs +++ b/src/commands/macros.rs @@ -114,7 +114,7 @@ macro_rules! command { $($extract)* { use std::convert::TryInto; - $args.get(stringify!($param_name)).clone().try_into()? + $args.get(stringify!($param_name)).try_into()? } } ); @@ -164,7 +164,7 @@ macro_rules! command { $($extract)* { use std::convert::TryInto; - $args.get(stringify!($param_name)).clone().try_into()? + $args.get(stringify!($param_name)).try_into()? } } ); @@ -214,7 +214,7 @@ macro_rules! command { $($extract)* { use std::convert::TryInto; - $args.get(stringify!($param_name)).clone().try_into()? + $args.get(stringify!($param_name)).try_into()? } } ); diff --git a/src/commands/nth.rs b/src/commands/nth.rs index 94e0e0005c..ae20953a36 100644 --- a/src/commands/nth.rs +++ b/src/commands/nth.rs @@ -65,7 +65,7 @@ fn nth( .iter() .any(|requested| requested.item == idx as u64) { - result.push_back(ReturnSuccess::value(item.clone())); + result.push_back(ReturnSuccess::value(item)); } result diff --git a/src/commands/range.rs b/src/commands/range.rs index c2e9a14d83..c847c66196 100644 --- a/src/commands/range.rs +++ b/src/commands/range.rs @@ -41,13 +41,13 @@ impl WholeStreamCommand for Range { fn range( RangeArgs { area }: RangeArgs, - RunnableContext { input, name: _, .. }: RunnableContext, + RunnableContext { input, .. }: RunnableContext, ) -> Result { let range = area.item; let (from, _) = range.from; let (to, _) = range.to; - return Ok(OutputStream::from_input( + Ok(OutputStream::from_input( input.values.skip(*from).take(*to - *from + 1), - )); + )) } diff --git a/src/commands/reduce_by.rs b/src/commands/reduce_by.rs index 4c978a88db..e6a7d1a1fa 100644 --- a/src/commands/reduce_by.rs +++ b/src/commands/reduce_by.rs @@ -180,7 +180,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -254,7 +254,7 @@ mod tests { Some(String::from("sum")), Tag::unknown() ), - Ok(table(&vec![table(&vec![int(3), int(3), int(3)])])) + Ok(table(&[table(&[int(3), int(3), int(3)])])) ); } } diff --git a/src/commands/split_by.rs b/src/commands/split_by.rs index a21246d895..9af056c0ad 100644 --- a/src/commands/split_by.rs +++ b/src/commands/split_by.rs @@ -167,7 +167,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -216,35 +216,35 @@ mod tests { split(&for_key, &nu_releases_grouped_by_date(), Tag::unknown()).unwrap(), UntaggedValue::row(indexmap! { "EC".into() => row(indexmap! { - "August 23-2019".into() => table(&vec![ + "August 23-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("August 23-2019")}) ]), - "Sept 24-2019".into() => table(&vec![ + "Sept 24-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("Sept 24-2019")}) ]), - "October 10-2019".into() => table(&vec![ + "October 10-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("October 10-2019")}) ]) }), "NZ".into() => row(indexmap! { - "August 23-2019".into() => table(&vec![ + "August 23-2019".into() => table(&[ row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("August 23-2019")}) ]), - "Sept 24-2019".into() => table(&vec![ + "Sept 24-2019".into() => table(&[ row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("Sept 24-2019")}) ]), - "October 10-2019".into() => table(&vec![ + "October 10-2019".into() => table(&[ row(indexmap!{"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("October 10-2019")}) ]) }), "US".into() => row(indexmap! { - "August 23-2019".into() => table(&vec![ + "August 23-2019".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("August 23-2019")}) ]), - "Sept 24-2019".into() => table(&vec![ + "Sept 24-2019".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("Sept 24-2019")}) ]), - "October 10-2019".into() => table(&vec![ + "October 10-2019".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("October 10-2019")}) ]) }) @@ -257,13 +257,13 @@ mod tests { let for_key = String::from("country").tagged_unknown(); let nu_releases = row(indexmap! { - "August 23-2019".into() => table(&vec![ + "August 23-2019".into() => table(&[ row(indexmap!{"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("August 23-2019")}) ]), - "Sept 24-2019".into() => table(&vec![ + "Sept 24-2019".into() => table(&[ row(indexmap!{"name".into() => UntaggedValue::string("JT").into_value(Tag::from(Span::new(5,10))), "date".into() => string("Sept 24-2019")}) ]), - "October 10-2019".into() => table(&vec![ + "October 10-2019".into() => table(&[ row(indexmap!{"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("October 10-2019")}) ]) }); diff --git a/src/commands/t_sort_by.rs b/src/commands/t_sort_by.rs index 447dd4f605..c4ef27f6ff 100644 --- a/src/commands/t_sort_by.rs +++ b/src/commands/t_sort_by.rs @@ -122,7 +122,7 @@ pub fn columns_sorted( value: UntaggedValue::Primitive(Primitive::Date(d)), .. } => format!("{}", d.format("%B %d-%Y")), - _ => k.as_string().unwrap().to_string(), + _ => k.as_string().unwrap(), }) .collect(); @@ -181,10 +181,7 @@ pub fn t_sort( Some(Value { value: UntaggedValue::Row(dict), .. - }) => dict - .get_data_by_key(label.borrow_spanned()) - .unwrap() - .clone(), + }) => dict.get_data_by_key(label.borrow_spanned()).unwrap(), _ => UntaggedValue::Table(vec![]).into_value(&origin_tag), }) .collect() @@ -223,7 +220,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -275,9 +272,9 @@ mod tests { Tag::unknown() ), vec![ - format!("August 23-2019").tagged_unknown(), - format!("September 24-2019").tagged_unknown(), - format!("October 10-2019").tagged_unknown() + "August 23-2019".to_string().tagged_unknown(), + "September 24-2019".to_string().tagged_unknown(), + "October 10-2019".to_string().tagged_unknown() ] ) } @@ -294,8 +291,8 @@ mod tests { Tag::unknown() ) .unwrap(), - table(&vec![table(&vec![ - table(&vec![ + table(&[table(&[ + table(&[ row( indexmap! {"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("August 23-2019")} ), @@ -306,7 +303,7 @@ mod tests { indexmap! {"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("August 23-2019")} ) ]), - table(&vec![ + table(&[ row( indexmap! {"name".into() => string("AR"), "country".into() => string("EC"), "date".into() => string("September 24-2019")} ), @@ -317,7 +314,7 @@ mod tests { indexmap! {"name".into() => string("JT"), "country".into() => string("NZ"), "date".into() => string("September 24-2019")} ) ]), - table(&vec![ + table(&[ row( indexmap! {"name".into() => string("YK"), "country".into() => string("US"), "date".into() => string("October 10-2019")} ), diff --git a/src/commands/to_delimited_data.rs b/src/commands/to_delimited_data.rs index e54553ae91..041a5158d3 100644 --- a/src/commands/to_delimited_data.rs +++ b/src/commands/to_delimited_data.rs @@ -132,10 +132,10 @@ fn to_string_tagged_value(v: &Value) -> Result { let tmp = format!("{}", b); Ok(tmp) } - UntaggedValue::Primitive(Primitive::Boolean(_)) => Ok(v.as_string()?.to_string()), - UntaggedValue::Primitive(Primitive::Decimal(_)) => Ok(v.as_string()?.to_string()), - UntaggedValue::Primitive(Primitive::Int(_)) => Ok(v.as_string()?.to_string()), - UntaggedValue::Primitive(Primitive::Path(_)) => Ok(v.as_string()?.to_string()), + UntaggedValue::Primitive(Primitive::Boolean(_)) => Ok(v.as_string()?), + UntaggedValue::Primitive(Primitive::Decimal(_)) => Ok(v.as_string()?), + UntaggedValue::Primitive(Primitive::Int(_)) => Ok(v.as_string()?), + UntaggedValue::Primitive(Primitive::Path(_)) => Ok(v.as_string()?), UntaggedValue::Table(_) => Ok(String::from("[Table]")), UntaggedValue::Row(_) => Ok(String::from("[Row]")), UntaggedValue::Primitive(Primitive::Line(s)) => Ok(s.to_string()), diff --git a/src/commands/where_.rs b/src/commands/where_.rs index 9e533d6c39..f37e879543 100644 --- a/src/commands/where_.rs +++ b/src/commands/where_.rs @@ -30,18 +30,17 @@ impl PerItemCommand for Where { _raw_args: &RawCommandArgs, input: Value, ) -> Result { - let input_clone = input.clone(); let condition = call_info.args.expect_nth(0)?; let stream = match condition { Value { value: UntaggedValue::Block(block), .. } => { - let result = block.invoke(&Scope::new(input_clone.clone())); + let result = block.invoke(&Scope::new(input.clone())); match result { Ok(v) => { if v.is_true() { - VecDeque::from(vec![Ok(ReturnSuccess::Value(input_clone))]) + VecDeque::from(vec![Ok(ReturnSuccess::Value(input))]) } else { VecDeque::new() } diff --git a/src/data/base.rs b/src/data/base.rs index 4fdee475dc..1ecb388763 100644 --- a/src/data/base.rs +++ b/src/data/base.rs @@ -214,7 +214,7 @@ mod tests { UntaggedValue::row(entries).into_untagged_value() } - fn table(list: &Vec) -> Value { + fn table(list: &[Value]) -> Value { UntaggedValue::table(list).into_untagged_value() } @@ -224,30 +224,26 @@ mod tests { move |(_obj_source, _column_path_tried, _err)| ShellError::unimplemented(reason) } - fn column_path(paths: &Vec) -> Tagged { - as_column_path(&table(&paths.iter().cloned().collect())).unwrap() + fn column_path(paths: &[Value]) -> Tagged { + as_column_path(&table(paths)).unwrap() } #[test] fn gets_matching_field_from_a_row() { let row = UntaggedValue::row(indexmap! { - "amigos".into() => table(&vec![string("andres"),string("jonathan"),string("yehuda")]) + "amigos".into() => table(&[string("andres"),string("jonathan"),string("yehuda")]) }) .into_untagged_value(); assert_eq!( row.get_data_by_key("amigos".spanned_unknown()).unwrap(), - table(&vec![ - string("andres"), - string("jonathan"), - string("yehuda") - ]) + table(&[string("andres"), string("jonathan"), string("yehuda")]) ); } #[test] fn gets_matching_field_from_nested_rows_inside_a_row() { - let field_path = column_path(&vec![string("package"), string("version")]); + let field_path = column_path(&[string("package"), string("version")]); let (version, tag) = string("0.4.0").into_parts(); @@ -270,7 +266,7 @@ mod tests { #[test] fn gets_first_matching_field_from_rows_with_same_field_inside_a_table() { - let field_path = column_path(&vec![string("package"), string("authors"), string("name")]); + let field_path = column_path(&[string("package"), string("authors"), string("name")]); let (_, tag) = string("Andrés N. Robalino").into_parts(); @@ -278,7 +274,7 @@ mod tests { "package".into() => row(indexmap! { "name".into() => string("nu"), "version".into() => string("0.4.0"), - "authors".into() => table(&vec![ + "authors".into() => table(&[ row(indexmap!{"name".into() => string("Andrés N. Robalino")}), row(indexmap!{"name".into() => string("Jonathan Turner")}), row(indexmap!{"name".into() => string("Yehuda Katz")}) @@ -294,7 +290,7 @@ mod tests { Box::new(error_callback("package.authors.name")) ) .unwrap(), - table(&vec![ + table(&[ string("Andrés N. Robalino"), string("Jonathan Turner"), string("Yehuda Katz") @@ -304,7 +300,7 @@ mod tests { #[test] fn column_path_that_contains_just_a_number_gets_a_row_from_a_table() { - let field_path = column_path(&vec![string("package"), string("authors"), int(0)]); + let field_path = column_path(&[string("package"), string("authors"), int(0)]); let (_, tag) = string("Andrés N. Robalino").into_parts(); @@ -312,7 +308,7 @@ mod tests { "package".into() => row(indexmap! { "name".into() => string("nu"), "version".into() => string("0.4.0"), - "authors".into() => table(&vec![ + "authors".into() => table(&[ row(indexmap!{"name".into() => string("Andrés N. Robalino")}), row(indexmap!{"name".into() => string("Jonathan Turner")}), row(indexmap!{"name".into() => string("Yehuda Katz")}) @@ -333,7 +329,7 @@ mod tests { #[test] fn column_path_that_contains_just_a_number_gets_a_row_from_a_row() { - let field_path = column_path(&vec![string("package"), string("authors"), string("0")]); + let field_path = column_path(&[string("package"), string("authors"), string("0")]); let (_, tag) = string("Andrés N. Robalino").into_parts(); @@ -365,10 +361,10 @@ mod tests { #[test] fn replaces_matching_field_from_a_row() { - let field_path = column_path(&vec![string("amigos")]); + let field_path = column_path(&[string("amigos")]); let sample = UntaggedValue::row(indexmap! { - "amigos".into() => table(&vec![ + "amigos".into() => table(&[ string("andres"), string("jonathan"), string("yehuda"), @@ -387,7 +383,7 @@ mod tests { #[test] fn replaces_matching_field_from_nested_rows_inside_a_row() { - let field_path = column_path(&vec![ + let field_path = column_path(&[ string("package"), string("authors"), string("los.3.caballeros"), @@ -396,14 +392,14 @@ mod tests { let sample = UntaggedValue::row(indexmap! { "package".into() => row(indexmap! { "authors".into() => row(indexmap! { - "los.3.mosqueteros".into() => table(&vec![string("andres::yehuda::jonathan")]), - "los.3.amigos".into() => table(&vec![string("andres::yehuda::jonathan")]), - "los.3.caballeros".into() => table(&vec![string("andres::yehuda::jonathan")]) + "los.3.mosqueteros".into() => table(&[string("andres::yehuda::jonathan")]), + "los.3.amigos".into() => table(&[string("andres::yehuda::jonathan")]), + "los.3.caballeros".into() => table(&[string("andres::yehuda::jonathan")]) }) }) }); - let replacement = table(&vec![string("yehuda::jonathan::andres")]); + let replacement = table(&[string("yehuda::jonathan::andres")]); let tag = replacement.tag.clone(); let actual = sample @@ -416,15 +412,15 @@ mod tests { UntaggedValue::row(indexmap! { "package".into() => row(indexmap! { "authors".into() => row(indexmap! { - "los.3.mosqueteros".into() => table(&vec![string("andres::yehuda::jonathan")]), - "los.3.amigos".into() => table(&vec![string("andres::yehuda::jonathan")]), - "los.3.caballeros".into() => replacement.clone()})})}) + "los.3.mosqueteros".into() => table(&[string("andres::yehuda::jonathan")]), + "los.3.amigos".into() => table(&[string("andres::yehuda::jonathan")]), + "los.3.caballeros".into() => replacement})})}) .into_value(tag) ); } #[test] fn replaces_matching_field_from_rows_inside_a_table() { - let field_path = column_path(&vec![ + let field_path = column_path(&[ string("shell_policy"), string("releases"), string("nu.version.arepa"), @@ -432,7 +428,7 @@ mod tests { let sample = UntaggedValue::row(indexmap! { "shell_policy".into() => row(indexmap! { - "releases".into() => table(&vec![ + "releases".into() => table(&[ row(indexmap! { "nu.version.arepa".into() => row(indexmap! { "code".into() => string("0.4.0"), "tag_line".into() => string("GitHub-era") @@ -467,7 +463,7 @@ mod tests { actual, UntaggedValue::row(indexmap! { "shell_policy".into() => row(indexmap! { - "releases".into() => table(&vec![ + "releases".into() => table(&[ row(indexmap! { "nu.version.arepa".into() => replacement }), diff --git a/src/data/base/shape.rs b/src/data/base/shape.rs index a6d1299570..101f0058c2 100644 --- a/src/data/base/shape.rs +++ b/src/data/base/shape.rs @@ -168,7 +168,7 @@ impl PrettyDebug for FormatInlineShape { (b::primitive(format!("{}", byte.get_value())) + b::space() + b::kind("B")) .group() } - _ => b::primitive(byte.format(1).to_string()), + _ => b::primitive(byte.format(1)), } } InlineShape::String(string) => b::primitive(string), diff --git a/src/data/value.rs b/src/data/value.rs index aa1eb3d521..e35415ff6a 100644 --- a/src/data/value.rs +++ b/src/data/value.rs @@ -22,7 +22,7 @@ pub fn date_from_str(s: Tagged<&str>) -> Result { } pub fn compare_values( - operator: &CompareOperator, + operator: CompareOperator, left: &UntaggedValue, right: &UntaggedValue, ) -> Result { diff --git a/src/deserializer.rs b/src/deserializer.rs index b82ad64a1f..882c9e8b22 100644 --- a/src/deserializer.rs +++ b/src/deserializer.rs @@ -403,7 +403,7 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut ConfigDeserializer<'de> { Value { value: UntaggedValue::Primitive(Primitive::Path(p)), .. - } => visit::, _>(p.clone().tagged(tag), name, fields, visitor), + } => visit::, _>(p.tagged(tag), name, fields, visitor), Value { value: UntaggedValue::Primitive(Primitive::Int(int)), .. diff --git a/src/evaluate/evaluator.rs b/src/evaluate/evaluator.rs index 6b3f84bc2c..d68c8c1c63 100644 --- a/src/evaluate/evaluator.rs +++ b/src/evaluate/evaluator.rs @@ -40,7 +40,7 @@ pub(crate) fn evaluate_baseline_expr( trace!("left={:?} right={:?}", left.value, right.value); - match apply_operator(&**binary.op(), &left, &right) { + match apply_operator(**binary.op(), &left, &right) { Ok(result) => Ok(result.into_value(tag)), Err((left_type, right_type)) => Err(ShellError::coerce_error( left_type.spanned(binary.left().span), @@ -120,7 +120,7 @@ pub(crate) fn evaluate_baseline_expr( }; } - Ok(item.value.clone().into_value(tag)) + Ok(item.value.into_value(tag)) } RawExpression::Boolean(_boolean) => unimplemented!(), } diff --git a/src/evaluate/operator.rs b/src/evaluate/operator.rs index 7eee06051b..c1c3c6a189 100644 --- a/src/evaluate/operator.rs +++ b/src/evaluate/operator.rs @@ -4,11 +4,11 @@ use nu_protocol::{Primitive, ShellTypeName, UntaggedValue, Value}; use std::ops::Not; pub fn apply_operator( - op: &CompareOperator, + op: CompareOperator, left: &Value, right: &Value, ) -> Result { - match *op { + match op { CompareOperator::Equal | CompareOperator::NotEqual | CompareOperator::LessThan diff --git a/src/format/table.rs b/src/format/table.rs index ed2110e666..fc450bdbc1 100644 --- a/src/format/table.rs +++ b/src/format/table.rs @@ -153,6 +153,7 @@ fn values_to_entries(values: &[Value], headers: &mut Vec, starting_idx: entries } +#[allow(clippy::ptr_arg)] fn max_per_column(headers: &[String], entries: &Entries, values_len: usize) -> Vec { let mut max_per_column = vec![]; diff --git a/src/plugins/nu_plugin_core_textview.rs b/src/plugins/nu_plugin_core_textview.rs index 3d06015de3..f59a2f53a2 100644 --- a/src/plugins/nu_plugin_core_textview.rs +++ b/src/plugins/nu_plugin_core_textview.rs @@ -38,7 +38,7 @@ impl Plugin for TextView { } fn paint_textview( - draw_commands: &Vec, + draw_commands: &[DrawCommand], starting_row: usize, use_color_buffer: bool, ) -> usize { @@ -148,8 +148,8 @@ fn scroll_view_lines_if_needed(draw_commands: Vec, use_color_buffer loop { if let Some(ev) = sync_stdin.next() { - match ev { - InputEvent::Keyboard(k) => match k { + if let InputEvent::Keyboard(k) = ev { + match k { KeyEvent::Esc => { break; } @@ -187,8 +187,7 @@ fn scroll_view_lines_if_needed(draw_commands: Vec, use_color_buffer paint_textview(&draw_commands, starting_row, use_color_buffer); } _ => {} - }, - _ => {} + } } } @@ -220,73 +219,67 @@ fn scroll_view(s: &str) { fn view_text_value(value: &Value) { let value_anchor = value.anchor(); - match &value.value { - UntaggedValue::Primitive(Primitive::String(ref s)) => { - if let Some(source) = value_anchor { - let extension: Option = match source { - AnchorLocation::File(file) => { - let path = Path::new(&file); - path.extension().map(|x| x.to_string_lossy().to_string()) - } - AnchorLocation::Url(url) => { - let url = url::Url::parse(&url); - if let Ok(url) = url { - let url = url.clone(); - if let Some(mut segments) = url.path_segments() { - if let Some(file) = segments.next_back() { - let path = Path::new(file); - path.extension().map(|x| x.to_string_lossy().to_string()) - } else { - None - } + if let UntaggedValue::Primitive(Primitive::String(ref s)) = &value.value { + if let Some(source) = value_anchor { + let extension: Option = match source { + AnchorLocation::File(file) => { + let path = Path::new(&file); + path.extension().map(|x| x.to_string_lossy().to_string()) + } + AnchorLocation::Url(url) => { + let url = url::Url::parse(&url); + if let Ok(url) = url { + if let Some(mut segments) = url.path_segments() { + if let Some(file) = segments.next_back() { + let path = Path::new(file); + path.extension().map(|x| x.to_string_lossy().to_string()) } else { None } } else { None } + } else { + None } - //FIXME: this probably isn't correct - AnchorLocation::Source(_source) => None, - }; + } + //FIXME: this probably isn't correct + AnchorLocation::Source(_source) => None, + }; - match extension { - Some(extension) => { - // Load these once at the start of your program - let ps: SyntaxSet = syntect::dumps::from_binary(include_bytes!( - "../../assets/syntaxes.bin" - )); + match extension { + Some(extension) => { + // Load these once at the start of your program + let ps: SyntaxSet = + syntect::dumps::from_binary(include_bytes!("../../assets/syntaxes.bin")); - if let Some(syntax) = ps.find_syntax_by_extension(&extension) { - let ts: ThemeSet = syntect::dumps::from_binary(include_bytes!( - "../../assets/themes.bin" - )); - let mut h = HighlightLines::new(syntax, &ts.themes["OneHalfDark"]); + if let Some(syntax) = ps.find_syntax_by_extension(&extension) { + let ts: ThemeSet = + syntect::dumps::from_binary(include_bytes!("../../assets/themes.bin")); + let mut h = HighlightLines::new(syntax, &ts.themes["OneHalfDark"]); - let mut v = vec![]; - for line in s.lines() { - let ranges: Vec<(Style, &str)> = h.highlight(line, &ps); + let mut v = vec![]; + for line in s.lines() { + let ranges: Vec<(Style, &str)> = h.highlight(line, &ps); - for range in ranges { - v.push(DrawCommand::DrawString(range.0, range.1.to_string())); - } - - v.push(DrawCommand::NextLine); + for range in ranges { + v.push(DrawCommand::DrawString(range.0, range.1.to_string())); } - scroll_view_lines_if_needed(v, true); - } else { - scroll_view(s); + + v.push(DrawCommand::NextLine); } - } - _ => { + scroll_view_lines_if_needed(v, true); + } else { scroll_view(s); } } - } else { - scroll_view(s); + _ => { + scroll_view(s); + } } + } else { + scroll_view(s); } - _ => {} } } diff --git a/src/shell.rs b/src/shell.rs index 14ec1c6755..bae7a96a6d 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -1,3 +1,5 @@ +#![allow(clippy::module_inception)] + pub(crate) mod completer; pub(crate) mod filesystem_shell; pub(crate) mod help_shell; diff --git a/src/shell/completer.rs b/src/shell/completer.rs index fac2af1c4a..84627568ba 100644 --- a/src/shell/completer.rs +++ b/src/shell/completer.rs @@ -97,56 +97,45 @@ impl NuCompleter { let replace_string = (replace_pos..pos).map(|_| " ").collect::(); line_copy.replace_range(replace_pos..pos, &replace_string); - match nu_parser::parse(&line_copy) { - Ok(val) => { - let source = Text::from(line); - let pipeline_list = vec![val.clone()]; - let mut iterator = - nu_parser::TokensIterator::all(&pipeline_list, source.clone(), val.span()); + if let Ok(val) = nu_parser::parse(&line_copy) { + let source = Text::from(line); + let pipeline_list = vec![val.clone()]; + let mut iterator = + nu_parser::TokensIterator::all(&pipeline_list, source.clone(), val.span()); - let expand_context = nu_parser::ExpandContext { - homedir: None, - registry: Box::new(self.commands.clone()), - source: &source, - }; + let expand_context = nu_parser::ExpandContext { + homedir: None, + registry: Box::new(self.commands.clone()), + source: &source, + }; - let result = nu_parser::expand_syntax( - &nu_parser::PipelineShape, - &mut iterator, - &expand_context, - ); + let result = + nu_parser::expand_syntax(&nu_parser::PipelineShape, &mut iterator, &expand_context); - if let Ok(result) = result { - for command in result.commands.list { - match command { - nu_parser::ClassifiedCommand::Internal( - nu_parser::InternalCommand { args, .. }, - ) => { - if replace_pos >= args.span.start() - && replace_pos <= args.span.end() - { - if let Some(named) = args.named { - for (name, _) in named.iter() { - let full_flag = format!("--{}", name); + if let Ok(result) = result { + for command in result.commands.list { + if let nu_parser::ClassifiedCommand::Internal(nu_parser::InternalCommand { + args, + .. + }) = command + { + if replace_pos >= args.span.start() && replace_pos <= args.span.end() { + if let Some(named) = args.named { + for (name, _) in named.iter() { + let full_flag = format!("--{}", name); - if full_flag.starts_with(&substring) { - matching_arguments.push( - rustyline::completion::Pair { - display: full_flag.clone(), - replacement: full_flag, - }, - ); - } - } + if full_flag.starts_with(&substring) { + matching_arguments.push(rustyline::completion::Pair { + display: full_flag.clone(), + replacement: full_flag, + }); } } } - _ => {} } } } } - _ => {} } matching_arguments diff --git a/src/shell/filesystem_shell.rs b/src/shell/filesystem_shell.rs index 9d5cb6c34c..bd0bbf77e0 100644 --- a/src/shell/filesystem_shell.rs +++ b/src/shell/filesystem_shell.rs @@ -212,7 +212,7 @@ impl Shell for FilesystemShell { return Err(ShellError::labeled_error( "Can not change to directory", "is not a directory", - v.tag().clone(), + v.tag(), )); } @@ -222,7 +222,7 @@ impl Shell for FilesystemShell { return Err(ShellError::labeled_error( "Can not change to directory", "directory not found", - v.tag().clone(), + v.tag(), )) } } @@ -753,80 +753,78 @@ impl Shell for FilesystemShell { new_dst.push(fragment); } - Ok((PathBuf::from(&source_file), PathBuf::from(new_dst))) + Ok((PathBuf::from(&source_file), new_dst)) }; let sources = sources.paths_applying_with(strategy)?; for (ref src, ref dst) in sources { - if src.is_dir() { - if !dst.exists() { - match std::fs::create_dir_all(dst) { - Err(e) => { - return Err(ShellError::labeled_error( - format!( - "Rename {:?} to {:?} aborted. {:}", - entry_file_name, - destination_file_name, - e.to_string(), - ), - format!( - "Rename {:?} to {:?} aborted. {:}", - entry_file_name, - destination_file_name, - e.to_string(), - ), - name_tag, - )); - } - Ok(o) => o, - } - } - } - - if src.is_file() { - match std::fs::copy(&src, &dst) { + if src.is_dir() && !dst.exists() { + match std::fs::create_dir_all(dst) { Err(e) => { return Err(ShellError::labeled_error( format!( "Rename {:?} to {:?} aborted. {:}", - src, + entry_file_name, destination_file_name, e.to_string(), ), format!( "Rename {:?} to {:?} aborted. {:}", - src, + entry_file_name, destination_file_name, e.to_string(), ), name_tag, )); } - Ok(_) => match std::fs::remove_file(&src) { - Err(e) => { - return Err(ShellError::labeled_error( - format!( - "Rename {:?} to {:?} aborted. {:}", - entry_file_name, - destination_file_name, - e.to_string(), - ), - format!( - "Rename {:?} to {:?} aborted. {:}", - entry_file_name, - destination_file_name, - e.to_string(), - ), - name_tag, - )); - } - Ok(o) => o, - }, - }; + Ok(o) => o, + } } } + if src.is_file() { + match std::fs::copy(&src, &dst) { + Err(e) => { + return Err(ShellError::labeled_error( + format!( + "Rename {:?} to {:?} aborted. {:}", + src, + destination_file_name, + e.to_string(), + ), + format!( + "Rename {:?} to {:?} aborted. {:}", + src, + destination_file_name, + e.to_string(), + ), + name_tag, + )); + } + Ok(_) => match std::fs::remove_file(&src) { + Err(e) => { + return Err(ShellError::labeled_error( + format!( + "Rename {:?} to {:?} aborted. {:}", + entry_file_name, + destination_file_name, + e.to_string(), + ), + format!( + "Rename {:?} to {:?} aborted. {:}", + entry_file_name, + destination_file_name, + e.to_string(), + ), + name_tag, + )); + } + Ok(o) => o, + }, + }; + } + match std::fs::remove_dir_all(entry) { Err(e) => { return Err(ShellError::labeled_error( diff --git a/src/shell/help_shell.rs b/src/shell/help_shell.rs index 48609cc7c5..d615629aec 100644 --- a/src/shell/help_shell.rs +++ b/src/shell/help_shell.rs @@ -97,7 +97,7 @@ impl HelpShell { } } x => { - cmds.push_back(x.clone()); + cmds.push_back(x); } } @@ -129,7 +129,7 @@ impl Shell for HelpShell { fn set_path(&mut self, path: String) { let _ = std::env::set_current_dir(&path); - self.path = path.clone(); + self.path = path; } fn ls( diff --git a/src/shell/helper.rs b/src/shell/helper.rs index 849643482f..09b6d8f65c 100644 --- a/src/shell/helper.rs +++ b/src/shell/helper.rs @@ -74,7 +74,7 @@ impl Highlighter for Helper { Ok(v) => v, }; - let tokens = vec![TokenNode::Pipeline(pipeline.clone())]; + let tokens = vec![TokenNode::Pipeline(pipeline)]; let mut tokens = TokensIterator::all(&tokens[..], Text::from(line), v.span()); let text = Text::from(line); diff --git a/src/shell/value_shell.rs b/src/shell/value_shell.rs index 00f2298285..77e3507f2d 100644 --- a/src/shell/value_shell.rs +++ b/src/shell/value_shell.rs @@ -61,7 +61,7 @@ impl ValueShell { } } x => { - shell_entries.push_back(x.clone()); + shell_entries.push_back(x); } } @@ -222,7 +222,7 @@ impl Shell for ValueShell { fn set_path(&mut self, path: String) { self.last_path = self.path.clone(); - self.path = path.clone(); + self.path = path; } fn complete( diff --git a/src/utils.rs b/src/utils.rs index fa7e93c15a..e73643d710 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -201,15 +201,12 @@ mod tests { sdx.push("fixtures"); sdx.push("formats"); - match dunce::canonicalize(sdx) { - Ok(path) => path, - Err(_) => panic!("Wrong path."), - } + dunce::canonicalize(sdx).expect("Wrong path") } fn structured_sample_record(key: &str, value: &str) -> Value { let mut record = TaggedDictBuilder::new(Tag::unknown()); - record.insert_untagged(key.clone(), UntaggedValue::string(value)); + record.insert_untagged(key, UntaggedValue::string(value)); record.into_value() } diff --git a/tests/shell/mod.rs b/tests/shell/mod.rs index ec8cec39fe..25909ea3ce 100644 --- a/tests/shell/mod.rs +++ b/tests/shell/mod.rs @@ -85,7 +85,7 @@ mod pipeline { ); assert!( - !actual.contains("~"), + !actual.contains('~'), format!("'{}' should not contain ~", actual) ); }