From 70bc9c4512aa13c4430080133fc32c579a5a0bc2 Mon Sep 17 00:00:00 2001 From: tyranron Date: Mon, 10 May 2021 11:41:56 +0300 Subject: [PATCH] Make Clippy almost happy on latest Rust --- juniper/src/ast.rs | 6 +- juniper/src/executor/look_ahead.rs | 4 +- juniper/src/executor/mod.rs | 2 + juniper/src/executor/owned_executor.rs | 12 +--- juniper/src/lib.rs | 2 +- juniper/src/parser/document.rs | 9 +-- juniper/src/parser/tests/document.rs | 5 +- juniper/src/schema/model.rs | 24 +++----- juniper/src/types/containers.rs | 6 +- juniper/src/types/pointers.rs | 10 +-- juniper/src/validation/multi_visitor.rs | 14 ++--- .../rules/unique_input_field_names.rs | 14 ++--- juniper/src/validation/test_harness.rs | 4 +- juniper/src/validation/traits.rs | 16 ++--- juniper_actix/src/lib.rs | 5 +- juniper_codegen/src/impl_scalar.rs | 61 +++++++------------ juniper_codegen/src/util/mod.rs | 23 ++++--- juniper_codegen/src/util/span_container.rs | 2 +- juniper_graphql_ws/src/lib.rs | 31 +++++----- juniper_graphql_ws/src/server_message.rs | 4 +- rustfmt.toml | 2 +- 21 files changed, 100 insertions(+), 156 deletions(-) diff --git a/juniper/src/ast.rs b/juniper/src/ast.rs index 88962f9b..86ba9e80 100644 --- a/juniper/src/ast.rs +++ b/juniper/src/ast.rs @@ -146,7 +146,9 @@ pub enum Definition<'a, S> { } #[doc(hidden)] -pub type Document<'a, S> = Vec>; +pub type Document<'a, S> = [Definition<'a, S>]; +#[doc(hidden)] +pub type OwnedDocument<'a, S> = Vec>; /// Parse an unstructured input value into a Rust data type. /// @@ -381,7 +383,7 @@ where /// /// This constructs a new IndexMap that contain references to the keys /// and values in `self`. - pub fn to_object_value<'a>(&'a self) -> Option> { + pub fn to_object_value(&self) -> Option> { match *self { InputValue::Object(ref o) => Some( o.iter() diff --git a/juniper/src/executor/look_ahead.rs b/juniper/src/executor/look_ahead.rs index 68dfac2b..b4e65952 100644 --- a/juniper/src/executor/look_ahead.rs +++ b/juniper/src/executor/look_ahead.rs @@ -440,7 +440,7 @@ impl<'a, S> LookAheadMethods<'a, S> for LookAheadSelection<'a, S> { mod tests { use super::*; use crate::{ - ast::Document, + ast::{Document, OwnedDocument}, parser::UnlocatedParseResult, schema::model::SchemaType, validation::test_harness::{MutationRoot, QueryRoot, SubscriptionRoot}, @@ -448,7 +448,7 @@ mod tests { }; use std::collections::HashMap; - fn parse_document_source(q: &str) -> UnlocatedParseResult> + fn parse_document_source(q: &str) -> UnlocatedParseResult> where S: ScalarValue, { diff --git a/juniper/src/executor/mod.rs b/juniper/src/executor/mod.rs index 7a33e88b..f4b56c25 100644 --- a/juniper/src/executor/mod.rs +++ b/juniper/src/executor/mod.rs @@ -326,6 +326,7 @@ where { type Type = T; + #[allow(clippy::type_complexity)] fn into(self, _: &'a C) -> FieldResult)>, S> { Ok(self.map(|(ctx, v)| (ctx, Some(v)))) } @@ -353,6 +354,7 @@ where { type Type = T; + #[allow(clippy::type_complexity)] fn into(self, _: &'a C) -> FieldResult)>, S2> { self.map(|o| o.map(|(ctx, v)| (ctx, Some(v)))) .map_err(FieldError::map_scalar_value) diff --git a/juniper/src/executor/owned_executor.rs b/juniper/src/executor/owned_executor.rs index 366425f2..28b03c3a 100644 --- a/juniper/src/executor/owned_executor.rs +++ b/juniper/src/executor/owned_executor.rs @@ -112,16 +112,8 @@ where Executor { fragments: &self.fragments, variables: &self.variables, - current_selection_set: if let Some(s) = &self.current_selection_set { - Some(&s[..]) - } else { - None - }, - parent_selection_set: if let Some(s) = &self.parent_selection_set { - Some(&s[..]) - } else { - None - }, + current_selection_set: self.current_selection_set.as_deref(), + parent_selection_set: self.parent_selection_set.as_deref(), current_type: self.current_type.clone(), schema: self.schema, context: self.context, diff --git a/juniper/src/lib.rs b/juniper/src/lib.rs index bb0ef3f1..1cd6a3de 100644 --- a/juniper/src/lib.rs +++ b/juniper/src/lib.rs @@ -319,7 +319,7 @@ where SubscriptionT::TypeInfo: Sync, S: ScalarValue + Send + Sync, { - let document: crate::ast::Document<'a, S> = + let document: crate::ast::OwnedDocument<'a, S> = parse_document_source(document_source, &root_node.schema)?; { diff --git a/juniper/src/parser/document.rs b/juniper/src/parser/document.rs index e83431f4..096b3991 100644 --- a/juniper/src/parser/document.rs +++ b/juniper/src/parser/document.rs @@ -1,8 +1,9 @@ use std::borrow::Cow; use crate::ast::{ - Arguments, Definition, Directive, Document, Field, Fragment, FragmentSpread, InlineFragment, - InputValue, Operation, OperationType, Selection, Type, VariableDefinition, VariableDefinitions, + Arguments, Definition, Directive, Field, Fragment, FragmentSpread, InlineFragment, InputValue, + Operation, OperationType, OwnedDocument, Selection, Type, VariableDefinition, + VariableDefinitions, }; use crate::{ @@ -21,7 +22,7 @@ use crate::{ pub fn parse_document_source<'a, 'b, S>( s: &'a str, schema: &'b SchemaType<'b, S>, -) -> UnlocatedParseResult<'a, Document<'a, S>> +) -> UnlocatedParseResult<'a, OwnedDocument<'a, S>> where S: ScalarValue, { @@ -33,7 +34,7 @@ where fn parse_document<'a, 'b, S>( parser: &mut Parser<'a>, schema: &'b SchemaType<'b, S>, -) -> UnlocatedParseResult<'a, Document<'a, S>> +) -> UnlocatedParseResult<'a, OwnedDocument<'a, S>> where S: ScalarValue, { diff --git a/juniper/src/parser/tests/document.rs b/juniper/src/parser/tests/document.rs index 5958ec7d..52ad0bbd 100644 --- a/juniper/src/parser/tests/document.rs +++ b/juniper/src/parser/tests/document.rs @@ -1,6 +1,7 @@ use crate::{ ast::{ - Arguments, Definition, Document, Field, InputValue, Operation, OperationType, Selection, + Arguments, Definition, Field, InputValue, Operation, OperationType, OwnedDocument, + Selection, }, parser::{document::parse_document_source, ParseError, SourcePosition, Spanning, Token}, schema::model::SchemaType, @@ -9,7 +10,7 @@ use crate::{ value::{DefaultScalarValue, ScalarValue}, }; -fn parse_document(s: &str) -> Document +fn parse_document(s: &str) -> OwnedDocument where S: ScalarValue, { diff --git a/juniper/src/schema/model.rs b/juniper/src/schema/model.rs index 51cb46ad..4872d1a0 100644 --- a/juniper/src/schema/model.rs +++ b/juniper/src/schema/model.rs @@ -293,14 +293,10 @@ impl<'a, S> SchemaType<'a, S> { /// Get the mutation type from the schema. pub fn mutation_type(&self) -> Option> { - if let Some(ref mutation_type_name) = self.mutation_type_name { - Some( - self.type_by_name(mutation_type_name) - .expect("Mutation type does not exist in schema"), - ) - } else { - None - } + self.mutation_type_name.as_ref().map(|name| { + self.type_by_name(name) + .expect("Mutation type does not exist in schema") + }) } /// Get the concrete mutation type from the schema. @@ -313,14 +309,10 @@ impl<'a, S> SchemaType<'a, S> { /// Get the subscription type. pub fn subscription_type(&self) -> Option> { - if let Some(ref subscription_type_name) = self.subscription_type_name { - Some( - self.type_by_name(subscription_type_name) - .expect("Subscription type does not exist in schema"), - ) - } else { - None - } + self.subscription_type_name.as_ref().map(|name| { + self.type_by_name(name) + .expect("Subscription type does not exist in schema") + }) } /// Get the concrete subscription type. diff --git a/juniper/src/types/containers.rs b/juniper/src/types/containers.rs index 074901ac..cb3d2ad0 100644 --- a/juniper/src/types/containers.rs +++ b/juniper/src/types/containers.rs @@ -299,7 +299,6 @@ where S: ScalarValue + Send + Sync, { use futures::stream::{FuturesOrdered, StreamExt as _}; - use std::iter::FromIterator; let stop_on_null = executor .current_type() @@ -307,8 +306,9 @@ where .expect("Current type is not a list type") .is_non_null(); - let iter = items.map(|it| async move { executor.resolve_into_value_async(info, it).await }); - let mut futures = FuturesOrdered::from_iter(iter); + let mut futures = items + .map(|it| async move { executor.resolve_into_value_async(info, it).await }) + .collect::>(); let mut values = Vec::with_capacity(futures.len()); while let Some(value) = futures.next().await { diff --git a/juniper/src/types/pointers.rs b/juniper/src/types/pointers.rs index 0c3d0f7e..85720922 100644 --- a/juniper/src/types/pointers.rs +++ b/juniper/src/types/pointers.rs @@ -94,10 +94,7 @@ where T: FromInputValue, { fn from_input_value(v: &InputValue) -> Option> { - match >::from_input_value(v) { - Some(v) => Some(Box::new(v)), - None => None, - } + >::from_input_value(v).map(Box::new) } } @@ -289,10 +286,7 @@ where T: FromInputValue, { fn from_input_value(v: &InputValue) -> Option> { - match >::from_input_value(v) { - Some(v) => Some(Arc::new(v)), - None => None, - } + >::from_input_value(v).map(Arc::new) } } diff --git a/juniper/src/validation/multi_visitor.rs b/juniper/src/validation/multi_visitor.rs index 5f76802d..cdefd9d4 100644 --- a/juniper/src/validation/multi_visitor.rs +++ b/juniper/src/validation/multi_visitor.rs @@ -230,19 +230,11 @@ where self.1.exit_list_value(ctx, l); } - fn enter_object_value( - &mut self, - ctx: &mut ValidatorContext<'a, S>, - o: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { + fn enter_object_value(&mut self, ctx: &mut ValidatorContext<'a, S>, o: SpannedObject<'a, S>) { self.0.enter_object_value(ctx, o); self.1.enter_object_value(ctx, o); } - fn exit_object_value( - &mut self, - ctx: &mut ValidatorContext<'a, S>, - o: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { + fn exit_object_value(&mut self, ctx: &mut ValidatorContext<'a, S>, o: SpannedObject<'a, S>) { self.0.exit_object_value(ctx, o); self.1.exit_object_value(ctx, o); } @@ -264,3 +256,5 @@ where self.1.exit_object_field(ctx, f); } } + +type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning, Spanning>)>>; diff --git a/juniper/src/validation/rules/unique_input_field_names.rs b/juniper/src/validation/rules/unique_input_field_names.rs index e2a6b3a3..db507502 100644 --- a/juniper/src/validation/rules/unique_input_field_names.rs +++ b/juniper/src/validation/rules/unique_input_field_names.rs @@ -21,19 +21,11 @@ impl<'a, S> Visitor<'a, S> for UniqueInputFieldNames<'a> where S: ScalarValue, { - fn enter_object_value( - &mut self, - _: &mut ValidatorContext<'a, S>, - _: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { + fn enter_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) { self.known_name_stack.push(HashMap::new()); } - fn exit_object_value( - &mut self, - _: &mut ValidatorContext<'a, S>, - _: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { + fn exit_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) { self.known_name_stack.pop(); } @@ -58,6 +50,8 @@ where } } +type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning, Spanning>)>>; + fn error_message(field_name: &str) -> String { format!("There can only be one input field named \"{}\"", field_name) } diff --git a/juniper/src/validation/test_harness.rs b/juniper/src/validation/test_harness.rs index 8d3acd19..a2af2194 100644 --- a/juniper/src/validation/test_harness.rs +++ b/juniper/src/validation/test_harness.rs @@ -865,7 +865,9 @@ where let mut ctx = ValidatorContext::new(unsafe { ::std::mem::transmute(&root.schema) }, &doc); let mut mv = MultiVisitorNil.with(factory()); - visit(&mut mv, &mut ctx, unsafe { ::std::mem::transmute(&doc) }); + visit(&mut mv, &mut ctx, unsafe { + ::std::mem::transmute(doc.as_slice()) + }); ctx.into_errors() } diff --git a/juniper/src/validation/traits.rs b/juniper/src/validation/traits.rs index c4e6852d..5a615b11 100644 --- a/juniper/src/validation/traits.rs +++ b/juniper/src/validation/traits.rs @@ -128,18 +128,8 @@ where ) { } - fn enter_object_value( - &mut self, - _: &mut ValidatorContext<'a, S>, - _: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { - } - fn exit_object_value( - &mut self, - _: &mut ValidatorContext<'a, S>, - _: Spanning<&'a Vec<(Spanning, Spanning>)>>, - ) { - } + fn enter_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) {} + fn exit_object_value(&mut self, _: &mut ValidatorContext<'a, S>, _: SpannedObject<'a, S>) {} fn enter_object_field( &mut self, @@ -154,3 +144,5 @@ where ) { } } + +type SpannedObject<'a, S> = Spanning<&'a Vec<(Spanning, Spanning>)>>; diff --git a/juniper_actix/src/lib.rs b/juniper_actix/src/lib.rs index 23f4cc05..cc68ae63 100644 --- a/juniper_actix/src/lib.rs +++ b/juniper_actix/src/lib.rs @@ -73,10 +73,7 @@ where operation_name, variables, } = get_req; - let variables = match variables { - Some(variables) => Some(serde_json::from_str(&variables).unwrap()), - None => None, - }; + let variables = variables.map(|s| serde_json::from_str(&s).unwrap()); Self::new(query, operation_name, variables) } } diff --git a/juniper_codegen/src/impl_scalar.rs b/juniper_codegen/src/impl_scalar.rs index e022e575..9d828df8 100644 --- a/juniper_codegen/src/impl_scalar.rs +++ b/juniper_codegen/src/impl_scalar.rs @@ -25,11 +25,9 @@ struct ScalarCodegenInput { fn get_first_method_arg( inputs: syn::punctuated::Punctuated, ) -> Option { - if let Some(fn_arg) = inputs.first() { - if let syn::FnArg::Typed(pat_type) = fn_arg { - if let syn::Pat::Ident(pat_ident) = &*pat_type.pat { - return Some(pat_ident.ident.clone()); - } + if let Some(syn::FnArg::Typed(pat_type)) = inputs.first() { + if let syn::Pat::Ident(pat_ident) = &*pat_type.pat { + return Some(pat_ident.ident.clone()); } } @@ -45,39 +43,27 @@ fn get_method_return_type(output: syn::ReturnType) -> Option { // Find the enum type by inspecting the type parameter on the return value fn get_enum_type(return_type: &Option) -> Option { - if let Some(return_type) = return_type { - match return_type { - syn::Type::Path(type_path) => { - let path_segment = type_path - .path - .segments - .iter() - .find(|ps| match ps.arguments { - syn::PathArguments::AngleBracketed(_) => true, - _ => false, - }); + if let Some(syn::Type::Path(type_path)) = return_type { + let path_segment = type_path + .path + .segments + .iter() + .find(|ps| matches!(ps.arguments, syn::PathArguments::AngleBracketed(_))); - if let Some(path_segment) = path_segment { - match &path_segment.arguments { - syn::PathArguments::AngleBracketed(generic_args) => { - let generic_type_arg = - generic_args.args.iter().find(|generic_type_arg| { - matches!(generic_type_arg, syn::GenericArgument::Type(_)) - }); + if let Some(path_segment) = path_segment { + if let syn::PathArguments::AngleBracketed(generic_args) = &path_segment.arguments { + let generic_type_arg = generic_args.args.iter().find(|generic_type_arg| { + matches!(generic_type_arg, syn::GenericArgument::Type(_)) + }); - if let Some(syn::GenericArgument::Type(syn::Type::Path(type_path))) = - generic_type_arg - { - if let Some(path_segment) = type_path.path.segments.first() { - return Some(path_segment.clone()); - } - } - } - _ => (), + if let Some(syn::GenericArgument::Type(syn::Type::Path(type_path))) = + generic_type_arg + { + if let Some(path_segment) = type_path.path.segments.first() { + return Some(path_segment.clone()); } } } - _ => (), } } @@ -109,8 +95,8 @@ impl syn::parse::Parse for ScalarCodegenInput { } for impl_item in parse_custom_scalar_value_impl.items { - match impl_item { - syn::ImplItem::Method(method) => match method.sig.ident.to_string().as_str() { + if let syn::ImplItem::Method(method) = impl_item { + match method.sig.ident.to_string().as_str() { "resolve" => { resolve_body = Some(method.block); } @@ -130,9 +116,8 @@ impl syn::parse::Parse for ScalarCodegenInput { from_str_body = Some(method.block); } _ => (), - }, - _ => (), - }; + } + } } let custom_data_type = if custom_data_type_is_struct { diff --git a/juniper_codegen/src/util/mod.rs b/juniper_codegen/src/util/mod.rs index b636d280..d007e173 100644 --- a/juniper_codegen/src/util/mod.rs +++ b/juniper_codegen/src/util/mod.rs @@ -161,7 +161,7 @@ fn join_doc_strings(docs: &[String]) -> String { docs.iter() .map(|s| s.as_str().trim_end()) // Trim leading space. - .map(|s| if s.starts_with(' ') { &s[1..] } else { s }) + .map(|s| s.strip_prefix(' ').unwrap_or(s)) // Add newline, exept when string ends in a continuation backslash or is the last line. .enumerate() .fold(String::new(), |mut buffer, (index, s)| { @@ -227,13 +227,11 @@ pub fn to_camel_case(s: &str) -> String { // Handle `_` and `__` to be more friendly with the `_var` convention for unused variables, and // GraphQL introspection identifiers. - let s_iter = if s.starts_with("__") { + let s_iter = if let Some(s) = s.strip_prefix("__") { dest.push_str("__"); - &s[2..] - } else if s.starts_with('_') { - &s[1..] - } else { s + } else { + s.strip_prefix('_').unwrap_or(s) } .split('_') .enumerate(); @@ -434,9 +432,10 @@ impl ObjectAttributes { } Ok(a) } else { - let mut a = Self::default(); - a.description = get_doc_comment(attrs); - Ok(a) + Ok(Self { + description: get_doc_comment(attrs), + ..Self::default() + }) } } } @@ -500,7 +499,7 @@ enum FieldAttribute { Deprecation(SpanContainer), Skip(SpanContainer), Arguments(HashMap), - Default(SpanContainer>), + Default(Box>>), } impl Parse for FieldAttribute { @@ -573,7 +572,7 @@ impl Parse for FieldAttribute { SpanContainer::new(ident.span(), None, None) }; - Ok(FieldAttribute::Default(default_expr)) + Ok(FieldAttribute::Default(Box::new(default_expr))) } _ => Err(syn::Error::new(ident.span(), "unknown attribute")), } @@ -617,7 +616,7 @@ impl Parse for FieldAttributes { output.arguments = args; } FieldAttribute::Default(expr) => { - output.default = Some(expr); + output.default = Some(*expr); } } } diff --git a/juniper_codegen/src/util/span_container.rs b/juniper_codegen/src/util/span_container.rs index f335da9f..370f17a7 100644 --- a/juniper_codegen/src/util/span_container.rs +++ b/juniper_codegen/src/util/span_container.rs @@ -21,7 +21,7 @@ impl ToTokens for SpanContainer { impl SpanContainer { pub fn new(ident: Span, expr: Option, val: T) -> Self { - Self { ident, expr, val } + Self { expr, ident, val } } pub fn span_ident(&self) -> Span { diff --git a/juniper_graphql_ws/src/lib.rs b/juniper_graphql_ws/src/lib.rs index 59834ba3..b832d99d 100644 --- a/juniper_graphql_ws/src/lib.rs +++ b/juniper_graphql_ws/src/lib.rs @@ -486,6 +486,7 @@ enum ConnectionSinkState> { state: ConnectionState, }, HandlingMessage { + #[allow(clippy::type_complexity)] result: BoxFuture<'static, (ConnectionState, BoxStream<'static, Reaction>)>, }, Closed, @@ -607,26 +608,22 @@ where } // Poll the reactions for new outgoing messages. - loop { - if !self.reactions.is_empty() { - match Pin::new(&mut self.reactions).poll_next(cx) { - Poll::Ready(Some(reaction)) => match reaction { - Reaction::ServerMessage(msg) => return Poll::Ready(Some(msg)), - Reaction::EndStream => return Poll::Ready(None), - }, - Poll::Ready(None) => { - // In rare cases, the reaction stream may terminate. For example, this will - // happen if the first message we receive does not require any reaction. Just - // recreate it in that case. - self.reactions = SelectAll::new(); - return Poll::Pending; - } - Poll::Pending => return Poll::Pending, + if !self.reactions.is_empty() { + match Pin::new(&mut self.reactions).poll_next(cx) { + Poll::Ready(Some(reaction)) => match reaction { + Reaction::ServerMessage(msg) => return Poll::Ready(Some(msg)), + Reaction::EndStream => return Poll::Ready(None), + }, + Poll::Ready(None) => { + // In rare cases, the reaction stream may terminate. For example, this will + // happen if the first message we receive does not require any reaction. Just + // recreate it in that case. + self.reactions = SelectAll::new(); } - } else { - return Poll::Pending; + _ => (), } } + Poll::Pending } } diff --git a/juniper_graphql_ws/src/server_message.rs b/juniper_graphql_ws/src/server_message.rs index d3f1a59a..bad7091a 100644 --- a/juniper_graphql_ws/src/server_message.rs +++ b/juniper_graphql_ws/src/server_message.rs @@ -39,9 +39,9 @@ pub struct ErrorPayload { impl ErrorPayload { /// For this to be okay, the caller must guarantee that the error can only reference data from /// execution_params and that execution_params has not been modified or moved. - pub(crate) unsafe fn new_unchecked<'a>( + pub(crate) unsafe fn new_unchecked( execution_params: Box, - error: GraphQLError<'a>, + error: GraphQLError<'_>, ) -> Self { Self { _execution_params: Some(execution_params), diff --git a/rustfmt.toml b/rustfmt.toml index 8586c40c..00146874 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,2 +1,2 @@ -merge_imports = true +imports_granularity = "Crate" use_field_init_shorthand = true