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 <artem@vorotnikov.me>
This commit is contained in:
Jonathan Turner
2019-12-31 20:36:08 +13:00
committed by GitHub
parent 8093612cac
commit 72838cc083
93 changed files with 754 additions and 852 deletions

View File

@ -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(),
),
),

View File

@ -107,7 +107,7 @@ impl SignatureRegistry for TestRegistry {
self.signatures.contains_key(name)
}
fn get(&self, name: &str) -> Option<Signature> {
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();

View File

@ -295,7 +295,7 @@ impl ColorSyntax for ExternalExpressionShape {
};
token_nodes.mutate_shapes(|shapes| atom.color_tokens(shapes));
return ExternalExpressionResult::Processed;
ExternalExpressionResult::Processed
}
}

View File

@ -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<String, NamedValue>,
}
impl NamedArguments {
pub fn new() -> NamedArguments {
NamedArguments {
named: IndexMap::new(),
}
Default::default()
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &NamedValue)> {
@ -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 {

View File

@ -111,15 +111,12 @@ impl ExpandSyntax for KeywordShape {
) -> Result<Self::Output, ParseError> {
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<Self::Output, ParseError> {
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(),
}
}

View File

@ -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<T>(
token_nodes: &mut TokensIterator<'_>,
expected: &'static str,
callback: impl FnOnce(UnspannedToken, Span, SingleError) -> Result<T, ParseError>,
) -> Result<T, ParseError> {
@ -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<T>(
token_nodes: &mut TokensIterator<'_>,
expected: &'static str,
callback: impl FnOnce(UnspannedToken, Span, SingleError) -> Result<T, ShellError>,
) -> Result<T, ShellError> {
@ -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))
}

View File

@ -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 (`<member>` -> `$it.<member>`)
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 (`<member>` -> `$it.<member>`)
@ -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

View File

@ -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,

View File

@ -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<Spanned<FlatShape>>) {
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<AtomicToken<'content>, 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()));
}
_ => {}
}
}

View File

@ -6,7 +6,7 @@ use nu_errors::ParseError;
use nu_source::{Span, SpannedItem, Tag};
pub fn expand_delimited_square(
children: &Vec<TokenNode>,
children: &[TokenNode],
span: Span,
context: &ExpandContext,
) -> Result<hir::Expression, ParseError> {

View File

@ -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"),
}
}
}

View File

@ -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
}
}
}

View File

@ -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"),
}
}
}

View File

@ -41,9 +41,8 @@ impl ExpandExpression for VariablePathShape {
let mut tail: Vec<PathMember> = 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<PathMember> = 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))),
}
}

View File

@ -35,7 +35,7 @@ pub enum FlatShape {
}
impl FlatShape {
pub fn from(token: &TokenNode, source: &Text, shapes: &mut Vec<Spanned<FlatShape>>) -> () {
pub fn from(token: &TokenNode, source: &Text, shapes: &mut Vec<Spanned<FlatShape>>) {
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()));
}
}

View File

@ -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<T>(
&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<usize> {
fn peek_pos(iterator: &TokensIterator<'_>, skip_ws: bool) -> Option<usize> {
let state = iterator.state();
let mut to = state.index;

View File

@ -24,13 +24,11 @@ pub(crate) fn debug_tokens(state: &TokensIteratorState, source: &str) -> Vec<Deb
out.push(DebugIteratorToken::Cursor);
}
let msg = token.debug(source).to_string();
if state.seen.contains(&i) {
out.push(DebugIteratorToken::Seen(format!("{}", token.debug(source))));
out.push(DebugIteratorToken::Seen(msg));
} else {
out.push(DebugIteratorToken::Unseen(format!(
"{}",
token.debug(source)
)));
out.push(DebugIteratorToken::Unseen(msg));
}
}

View File

@ -49,7 +49,7 @@ pub struct ColorFrame {
impl ColorFrame {
fn colored_leaf_description(&self, f: &mut impl io::Write) -> 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<FlatShape>) -> 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);
}

View File

@ -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");
}

View File

@ -1,3 +1,5 @@
#![allow(clippy::large_enum_variant, clippy::type_complexity)]
pub mod commands;
pub mod hir;
pub mod parse;

View File

@ -30,7 +30,7 @@ impl PrettyDebugWithSource for CallNode {
impl CallNode {
pub fn new(head: Box<TokenNode>, children: Vec<TokenNode>) -> CallNode {
if children.len() == 0 {
if children.is_empty() {
CallNode {
head,
children: None,

View File

@ -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<usize> {
@ -143,9 +143,7 @@ impl language_reporting::ReportingFiles for Files {
fn source(&self, span: Self::Span) -> Option<String> {
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())

View File

@ -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 => "..",
}

View File

@ -233,13 +233,9 @@ pub fn raw_number(input: NomSpan) -> IResult<NomSpan, RawNumber> {
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<NomSpan, NomSpan, (NomSpan, nom::error::ErrorKind)> = tag(".")(input);
@ -434,10 +430,8 @@ enum SawSpecial {
fn start_file_char(input: NomSpan) -> IResult<NomSpan, BitFlags<SawSpecial>> {
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<NomSpan, BitFlags<SawSpecial>> {
fn continue_file_char(input: NomSpan) -> IResult<NomSpan, BitFlags<SawSpecial>> {
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<NomSpan, BitFlags<SawSpecial>>
#[tracable_parser]
fn special_file_char(input: NomSpan) -> IResult<NomSpan, BitFlags<SawSpecial>> {
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<NomSpan, Spanned<Vec<TokenNo
let mut out = vec![];
pre_ws.map(|pre_ws| out.extend(pre_ws));
if let Some(pre_ws) = pre_ws {
out.extend(pre_ws)
}
out.extend(items.item);
post_ws.map(|post_ws| out.extend(post_ws));
if let Some(post_ws) = post_ws {
out.extend(post_ws)
}
Ok((input, out.spanned(Span::new(start, end))))
}
@ -917,7 +913,7 @@ fn parse_int<T>(frag: &str, neg: Option<T>) -> 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! {
<nodes>
">" -> b::token_list(vec![b::op(">")])
}
}
#[test]
fn test_gte_operator() {
equal_tokens! {
<nodes>
">=" -> b::token_list(vec![b::op(">=")])
}
}
#[test]
fn test_lt_operator() {
equal_tokens! {
<nodes>
"<" -> b::token_list(vec![b::op("<")])
}
}
#[test]
fn test_lte_operator() {
equal_tokens! {
<nodes>
"<=" -> b::token_list(vec![b::op("<=")])
}
}
#[test]
fn test_eq_operator() {
equal_tokens! {
<nodes>
"==" -> b::token_list(vec![b::op("==")])
}
}
#[test]
fn test_ne_operator() {
equal_tokens! {
<nodes>
"!=" -> b::token_list(vec![b::op("!=")])
<nodes>
"!=" -> b::token_list(vec![b::op("!=")])
}
}
#[test]
fn test_sim_operator() {
equal_tokens! {
<nodes>
"=~" -> b::token_list(vec![b::op("=~")])
}
}
#[test]
fn test_nsim_operator() {
equal_tokens! {
<nodes>
"!~" -> b::token_list(vec![b::op("!~")])
@ -1396,37 +1413,58 @@ mod tests {
<nodes>
"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! {
<nodes>
"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! {
<nodes>
"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! {
<nodes>
"echo $it" -> b::token_list(vec![b::bare("echo"), b::sp(), b::var("it")])
}
}
#[test]
fn test_smoke_single_command_open_raw() {
equal_tokens! {
<nodes>
"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! {
<nodes>
"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! {
<nodes>
"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! {
<nodes>
"inc --patch package.version" -> b::token_list(

View File

@ -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 => "}",

View File

@ -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<TokenNode>, span: impl Into<Span>) -> Spanned<CallNode> {
if input.len() == 0 {
if input.is_empty() {
panic!("BUG: spanned call (TODO)")
}

View File

@ -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),

View File

@ -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) => {