diff --git a/benches/Cargo.toml b/benches/Cargo.toml index c5014f5a..57a1c9d4 100644 --- a/benches/Cargo.toml +++ b/benches/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "juniper_benchmarks" version = "0.0.0" -edition = "2018" +edition = "2021" authors = ["Christoph Herzog "] publish = false diff --git a/benches/benches/benchmark.rs b/benches/benches/benchmark.rs index 7aa5da65..c2ba501c 100644 --- a/benches/benches/benchmark.rs +++ b/benches/benches/benchmark.rs @@ -38,7 +38,7 @@ fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) { b.iter(|| { j::execute_sync( SYNC_QUERY, - vec![("ids".to_string(), ids.clone())].into_iter().collect(), + vec![("ids".to_owned(), ids.clone())].into_iter().collect(), ) }) }, @@ -58,7 +58,7 @@ fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) { b.iter(|| { let f = j::execute( ASYNC_QUERY, - vec![("ids".to_string(), ids.clone())].into_iter().collect(), + vec![("ids".to_owned(), ids.clone())].into_iter().collect(), ); rt.block_on(f) }) @@ -77,7 +77,7 @@ fn bench_sync_vs_async_users_flat_instant(c: &mut Criterion) { b.iter(|| { let f = j::execute( ASYNC_QUERY, - vec![("ids".to_string(), ids.clone())].into_iter().collect(), + vec![("ids".to_owned(), ids.clone())].into_iter().collect(), ); rt.block_on(f) }) diff --git a/benches/src/lib.rs b/benches/src/lib.rs index 526d0043..c8ad5b51 100644 --- a/benches/src/lib.rs +++ b/benches/src/lib.rs @@ -11,11 +11,11 @@ pub type QueryResult = Result< String, >; -pub struct Context {} +pub struct Context; impl Context { fn new() -> Self { - Self {} + Self } } @@ -51,8 +51,8 @@ impl User { Self { id, kind: UserKind::Admin, - username: "userx".to_string(), - email: "userx@domain.com".to_string(), + username: "userx".into(), + email: "userx@domain.com".into(), gender: Some(Gender::Female), } } @@ -97,7 +97,7 @@ pub fn new_schema() -> RootNode<'static, Query, EmptyMutation, EmptySub pub fn execute_sync(query: &str, vars: Variables) -> QueryResult { let root = new_schema(); let ctx = Context::new(); - juniper::execute_sync(query, None, &root, &vars, &ctx).map_err(|e| format!("{:?}", e)) + juniper::execute_sync(query, None, &root, &vars, &ctx).map_err(|e| format!("{e:?}")) } pub async fn execute(query: &str, vars: Variables) -> QueryResult { @@ -105,5 +105,5 @@ pub async fn execute(query: &str, vars: Variables) -> QueryResult { let ctx = Context::new(); juniper::execute(query, None, &root, &vars, &ctx) .await - .map_err(|e| format!("{:?}", e)) + .map_err(|e| format!("{e:?}")) } diff --git a/book/book.toml b/book/book.toml index 9fc67124..9dad3932 100644 --- a/book/book.toml +++ b/book/book.toml @@ -13,4 +13,4 @@ create-missing = false git_repository_url = "https://github.com/graphql-rs/juniper" [rust] -edition = "2018" +edition = "2021" diff --git a/book/src/advanced/dataloaders.md b/book/src/advanced/dataloaders.md index 560f6048..ef03afc1 100644 --- a/book/src/advanced/dataloaders.md +++ b/book/src/advanced/dataloaders.md @@ -68,7 +68,7 @@ use std::env; pub fn get_db_conn() -> Connection { let pg_connection_string = env::var("DATABASE_URI").expect("need a db uri"); - println!("Connecting to {}", pg_connection_string); + println!("Connecting to {pg_connection_string}"); let conn = Connection::connect(&pg_connection_string[..], TlsMode::None).unwrap(); println!("Connection is fine"); conn @@ -101,7 +101,7 @@ impl BatchFn for CultBatcher { // A hashmap is used, as we need to return an array which maps each original key to a Cult. async fn load(&self, keys: &[i32]) -> HashMap { - println!("load cult batch {:?}", keys); + println!("load cult batch {keys:?}"); let mut cult_hashmap = HashMap::new(); get_cult_by_ids(&mut cult_hashmap, keys.to_vec()); cult_hashmap diff --git a/book/src/advanced/introspection.md b/book/src/advanced/introspection.md index 3fabcb73..d7bc7c2f 100644 --- a/book/src/advanced/introspection.md +++ b/book/src/advanced/introspection.md @@ -66,7 +66,7 @@ type Schema = juniper::RootNode< fn main() { // Create a context object. - let ctx = Context{}; + let ctx = Context; // Run the built-in introspection query. let (res, _errors) = juniper::introspect( diff --git a/book/src/advanced/subscriptions.md b/book/src/advanced/subscriptions.md index 90877c42..89ce7bf4 100644 --- a/book/src/advanced/subscriptions.md +++ b/book/src/advanced/subscriptions.md @@ -98,7 +98,7 @@ where [`Connection`][Connection] is a `Stream` of values returned by the operati # # impl Database { # fn new() -> Self { -# Self {} +# Self # } # } # @@ -126,7 +126,7 @@ where [`Connection`][Connection] is a `Stream` of values returned by the operati type Schema = RootNode<'static, Query, EmptyMutation, Subscription>; fn schema() -> Schema { - Schema::new(Query {}, EmptyMutation::new(), Subscription {}) + Schema::new(Query, EmptyMutation::new(), Subscription) } async fn run_subscription() { diff --git a/book/src/quickstart.md b/book/src/quickstart.md index b8ff7226..770b86a6 100644 --- a/book/src/quickstart.md +++ b/book/src/quickstart.md @@ -130,7 +130,7 @@ impl Mutation { type Schema = juniper::RootNode<'static, Query, Mutation, EmptySubscription>; # # fn main() { -# let _ = Schema::new(Query, Mutation{}, EmptySubscription::new()); +# let _ = Schema::new(Query, Mutation, EmptySubscription::new()); # } ``` diff --git a/book/src/servers/iron.md b/book/src/servers/iron.md index 9c81fc4b..38782c36 100644 --- a/book/src/servers/iron.md +++ b/book/src/servers/iron.md @@ -50,7 +50,7 @@ struct Root; #[juniper::graphql_object] impl Root { fn foo() -> String { - "Bar".to_owned() + "Bar".into() } } diff --git a/book/src/types/interfaces.md b/book/src/types/interfaces.md index 6a394ceb..87b72348 100644 --- a/book/src/types/interfaces.md +++ b/book/src/types/interfaces.md @@ -227,7 +227,7 @@ impl ObjA { // ^^ the evaluated program panicked at // 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` // isn't present on the interface and so has to be nullable.' - is_present.then(|| self.id.as_str()).unwrap_or("missing") + is_present.then_some(&self.id).unwrap_or("missing") } } diff --git a/book/src/types/objects/complex_fields.md b/book/src/types/objects/complex_fields.md index 86d310ec..f8aa1399 100644 --- a/book/src/types/objects/complex_fields.md +++ b/book/src/types/objects/complex_fields.md @@ -157,7 +157,7 @@ They can have custom descriptions and default values. # extern crate juniper; # use juniper::graphql_object; # -struct Person {} +struct Person; #[graphql_object] impl Person { @@ -177,7 +177,7 @@ impl Person { #[graphql(default)] arg2: i32, ) -> String { - format!("{} {}", arg1, arg2) + format!("{arg1} {arg2}") } } # diff --git a/book/src/types/objects/error_handling.md b/book/src/types/objects/error_handling.md index 1d4d8247..5404c4bf 100644 --- a/book/src/types/objects/error_handling.md +++ b/book/src/types/objects/error_handling.md @@ -242,15 +242,15 @@ impl Mutation { if !(10 <= name.len() && name.len() <= 100) { errors.push(ValidationError { - field: "name".to_string(), - message: "between 10 and 100".to_string() + field: "name".into(), + message: "between 10 and 100".into(), }); } if !(1 <= quantity && quantity <= 10) { errors.push(ValidationError { - field: "quantity".to_string(), - message: "between 1 and 10".to_string() + field: "quantity".into(), + message: "between 1 and 10".into(), }); } @@ -338,11 +338,11 @@ impl Mutation { }; if !(10 <= name.len() && name.len() <= 100) { - error.name = Some("between 10 and 100".to_string()); + error.name = Some("between 10 and 100".into()); } if !(1 <= quantity && quantity <= 10) { - error.quantity = Some("between 1 and 10".to_string()); + error.quantity = Some("between 1 and 10".into()); } if error.name.is_none() && error.quantity.is_none() { @@ -436,11 +436,11 @@ impl Mutation { }; if !(10 <= name.len() && name.len() <= 100) { - error.name = Some("between 10 and 100".to_string()); + error.name = Some("between 10 and 100".into()); } if !(1 <= quantity && quantity <= 10) { - error.quantity = Some("between 1 and 10".to_string()); + error.quantity = Some("between 1 and 10".into()); } if error.name.is_none() && error.quantity.is_none() { diff --git a/book/src/types/scalars.md b/book/src/types/scalars.md index 052fe8dc..5f2f44b0 100644 --- a/book/src/types/scalars.md +++ b/book/src/types/scalars.md @@ -145,14 +145,13 @@ impl UserId { S: ScalarValue { input.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", input)) + .ok_or_else(|| format!("Expected `String`, found: {input}")) .and_then(|str| { str.strip_prefix("id: ") .ok_or_else(|| { format!( "Expected `UserId` to begin with `id: `, \ - found: {}", - input, + found: {input}", ) }) }) @@ -190,7 +189,7 @@ where S: ScalarValue { match v { - StringOrInt::String(str) => Value::scalar(str.to_owned()), + StringOrInt::String(s) => Value::scalar(s.to_owned()), StringOrInt::Int(i) => Value::scalar(*i), } } @@ -200,9 +199,9 @@ where S: ScalarValue { v.as_string_value() - .map(|s| StringOrInt::String(s.to_owned())) + .map(|s| StringOrInt::String(s.into())) .or_else(|| v.as_int_value().map(|i| StringOrInt::Int(i))) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -240,7 +239,7 @@ enum StringOrInt { impl StringOrInt { fn to_output(&self) -> Value { match self { - Self::String(str) => Value::scalar(str.to_owned()), + Self::String(s) => Value::scalar(s.to_owned()), Self::Int(i) => Value::scalar(*i), } } @@ -250,9 +249,9 @@ impl StringOrInt { S: ScalarValue, { v.as_string_value() - .map(|s| Self::String(s.to_owned())) + .map(|s| Self::String(s.into())) .or_else(|| v.as_int_value().map(Self::Int)) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult @@ -290,7 +289,7 @@ mod string_or_int { S: ScalarValue, { match v { - StringOrInt::String(str) => Value::scalar(str.to_owned()), + StringOrInt::String(s) => Value::scalar(s.to_owned()), StringOrInt::Int(i) => Value::scalar(*i), } } @@ -300,9 +299,9 @@ mod string_or_int { S: ScalarValue, { v.as_string_value() - .map(|s| StringOrInt::String(s.to_owned())) + .map(|s| StringOrInt::String(s.into())) .or_else(|| v.as_int_value().map(StringOrInt::Int)) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult @@ -335,7 +334,7 @@ impl StringOrInt { S: ScalarValue, { match self { - Self::String(str) => Value::scalar(str.to_owned()), + Self::String(s) => Value::scalar(s.to_owned()), Self::Int(i) => Value::scalar(*i), } } @@ -345,9 +344,9 @@ impl StringOrInt { S: ScalarValue, { v.as_string_value() - .map(|s| Self::String(s.to_owned())) + .map(|s| Self::String(s.into())) .or_else(|| v.as_int_value().map(Self::Int)) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } } # @@ -400,8 +399,8 @@ mod date_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) - .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {}", e))) + .ok_or_else(|| format!("Expected `String`, found: {v}")) + .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}"))) } } # diff --git a/book/tests/Cargo.toml b/book/tests/Cargo.toml index f73d6fb9..395a3d14 100644 --- a/book/tests/Cargo.toml +++ b/book/tests/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "juniper_book_tests" version = "0.0.0" -edition = "2018" +edition = "2021" authors = ["Magnus Hallin "] publish = false diff --git a/examples/actix_subscriptions/Cargo.toml b/examples/actix_subscriptions/Cargo.toml index 9bab7b3b..9c200447 100644 --- a/examples/actix_subscriptions/Cargo.toml +++ b/examples/actix_subscriptions/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "example_actix_subscriptions" version = "0.0.0" -edition = "2018" +edition = "2021" +rust-version = "1.62" authors = ["Mihai Dinculescu "] publish = false diff --git a/examples/actix_subscriptions/src/main.rs b/examples/actix_subscriptions/src/main.rs index 66480242..6747105f 100644 --- a/examples/actix_subscriptions/src/main.rs +++ b/examples/actix_subscriptions/src/main.rs @@ -9,9 +9,9 @@ use actix_web::{ }; use juniper::{ - graphql_object, graphql_subscription, graphql_value, + graphql_subscription, graphql_value, tests::fixtures::starwars::schema::{Database, Query}, - EmptyMutation, FieldError, RootNode, + EmptyMutation, FieldError, GraphQLObject, RootNode, }; use juniper_actix::{graphql_handler, playground_handler, subscriptions::subscriptions_handler}; use juniper_graphql_ws::ConnectionConfig; @@ -37,23 +37,12 @@ async fn graphql( struct Subscription; +#[derive(GraphQLObject)] struct RandomHuman { id: String, name: String, } -// TODO: remove this when async interfaces are merged -#[graphql_object(context = Database)] -impl RandomHuman { - fn id(&self) -> &str { - &self.id - } - - fn name(&self) -> &str { - &self.name - } -} - type RandomHumanStream = Pin> + Send>>; @@ -84,8 +73,8 @@ impl Subscription { let human = context.get_human(&random_id).unwrap().clone(); yield Ok(RandomHuman { - id: human.id().to_owned(), - name: human.name().unwrap().to_owned(), + id: human.id().into(), + name: human.name().unwrap().into(), }) } } @@ -142,7 +131,7 @@ async fn main() -> std::io::Result<()> { .finish() })) }) - .bind(format!("{}:{}", "127.0.0.1", 8080))? + .bind("127.0.0.1:8080")? .run() .await } diff --git a/examples/basic_subscriptions/Cargo.toml b/examples/basic_subscriptions/Cargo.toml index f03bdef4..252bdbeb 100644 --- a/examples/basic_subscriptions/Cargo.toml +++ b/examples/basic_subscriptions/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "example_basic_subscriptions" version = "0.0.0" -edition = "2018" +edition = "2021" +rust-version = "1.62" authors = ["Jordao Rosario "] publish = false diff --git a/examples/basic_subscriptions/src/main.rs b/examples/basic_subscriptions/src/main.rs index 82d4b46f..df523674 100644 --- a/examples/basic_subscriptions/src/main.rs +++ b/examples/basic_subscriptions/src/main.rs @@ -16,7 +16,7 @@ impl juniper::Context for Database {} impl Database { fn new() -> Self { - Self {} + Self } } @@ -45,7 +45,7 @@ impl Subscription { type Schema = RootNode<'static, Query, EmptyMutation, Subscription>; fn schema() -> Schema { - Schema::new(Query {}, EmptyMutation::new(), Subscription {}) + Schema::new(Query, EmptyMutation::new(), Subscription) } #[tokio::main] diff --git a/examples/warp_async/Cargo.toml b/examples/warp_async/Cargo.toml index 94208317..0f891304 100644 --- a/examples/warp_async/Cargo.toml +++ b/examples/warp_async/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "example_warp_async" version = "0.0.0" -edition = "2018" +edition = "2021" +rust-version = "1.62" authors = ["Christoph Herzog "] publish = false diff --git a/examples/warp_subscriptions/Cargo.toml b/examples/warp_subscriptions/Cargo.toml index 6e22c5a7..da05cf99 100644 --- a/examples/warp_subscriptions/Cargo.toml +++ b/examples/warp_subscriptions/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "example_warp_subscriptions" version = "0.0.0" -edition = "2018" +edition = "2021" +rust-version = "1.62" publish = false [dependencies] diff --git a/examples/warp_subscriptions/src/main.rs b/examples/warp_subscriptions/src/main.rs index abac06a5..4e4d4584 100644 --- a/examples/warp_subscriptions/src/main.rs +++ b/examples/warp_subscriptions/src/main.rs @@ -12,7 +12,7 @@ use juniper_warp::{playground_filter, subscriptions::serve_graphql_ws}; use warp::{http::Response, Filter}; #[derive(Clone)] -struct Context {} +struct Context; impl juniper::Context for Context {} @@ -123,7 +123,7 @@ impl Subscription { yield Ok(User { id: counter, kind: UserKind::Admin, - name: "stream user".to_string(), + name: "stream user".into(), }) } } @@ -149,11 +149,11 @@ async fn main() { let homepage = warp::path::end().map(|| { Response::builder() .header("content-type", "text/html") - .body("

juniper_subscriptions demo

visit graphql playground".to_string()) + .body("

juniper_subscriptions demo

visit graphql playground") }); let qm_schema = schema(); - let qm_state = warp::any().map(move || Context {}); + let qm_state = warp::any().map(|| Context); let qm_graphql_filter = juniper_warp::make_graphql_filter(qm_schema, qm_state.boxed()); let root_node = Arc::new(schema()); @@ -165,10 +165,10 @@ async fn main() { .map(move |ws: warp::ws::Ws| { let root_node = root_node.clone(); ws.on_upgrade(move |websocket| async move { - serve_graphql_ws(websocket, root_node, ConnectionConfig::new(Context {})) + serve_graphql_ws(websocket, root_node, ConnectionConfig::new(Context)) .map(|r| { if let Err(e) = r { - println!("Websocket error: {}", e); + println!("Websocket error: {e}"); } }) .await diff --git a/juniper/Cargo.toml b/juniper/Cargo.toml index bbf55964..6a1121aa 100644 --- a/juniper/Cargo.toml +++ b/juniper/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper" version = "0.16.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "GraphQL server library." license = "BSD-2-Clause" authors = [ diff --git a/juniper/src/ast.rs b/juniper/src/ast.rs index 2336138b..0358dd83 100644 --- a/juniper/src/ast.rs +++ b/juniper/src/ast.rs @@ -224,10 +224,10 @@ impl<'a> Type<'a> { impl<'a> fmt::Display for Type<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Named(n) => write!(f, "{}", n), - Self::NonNullNamed(n) => write!(f, "{}!", n), - Self::List(t, _) => write!(f, "[{}]", t), - Self::NonNullList(t, _) => write!(f, "[{}]!", t), + Self::Named(n) => write!(f, "{n}"), + Self::NonNullNamed(n) => write!(f, "{n}!"), + Self::List(t, _) => write!(f, "[{t}]"), + Self::NonNullList(t, _) => write!(f, "[{t}]!"), } } } @@ -248,12 +248,12 @@ impl InputValue { /// Construct an enum value. pub fn enum_value>(s: T) -> Self { - Self::Enum(s.as_ref().to_owned()) + Self::Enum(s.as_ref().into()) } /// Construct a variable value. pub fn variable>(v: T) -> Self { - Self::Variable(v.as_ref().to_owned()) + Self::Variable(v.as_ref().into()) } /// Construct a [`Spanning::unlocated`] list. @@ -282,7 +282,7 @@ impl InputValue { o.into_iter() .map(|(k, v)| { ( - Spanning::unlocated(k.as_ref().to_owned()), + Spanning::unlocated(k.as_ref().into()), Spanning::unlocated(v), ) }) @@ -467,13 +467,13 @@ impl fmt::Display for InputValue { Self::Null => write!(f, "null"), Self::Scalar(s) => { if let Some(s) = s.as_str() { - write!(f, "\"{}\"", s) + write!(f, "\"{s}\"") } else { - write!(f, "{}", s) + write!(f, "{s}") } } - Self::Enum(v) => write!(f, "{}", v), - Self::Variable(v) => write!(f, "${}", v), + Self::Enum(v) => write!(f, "{v}"), + Self::Variable(v) => write!(f, "${v}"), Self::List(v) => { write!(f, "[")?; for (i, spanning) in v.iter().enumerate() { @@ -588,30 +588,30 @@ mod tests { #[test] fn test_input_value_fmt() { let value: InputValue = graphql_input_value!(null); - assert_eq!(format!("{}", value), "null"); + assert_eq!(value.to_string(), "null"); let value: InputValue = graphql_input_value!(123); - assert_eq!(format!("{}", value), "123"); + assert_eq!(value.to_string(), "123"); let value: InputValue = graphql_input_value!(12.3); - assert_eq!(format!("{}", value), "12.3"); + assert_eq!(value.to_string(), "12.3"); let value: InputValue = graphql_input_value!("FOO"); - assert_eq!(format!("{}", value), "\"FOO\""); + assert_eq!(value.to_string(), "\"FOO\""); let value: InputValue = graphql_input_value!(true); - assert_eq!(format!("{}", value), "true"); + assert_eq!(value.to_string(), "true"); let value: InputValue = graphql_input_value!(BAR); - assert_eq!(format!("{}", value), "BAR"); + assert_eq!(value.to_string(), "BAR"); let value: InputValue = graphql_input_value!(@baz); - assert_eq!(format!("{}", value), "$baz"); + assert_eq!(value.to_string(), "$baz"); let value: InputValue = graphql_input_value!([1, 2]); - assert_eq!(format!("{}", value), "[1, 2]"); + assert_eq!(value.to_string(), "[1, 2]"); let value: InputValue = graphql_input_value!({"foo": 1,"bar": 2}); - assert_eq!(format!("{}", value), "{foo: 1, bar: 2}"); + assert_eq!(value.to_string(), "{foo: 1, bar: 2}"); } } diff --git a/juniper/src/executor/look_ahead.rs b/juniper/src/executor/look_ahead.rs index 41bae7ee..b12231d6 100644 --- a/juniper/src/executor/look_ahead.rs +++ b/juniper/src/executor/look_ahead.rs @@ -112,12 +112,11 @@ pub struct LookAheadSelection<'a, S: 'a> { pub(super) children: Vec>, } -impl<'a, S> Default for LookAheadSelection<'a, S> -where - S: ScalarValue, -{ +// Implemented manually to omit redundant `S: Default` trait bound, imposed by +// `#[derive(Default)]`. +impl<'a, S: 'a> Default for LookAheadSelection<'a, S> { fn default() -> Self { - LookAheadSelection { + Self { name: "", alias: None, arguments: vec![], diff --git a/juniper/src/executor/mod.rs b/juniper/src/executor/mod.rs index 887091c7..9ab412d4 100644 --- a/juniper/src/executor/mod.rs +++ b/juniper/src/executor/mod.rs @@ -304,7 +304,7 @@ where type Type; #[doc(hidden)] - fn into(self, ctx: &'a C) -> FieldResult, S>; + fn into_resolvable(self, ctx: &'a C) -> FieldResult, S>; } impl<'a, S, T, C> IntoResolvable<'a, S, T, C> for T @@ -315,7 +315,7 @@ where { type Type = T; - fn into(self, ctx: &'a C) -> FieldResult, S> { + fn into_resolvable(self, ctx: &'a C) -> FieldResult, S> { Ok(Some((FromContext::from(ctx), self))) } } @@ -328,7 +328,7 @@ where { type Type = T; - fn into(self, ctx: &'a C) -> FieldResult, S> { + fn into_resolvable(self, ctx: &'a C) -> FieldResult, S> { self.map(|v: T| Some((>::from(ctx), v))) .map_err(IntoFieldError::into_field_error) } @@ -341,7 +341,7 @@ where { type Type = T; - fn into(self, _: &'a C) -> FieldResult, S> { + fn into_resolvable(self, _: &'a C) -> FieldResult, S> { Ok(Some(self)) } } @@ -354,7 +354,7 @@ where type Type = T; #[allow(clippy::type_complexity)] - fn into(self, _: &'a C) -> FieldResult)>, S> { + fn into_resolvable(self, _: &'a C) -> FieldResult)>, S> { Ok(self.map(|(ctx, v)| (ctx, Some(v)))) } } @@ -367,7 +367,7 @@ where { type Type = T; - fn into(self, _: &'a C) -> FieldResult, S2> { + fn into_resolvable(self, _: &'a C) -> FieldResult, S2> { self.map(Some).map_err(FieldError::map_scalar_value) } } @@ -382,7 +382,7 @@ where type Type = T; #[allow(clippy::type_complexity)] - fn into(self, _: &'a C) -> FieldResult)>, S2> { + fn into_resolvable(self, _: &'a C) -> FieldResult)>, S2> { self.map(|o| o.map(|(ctx, v)| (ctx, Some(v)))) .map_err(FieldError::map_scalar_value) } @@ -774,7 +774,7 @@ impl<'a> FieldPath<'a> { FieldPath::Root(_) => (), FieldPath::Field(name, _, parent) => { parent.construct_path(acc); - acc.push((*name).to_owned()); + acc.push((*name).into()); } } } @@ -791,7 +791,7 @@ impl ExecutionError { pub fn new(location: SourcePosition, path: &[&str], error: FieldError) -> ExecutionError { ExecutionError { location, - path: path.iter().map(|s| (*s).to_owned()).collect(), + path: path.iter().map(|s| (*s).into()).collect(), error, } } @@ -842,10 +842,10 @@ where defs.item .items .iter() - .filter_map(|&(ref name, ref def)| { + .filter_map(|(name, def)| { def.default_value .as_ref() - .map(|i| (name.item.to_owned(), i.item.clone())) + .map(|i| (name.item.into(), i.item.clone())) }) .collect::>>() }); @@ -943,7 +943,7 @@ where .filter_map(|&(ref name, ref def)| { def.default_value .as_ref() - .map(|i| (name.item.to_owned(), i.item.clone())) + .map(|i| (name.item.into(), i.item.clone())) }) .collect::>>() }); @@ -1090,7 +1090,7 @@ where .filter_map(|&(ref name, ref def)| { def.default_value .as_ref() - .map(|i| (name.item.to_owned(), i.item.clone())) + .map(|i| (name.item.into(), i.item.clone())) }) .collect::>>() }); @@ -1172,7 +1172,7 @@ impl<'r, S: 'r> Registry<'r, S> { if !self.types.contains_key(name) { self.insert_placeholder( validated_name.clone(), - Type::NonNullNamed(Cow::Owned(name.to_string())), + Type::NonNullNamed(Cow::Owned(name.into())), ); let meta = T::meta(info, self); self.types.insert(validated_name, meta); @@ -1209,7 +1209,7 @@ impl<'r, S: 'r> Registry<'r, S> { S: ScalarValue, { Field { - name: smartstring::SmartString::from(name), + name: name.into(), description: None, arguments: None, field_type: self.get_type::(info), @@ -1255,7 +1255,7 @@ impl<'r, S: 'r> Registry<'r, S> { { let name = T::name(info).expect("Scalar types must be named. Implement `name()`"); - ScalarMeta::new::(Cow::Owned(name.to_string())) + ScalarMeta::new::(Cow::Owned(name.into())) } /// Creates a [`ListMeta`] type. @@ -1299,7 +1299,7 @@ impl<'r, S: 'r> Registry<'r, S> { let mut v = fields.to_vec(); v.push(self.field::("__typename", &())); - ObjectMeta::new(Cow::Owned(name.to_string()), &v) + ObjectMeta::new(Cow::Owned(name.into()), &v) } /// Creates an [`EnumMeta`] type out of the provided `values`. @@ -1315,7 +1315,7 @@ impl<'r, S: 'r> Registry<'r, S> { { let name = T::name(info).expect("Enum types must be named. Implement `name()`"); - EnumMeta::new::(Cow::Owned(name.to_string()), values) + EnumMeta::new::(Cow::Owned(name.into()), values) } /// Creates an [`InterfaceMeta`] type with the given `fields`. @@ -1332,7 +1332,7 @@ impl<'r, S: 'r> Registry<'r, S> { let mut v = fields.to_vec(); v.push(self.field::("__typename", &())); - InterfaceMeta::new(Cow::Owned(name.to_string()), &v) + InterfaceMeta::new(Cow::Owned(name.into()), &v) } /// Creates an [`UnionMeta`] type of the given `types`. @@ -1343,7 +1343,7 @@ impl<'r, S: 'r> Registry<'r, S> { { let name = T::name(info).expect("Union types must be named. Implement name()"); - UnionMeta::new(Cow::Owned(name.to_string()), types) + UnionMeta::new(Cow::Owned(name.into()), types) } /// Creates an [`InputObjectMeta`] type with the given `args`. @@ -1359,6 +1359,6 @@ impl<'r, S: 'r> Registry<'r, S> { { let name = T::name(info).expect("Input object types must be named. Implement name()"); - InputObjectMeta::new::(Cow::Owned(name.to_string()), args) + InputObjectMeta::new::(Cow::Owned(name.into()), args) } } diff --git a/juniper/src/executor_tests/async_await/mod.rs b/juniper/src/executor_tests/async_await/mod.rs index 277c0197..228c53d3 100644 --- a/juniper/src/executor_tests/async_await/mod.rs +++ b/juniper/src/executor_tests/async_await/mod.rs @@ -1,5 +1,6 @@ use crate::{ - graphql_object, graphql_value, EmptyMutation, EmptySubscription, GraphQLEnum, RootNode, Value, + graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLEnum, + RootNode, Value, }; #[derive(GraphQLEnum)] @@ -30,7 +31,7 @@ impl User { (0..10) .map(|index| User { id: index, - name: format!("user{}", index), + name: format!("user{index}"), kind: UserKind::User, }) .collect() @@ -55,7 +56,7 @@ impl Query { } async fn field_async_plain() -> String { - "field_async_plain".to_string() + "field_async_plain".into() } fn user(id: String) -> User { @@ -86,8 +87,7 @@ async fn async_simple() { } "#; - let vars = Default::default(); - let (res, errs) = crate::execute(doc, None, &schema, &vars, &()) + let (res, errs) = crate::execute(doc, None, &schema, &graphql_vars! {}, &()) .await .unwrap(); diff --git a/juniper/src/executor_tests/directives.rs b/juniper/src/executor_tests/directives.rs index adc05594..1f902e69 100644 --- a/juniper/src/executor_tests/directives.rs +++ b/juniper/src/executor_tests/directives.rs @@ -35,7 +35,7 @@ where assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let obj = result.as_object_value().expect("Result is not an object"); diff --git a/juniper/src/executor_tests/enums.rs b/juniper/src/executor_tests/enums.rs index 69cda71d..11fa80ae 100644 --- a/juniper/src/executor_tests/enums.rs +++ b/juniper/src/executor_tests/enums.rs @@ -22,7 +22,7 @@ struct TestType; #[crate::graphql_object] impl TestType { fn to_string(color: Color) -> String { - format!("Color::{:?}", color) + format!("Color::{color:?}") } fn a_color() -> Color { @@ -46,7 +46,7 @@ where assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let obj = result.as_object_value().expect("Result is not an object"); diff --git a/juniper/src/executor_tests/executor.rs b/juniper/src/executor_tests/executor.rs index a1da0673..06d93fc0 100644 --- a/juniper/src/executor_tests/executor.rs +++ b/juniper/src/executor_tests/executor.rs @@ -96,7 +96,7 @@ mod field_execution { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -180,7 +180,7 @@ mod merge_parallel_fragments { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -288,7 +288,7 @@ mod merge_parallel_inline_fragments { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -355,7 +355,7 @@ mod threads_context_correctly { &schema, &vars, &TestContext { - value: "Context value".to_owned(), + value: "Context value".into(), }, ) .await @@ -363,7 +363,7 @@ mod threads_context_correctly { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!({"a": "Context value"})); } @@ -410,7 +410,7 @@ mod dynamic_context_switching { let res = context .items .get(&key) - .ok_or(format!("Could not find key {}", key)) + .ok_or(format!("Could not find key {key}")) .map(|c| (c, ItemRef))?; Ok(res) } @@ -420,7 +420,7 @@ mod dynamic_context_switching { key: i32, ) -> FieldResult> { if key > 100 { - Err(format!("Key too large: {}", key))?; + Err(format!("Key too large: {key}"))?; } Ok(context.items.get(&key).map(|c| (c, ItemRef))) } @@ -452,13 +452,13 @@ mod dynamic_context_switching { ( 0, InnerContext { - value: "First value".to_owned(), + value: "First value".into(), }, ), ( 1, InnerContext { - value: "Second value".to_owned(), + value: "Second value".into(), }, ), ] @@ -472,7 +472,7 @@ mod dynamic_context_switching { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -500,13 +500,13 @@ mod dynamic_context_switching { ( 0, InnerContext { - value: "First value".to_owned(), + value: "First value".into(), }, ), ( 1, InnerContext { - value: "Second value".to_owned(), + value: "Second value".into(), }, ), ] @@ -520,7 +520,7 @@ mod dynamic_context_switching { assert_eq!(errs, vec![]); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!({"first": {"value": "First value"}})); } @@ -542,13 +542,13 @@ mod dynamic_context_switching { ( 0, InnerContext { - value: "First value".to_owned(), + value: "First value".into(), }, ), ( 1, InnerContext { - value: "Second value".to_owned(), + value: "Second value".into(), }, ), ] @@ -569,7 +569,7 @@ mod dynamic_context_switching { )], ); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!(null)); } @@ -593,13 +593,13 @@ mod dynamic_context_switching { ( 0, InnerContext { - value: "First value".to_owned(), + value: "First value".into(), }, ), ( 1, InnerContext { - value: "Second value".to_owned(), + value: "Second value".into(), }, ), ] @@ -620,7 +620,7 @@ mod dynamic_context_switching { )], ); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -647,13 +647,13 @@ mod dynamic_context_switching { ( 0, InnerContext { - value: "First value".to_owned(), + value: "First value".into(), }, ), ( 1, InnerContext { - value: "Second value".to_owned(), + value: "Second value".into(), }, ), ] @@ -667,7 +667,7 @@ mod dynamic_context_switching { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!({"first": {"value": "First value"}})); } @@ -752,7 +752,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -783,7 +783,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!(null)); @@ -811,7 +811,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!(null)); @@ -839,7 +839,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!({"inner": {"nullableField": null}}),); @@ -867,7 +867,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!(null)); @@ -895,7 +895,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -926,7 +926,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!(result, graphql_value!(null)); @@ -954,7 +954,7 @@ mod propagates_errors_to_nullable_fields { .await .expect("Execution failed"); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, diff --git a/juniper/src/executor_tests/interfaces_unions.rs b/juniper/src/executor_tests/interfaces_unions.rs index 1044baaf..10d5e088 100644 --- a/juniper/src/executor_tests/interfaces_unions.rs +++ b/juniper/src/executor_tests/interfaces_unions.rs @@ -42,12 +42,12 @@ mod interface { Schema { pets: vec![ Dog { - name: "Odie".to_owned(), + name: "Odie".into(), woofs: true, } .into(), Cat { - name: "Garfield".to_owned(), + name: "Garfield".into(), meows: false, } .into(), @@ -77,7 +77,7 @@ mod interface { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -170,11 +170,11 @@ mod union { Schema { pets: vec![ Box::new(Dog { - name: "Odie".to_owned(), + name: "Odie".into(), woofs: true, }), Box::new(Cat { - name: "Garfield".to_owned(), + name: "Garfield".into(), meows: false, }), ], @@ -205,7 +205,7 @@ mod union { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, diff --git a/juniper/src/executor_tests/introspection/enums.rs b/juniper/src/executor_tests/introspection/enums.rs index 127f45ab..c70a60e9 100644 --- a/juniper/src/executor_tests/introspection/enums.rs +++ b/juniper/src/executor_tests/introspection/enums.rs @@ -92,7 +92,7 @@ where F: Fn((&Object, &Vec>)) -> (), { let schema = RootNode::new( - Root {}, + Root, EmptyMutation::<()>::new(), EmptySubscription::<()>::new(), ); @@ -103,7 +103,7 @@ where assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() diff --git a/juniper/src/executor_tests/introspection/input_object.rs b/juniper/src/executor_tests/introspection/input_object.rs index cf8c0d20..2e70d088 100644 --- a/juniper/src/executor_tests/introspection/input_object.rs +++ b/juniper/src/executor_tests/introspection/input_object.rs @@ -117,7 +117,7 @@ where F: Fn(&Object, &Vec>) -> (), { let schema = RootNode::new( - Root {}, + Root, EmptyMutation::<()>::new(), EmptySubscription::<()>::new(), ); @@ -128,7 +128,7 @@ where assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() @@ -312,7 +312,7 @@ fn derive_derived() { format!( "{:?}", Derive { - field_one: "test".to_owned(), + field_one: "test".into(), }, ), "Derive { field_one: \"test\" }" diff --git a/juniper/src/executor_tests/introspection/mod.rs b/juniper/src/executor_tests/introspection/mod.rs index e78995ec..ee2501b2 100644 --- a/juniper/src/executor_tests/introspection/mod.rs +++ b/juniper/src/executor_tests/introspection/mod.rs @@ -69,7 +69,7 @@ async fn test_execution() { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); assert_eq!( result, @@ -114,7 +114,7 @@ async fn enum_introspection() { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() @@ -223,7 +223,7 @@ async fn interface_introspection() { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() @@ -355,7 +355,7 @@ async fn object_introspection() { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() @@ -406,7 +406,7 @@ async fn object_introspection() { assert_eq!(fields.len(), 2); - println!("Fields: {:#?}", fields); + println!("Fields: {fields:#?}"); assert!(fields.contains(&graphql_value!({ "name": "sampleEnum", @@ -497,7 +497,7 @@ async fn scalar_introspection() { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); let type_info = result .as_object_value() diff --git a/juniper/src/executor_tests/variables.rs b/juniper/src/executor_tests/variables.rs index 0073d0e2..f49d4a23 100644 --- a/juniper/src/executor_tests/variables.rs +++ b/juniper/src/executor_tests/variables.rs @@ -23,7 +23,7 @@ impl TestComplexScalar { v.as_string_value() .filter(|s| *s == "SerializedValue") .map(|_| Self) - .ok_or_else(|| format!(r#"Expected "SerializedValue" string, found: {}"#, v)) + .ok_or_else(|| format!(r#"Expected "SerializedValue" string, found: {v}"#)) } } @@ -58,47 +58,47 @@ struct TestType; #[graphql_object] impl TestType { fn field_with_object_input(input: Option) -> String { - format!("{:?}", input) + format!("{input:?}") } fn field_with_nullable_string_input(input: Option) -> String { - format!("{:?}", input) + format!("{input:?}") } fn field_with_non_nullable_string_input(input: String) -> String { - format!("{:?}", input) + format!("{input:?}") } fn field_with_default_argument_value( #[graphql(default = "Hello World")] input: String, ) -> String { - format!("{:?}", input) + format!("{input:?}") } fn nullable_field_with_default_argument_value( #[graphql(default = "Hello World".to_owned())] input: Option, ) -> String { - format!("{:?}", input) + format!("{input:?}") } fn field_with_nested_object_input(input: Option) -> String { - format!("{:?}", input) + format!("{input:?}") } fn list(input: Option>>) -> String { - format!("{:?}", input) + format!("{input:?}") } fn nn_list(input: Vec>) -> String { - format!("{:?}", input) + format!("{input:?}") } fn list_nn(input: Option>) -> String { - format!("{:?}", input) + format!("{input:?}") } fn nn_list_nn(input: Vec) -> String { - format!("{:?}", input) + format!("{input:?}") } fn example_input(arg: ExampleInputObject) -> String { @@ -110,11 +110,11 @@ impl TestType { } fn integer_input(value: i32) -> String { - format!("value: {}", value) + format!("value: {value}") } fn float_input(value: f64) -> String { - format!("value: {}", value) + format!("value: {value}") } } @@ -134,7 +134,7 @@ where assert_eq!(errs, []); - println!("Result: {:?}", result); + println!("Result: {result:?}"); let obj = result.as_object_value().expect("Result is not an object"); diff --git a/juniper/src/http/mod.rs b/juniper/src/http/mod.rs index fe3f2d65..45e310be 100644 --- a/juniper/src/http/mod.rs +++ b/juniper/src/http/mod.rs @@ -60,11 +60,8 @@ where self.variables .as_ref() .and_then(|iv| { - iv.to_object_value().map(|o| { - o.into_iter() - .map(|(k, v)| (k.to_owned(), v.clone())) - .collect() - }) + iv.to_object_value() + .map(|o| o.into_iter().map(|(k, v)| (k.into(), v.clone())).collect()) }) .unwrap_or_default() } @@ -635,20 +632,20 @@ pub mod tests { "type":"connection_init", "payload":{} }"# - .to_owned(), + .into(), ), WsIntegrationMessage::Expect( r#"{ "type":"connection_ack" }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, ), WsIntegrationMessage::Expect( r#"{ "type":"ka" }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, ), WsIntegrationMessage::Send( @@ -662,7 +659,7 @@ pub mod tests { "query":"subscription { asyncHuman { id, name, homePlanet } }" } }"# - .to_owned(), + .into(), ), WsIntegrationMessage::Expect( r#"{ @@ -678,7 +675,7 @@ pub mod tests { } } }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, ), ]; @@ -688,7 +685,7 @@ pub mod tests { async fn test_ws_invalid_json(integration: &T) { let messages = vec![ - WsIntegrationMessage::Send("invalid json".to_owned()), + WsIntegrationMessage::Send("invalid json".into()), WsIntegrationMessage::Expect( r#"{ "type":"connection_error", @@ -696,7 +693,7 @@ pub mod tests { "message":"serde error: expected value at line 1 column 1" } }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT, ), ]; @@ -711,20 +708,20 @@ pub mod tests { "type":"connection_init", "payload":{} }"# - .to_owned(), + .into(), ), WsIntegrationMessage::Expect( r#"{ "type":"connection_ack" }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT ), WsIntegrationMessage::Expect( r#"{ "type":"ka" }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT ), WsIntegrationMessage::Send( @@ -738,7 +735,7 @@ pub mod tests { "query":"subscription { asyncHuman }" } }"# - .to_owned(), + .into(), ), WsIntegrationMessage::Expect( r#"{ @@ -752,7 +749,7 @@ pub mod tests { }] }] }"# - .to_owned(), + .into(), WS_INTEGRATION_EXPECT_DEFAULT_TIMEOUT ) ]; diff --git a/juniper/src/integrations/bigdecimal.rs b/juniper/src/integrations/bigdecimal.rs index a1635fcc..3715536c 100644 --- a/juniper/src/integrations/bigdecimal.rs +++ b/juniper/src/integrations/bigdecimal.rs @@ -32,8 +32,6 @@ use crate::{graphql_scalar, InputValue, ScalarValue, Value}; type BigDecimal = bigdecimal::BigDecimal; mod bigdecimal_scalar { - use std::convert::TryFrom as _; - use super::*; pub(super) fn to_output(v: &BigDecimal) -> Value { @@ -45,13 +43,13 @@ mod bigdecimal_scalar { Ok(BigDecimal::from(i)) } else if let Some(f) = v.as_float_value() { BigDecimal::try_from(f) - .map_err(|e| format!("Failed to parse `BigDecimal` from `Float`: {}", e)) + .map_err(|e| format!("Failed to parse `BigDecimal` from `Float`: {e}")) } else { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { BigDecimal::from_str(s) - .map_err(|e| format!("Failed to parse `BigDecimal` from `String`: {}", e)) + .map_err(|e| format!("Failed to parse `BigDecimal` from `String`: {e}")) }) } } @@ -88,11 +86,10 @@ mod test { assert!( parsed.is_ok(), - "failed to parse `{:?}`: {:?}", - input, + "failed to parse `{input:?}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {:?}", input); + assert_eq!(parsed.unwrap(), expected, "input: {input:?}"); } } @@ -110,7 +107,7 @@ mod test { let input: InputValue = input; let parsed = BigDecimal::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -126,7 +123,7 @@ mod test { ] { let actual: InputValue = BigDecimal::from_str(raw).unwrap().to_input_value(); - assert_eq!(actual, graphql_input_value!((raw)), "on value: {}", raw); + assert_eq!(actual, graphql_input_value!((raw)), "on value: {raw}"); } } } diff --git a/juniper/src/integrations/bson.rs b/juniper/src/integrations/bson.rs index 8d904025..20c88fbe 100644 --- a/juniper/src/integrations/bson.rs +++ b/juniper/src/integrations/bson.rs @@ -14,9 +14,9 @@ mod object_id { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { - ObjectId::parse_str(s).map_err(|e| format!("Failed to parse `ObjectId`: {}", e)) + ObjectId::parse_str(s).map_err(|e| format!("Failed to parse `ObjectId`: {e}")) }) } } @@ -30,16 +30,16 @@ mod utc_date_time { pub(super) fn to_output(v: &UtcDateTime) -> Value { Value::scalar( (*v).try_to_rfc3339_string() - .unwrap_or_else(|e| panic!("failed to format `UtcDateTime` as RFC3339: {}", e)), + .unwrap_or_else(|e| panic!("failed to format `UtcDateTime` as RFC3339: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { UtcDateTime::parse_rfc3339_str(s) - .map_err(|e| format!("Failed to parse `UtcDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `UtcDateTime`: {e}")) }) } } diff --git a/juniper/src/integrations/chrono.rs b/juniper/src/integrations/chrono.rs index a0c6edc4..b1fb3a48 100644 --- a/juniper/src/integrations/chrono.rs +++ b/juniper/src/integrations/chrono.rs @@ -62,9 +62,9 @@ mod date { S: ScalarValue, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { - Date::parse_from_str(s, FORMAT).map_err(|e| format!("Invalid `Date`: {}", e)) + Date::parse_from_str(s, FORMAT).map_err(|e| format!("Invalid `Date`: {e}")) }) } } @@ -127,7 +127,7 @@ mod local_time { S: ScalarValue, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { // First, try to parse the most used format. // At the end, try to parse the full format for the parsing @@ -135,7 +135,7 @@ mod local_time { LocalTime::parse_from_str(s, FORMAT_NO_MILLIS) .or_else(|_| LocalTime::parse_from_str(s, FORMAT_NO_SECS)) .or_else(|_| LocalTime::parse_from_str(s, FORMAT)) - .map_err(|e| format!("Invalid `LocalTime`: {}", e)) + .map_err(|e| format!("Invalid `LocalTime`: {e}")) }) } } @@ -166,10 +166,10 @@ mod local_date_time { S: ScalarValue, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { LocalDateTime::parse_from_str(s, FORMAT) - .map_err(|e| format!("Invalid `LocalDateTime`: {}", e)) + .map_err(|e| format!("Invalid `LocalDateTime`: {e}")) }) } } @@ -219,10 +219,10 @@ mod date_time { Tz: TimeZone + FromFixedOffset, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::::parse_from_rfc3339(s) - .map_err(|e| format!("Invalid `DateTime`: {}", e)) + .map_err(|e| format!("Invalid `DateTime`: {e}")) .map(FromFixedOffset::from_fixed_offset) }) } @@ -345,11 +345,10 @@ mod date_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -372,7 +371,7 @@ mod date_test { let input: InputValue = input; let parsed = Date::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -394,7 +393,7 @@ mod date_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -420,11 +419,10 @@ mod local_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -451,7 +449,7 @@ mod local_time_test { let input: InputValue = input; let parsed = LocalTime::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -477,7 +475,7 @@ mod local_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -513,11 +511,10 @@ mod local_date_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -546,7 +543,7 @@ mod local_date_time_test { let input: InputValue = input; let parsed = LocalDateTime::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -570,7 +567,7 @@ mod local_date_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -635,11 +632,10 @@ mod date_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -673,7 +669,7 @@ mod date_time_test { let input: InputValue = input; let parsed = DateTime::::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -703,7 +699,7 @@ mod date_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } diff --git a/juniper/src/integrations/chrono_tz.rs b/juniper/src/integrations/chrono_tz.rs index b6fa5732..8950f97f 100644 --- a/juniper/src/integrations/chrono_tz.rs +++ b/juniper/src/integrations/chrono_tz.rs @@ -34,10 +34,10 @@ mod tz { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { s.parse::() - .map_err(|e| format!("Failed to parse `TimeZone`: {}", e)) + .map_err(|e| format!("Failed to parse `TimeZone`: {e}")) }) } } diff --git a/juniper/src/integrations/rust_decimal.rs b/juniper/src/integrations/rust_decimal.rs index 2e74db32..52a6d20c 100644 --- a/juniper/src/integrations/rust_decimal.rs +++ b/juniper/src/integrations/rust_decimal.rs @@ -34,8 +34,6 @@ use crate::{graphql_scalar, InputValue, ScalarValue, Value}; type Decimal = rust_decimal::Decimal; mod rust_decimal_scalar { - use std::convert::TryFrom as _; - use super::*; pub(super) fn to_output(v: &Decimal) -> Value { @@ -46,14 +44,13 @@ mod rust_decimal_scalar { if let Some(i) = v.as_int_value() { Ok(Decimal::from(i)) } else if let Some(f) = v.as_float_value() { - Decimal::try_from(f) - .map_err(|e| format!("Failed to parse `Decimal` from `Float`: {}", e)) + Decimal::try_from(f).map_err(|e| format!("Failed to parse `Decimal` from `Float`: {e}")) } else { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { Decimal::from_str(s) - .map_err(|e| format!("Failed to parse `Decimal` from `String`: {}", e)) + .map_err(|e| format!("Failed to parse `Decimal` from `String`: {e}")) }) } } @@ -84,11 +81,10 @@ mod test { assert!( parsed.is_ok(), - "failed to parse `{:?}`: {:?}", - input, + "failed to parse `{input:?}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {:?}", input); + assert_eq!(parsed.unwrap(), expected, "input: {input:?}"); } } @@ -108,7 +104,7 @@ mod test { let input: InputValue = input; let parsed = Decimal::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -117,7 +113,7 @@ mod test { for raw in ["4.20", "0", "999.999999999", "875533788", "123", "43.44"] { let actual: InputValue = Decimal::from_str(raw).unwrap().to_input_value(); - assert_eq!(actual, graphql_input_value!((raw)), "on value: {}", raw); + assert_eq!(actual, graphql_input_value!((raw)), "on value: {raw}"); } } } diff --git a/juniper/src/integrations/serde.rs b/juniper/src/integrations/serde.rs index 64b5018f..38779964 100644 --- a/juniper/src/integrations/serde.rs +++ b/juniper/src/integrations/serde.rs @@ -1,8 +1,4 @@ -use std::{ - convert::{TryFrom as _, TryInto as _}, - fmt, - marker::PhantomData, -}; +use std::{fmt, marker::PhantomData}; use indexmap::IndexMap; use serde::{ @@ -251,7 +247,7 @@ impl Serialize for Spanning { fn serialize(&self, ser: S) -> Result { let mut map = ser.serialize_map(Some(2))?; - let msg = format!("{}", self.item); + let msg = self.item.to_string(); map.serialize_key("message")?; map.serialize_value(&msg)?; @@ -396,7 +392,7 @@ mod tests { #[test] fn error_extensions() { let mut obj: Object = Object::with_capacity(1); - obj.add_field("foo".to_string(), Value::scalar("bar")); + obj.add_field("foo", Value::scalar("bar")); assert_eq!( to_string(&ExecutionError::at_origin(FieldError::new( "foo error", diff --git a/juniper/src/integrations/time.rs b/juniper/src/integrations/time.rs index e05bf535..d2c88529 100644 --- a/juniper/src/integrations/time.rs +++ b/juniper/src/integrations/time.rs @@ -57,14 +57,14 @@ mod date { pub(super) fn to_output(v: &Date) -> Value { Value::scalar( v.format(FORMAT) - .unwrap_or_else(|e| panic!("Failed to format `Date`: {}", e)), + .unwrap_or_else(|e| panic!("Failed to format `Date`: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) - .and_then(|s| Date::parse(s, FORMAT).map_err(|e| format!("Invalid `Date`: {}", e))) + .ok_or_else(|| format!("Expected `String`, found: {v}")) + .and_then(|s| Date::parse(s, FORMAT).map_err(|e| format!("Invalid `Date`: {e}"))) } } @@ -109,13 +109,13 @@ mod local_time { } else { v.format(FORMAT) } - .unwrap_or_else(|e| panic!("Failed to format `LocalTime`: {}", e)), + .unwrap_or_else(|e| panic!("Failed to format `LocalTime`: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { // First, try to parse the most used format. // At the end, try to parse the full format for the parsing @@ -123,7 +123,7 @@ mod local_time { LocalTime::parse(s, FORMAT_NO_MILLIS) .or_else(|_| LocalTime::parse(s, FORMAT_NO_SECS)) .or_else(|_| LocalTime::parse(s, FORMAT)) - .map_err(|e| format!("Invalid `LocalTime`: {}", e)) + .map_err(|e| format!("Invalid `LocalTime`: {e}")) }) } } @@ -146,16 +146,15 @@ mod local_date_time { pub(super) fn to_output(v: &LocalDateTime) -> Value { Value::scalar( v.format(FORMAT) - .unwrap_or_else(|e| panic!("Failed to format `LocalDateTime`: {}", e)), + .unwrap_or_else(|e| panic!("Failed to format `LocalDateTime`: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { - LocalDateTime::parse(s, FORMAT) - .map_err(|e| format!("Invalid `LocalDateTime`: {}", e)) + LocalDateTime::parse(s, FORMAT).map_err(|e| format!("Invalid `LocalDateTime`: {e}")) }) } } @@ -186,15 +185,15 @@ mod date_time { Value::scalar( v.to_offset(UtcOffset::UTC) .format(&Rfc3339) - .unwrap_or_else(|e| panic!("Failed to format `DateTime`: {}", e)), + .unwrap_or_else(|e| panic!("Failed to format `DateTime`: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { - DateTime::parse(s, &Rfc3339).map_err(|e| format!("Invalid `DateTime`: {}", e)) + DateTime::parse(s, &Rfc3339).map_err(|e| format!("Invalid `DateTime`: {e}")) }) .map(|dt| dt.to_offset(UtcOffset::UTC)) } @@ -228,16 +227,16 @@ mod utc_offset { pub(super) fn to_output(v: &UtcOffset) -> Value { Value::scalar( v.format(UTC_OFFSET_FORMAT) - .unwrap_or_else(|e| panic!("Failed to format `UtcOffset`: {}", e)), + .unwrap_or_else(|e| panic!("Failed to format `UtcOffset`: {e}")), ) } pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { UtcOffset::parse(s, UTC_OFFSET_FORMAT) - .map_err(|e| format!("Invalid `UtcOffset`: {}", e)) + .map_err(|e| format!("Invalid `UtcOffset`: {e}")) }) } } @@ -261,11 +260,10 @@ mod date_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -288,7 +286,7 @@ mod date_test { let input: InputValue = input; let parsed = Date::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -302,7 +300,7 @@ mod date_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -330,11 +328,10 @@ mod local_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -364,7 +361,7 @@ mod local_time_test { let input: InputValue = input; let parsed = LocalTime::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -378,7 +375,7 @@ mod local_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -402,11 +399,10 @@ mod local_date_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -437,7 +433,7 @@ mod local_date_time_test { let input: InputValue = input; let parsed = LocalDateTime::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -455,7 +451,7 @@ mod local_date_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -490,11 +486,10 @@ mod date_time_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -528,7 +523,7 @@ mod date_time_test { let input: InputValue = input; let parsed = DateTime::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -546,7 +541,7 @@ mod date_time_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } @@ -574,11 +569,10 @@ mod utc_offset_test { assert!( parsed.is_ok(), - "failed to parse `{}`: {:?}", - raw, + "failed to parse `{raw}`: {:?}", parsed.unwrap_err(), ); - assert_eq!(parsed.unwrap(), expected, "input: {}", raw); + assert_eq!(parsed.unwrap(), expected, "input: {raw}"); } } @@ -607,7 +601,7 @@ mod utc_offset_test { let input: InputValue = input; let parsed = UtcOffset::from_input_value(&input); - assert!(parsed.is_err(), "allows input: {:?}", input); + assert!(parsed.is_err(), "allows input: {input:?}"); } } @@ -620,7 +614,7 @@ mod utc_offset_test { ] { let actual: InputValue = val.to_input_value(); - assert_eq!(actual, expected, "on value: {}", val); + assert_eq!(actual, expected, "on value: {val}"); } } } diff --git a/juniper/src/integrations/url.rs b/juniper/src/integrations/url.rs index e3764c6b..6121ac56 100644 --- a/juniper/src/integrations/url.rs +++ b/juniper/src/integrations/url.rs @@ -14,8 +14,8 @@ mod url_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) - .and_then(|s| Url::parse(s).map_err(|e| format!("Failed to parse `Url`: {}", e))) + .ok_or_else(|| format!("Expected `String`, found: {v}")) + .and_then(|s| Url::parse(s).map_err(|e| format!("Failed to parse `Url`: {e}"))) } } diff --git a/juniper/src/integrations/uuid.rs b/juniper/src/integrations/uuid.rs index 37f71042..4fed7f5f 100644 --- a/juniper/src/integrations/uuid.rs +++ b/juniper/src/integrations/uuid.rs @@ -16,8 +16,8 @@ mod uuid_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) - .and_then(|s| Uuid::parse_str(s).map_err(|e| format!("Failed to parse `Uuid`: {}", e))) + .ok_or_else(|| format!("Expected `String`, found: {v}")) + .and_then(|s| Uuid::parse_str(s).map_err(|e| format!("Failed to parse `Uuid`: {e}"))) } } diff --git a/juniper/src/introspection/mod.rs b/juniper/src/introspection/mod.rs index aedd4ef9..e59a492e 100644 --- a/juniper/src/introspection/mod.rs +++ b/juniper/src/introspection/mod.rs @@ -5,15 +5,12 @@ pub(crate) const INTROSPECTION_QUERY_WITHOUT_DESCRIPTIONS: &str = /// The desired GraphQL introspection format for the canonical query /// () +#[derive(Clone, Copy, Debug, Default)] pub enum IntrospectionFormat { /// The canonical GraphQL introspection query. + #[default] All, + /// The canonical GraphQL introspection query without descriptions. WithoutDescriptions, } - -impl Default for IntrospectionFormat { - fn default() -> Self { - IntrospectionFormat::All - } -} diff --git a/juniper/src/lib.rs b/juniper/src/lib.rs index e113fcd9..ae753c8e 100644 --- a/juniper/src/lib.rs +++ b/juniper/src/lib.rs @@ -6,6 +6,7 @@ // Required for using `juniper_codegen` macros inside this crate to resolve // absolute `::juniper` path correctly, without errors. +extern crate core; extern crate self as juniper; use std::fmt; @@ -108,10 +109,10 @@ pub enum GraphQLError { impl fmt::Display for GraphQLError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::ParseError(e) => write!(f, "{}", e), + Self::ParseError(e) => write!(f, "{e}"), Self::ValidationError(errs) => { for e in errs { - writeln!(f, "{}", e)?; + writeln!(f, "{e}")?; } Ok(()) } diff --git a/juniper/src/macros/graphql_vars.rs b/juniper/src/macros/graphql_vars.rs index 56bff3b3..5d0f5562 100644 --- a/juniper/src/macros/graphql_vars.rs +++ b/juniper/src/macros/graphql_vars.rs @@ -217,37 +217,35 @@ mod tests { assert_eq!( graphql_vars! {"key": 123}, - vec![("key".to_owned(), IV::scalar(123))] + vec![("key".into(), IV::scalar(123))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": "val"}, - vec![("key".to_owned(), IV::scalar("val"))] + vec![("key".into(), IV::scalar("val"))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": 1.23}, - vec![("key".to_owned(), IV::scalar(1.23))] + vec![("key".into(), IV::scalar(1.23))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": 1 + 2}, - vec![("key".to_owned(), IV::scalar(3))] - .into_iter() - .collect(), + vec![("key".into(), IV::scalar(3))].into_iter().collect(), ); assert_eq!( graphql_vars! {"key": false}, - vec![("key".to_owned(), IV::scalar(false))] + vec![("key".into(), IV::scalar(false))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": (val)}, - vec![("key".to_owned(), IV::scalar(42))] + vec![("key".into(), IV::scalar(42))] .into_iter() .collect::(), ); @@ -257,13 +255,13 @@ mod tests { fn r#enum() { assert_eq!( graphql_vars! {"key": ENUM}, - vec![("key".to_owned(), IV::enum_value("ENUM"))] + vec![("key".into(), IV::enum_value("ENUM"))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": lowercase}, - vec![("key".to_owned(), IV::enum_value("lowercase"))] + vec![("key".into(), IV::enum_value("lowercase"))] .into_iter() .collect::(), ); @@ -273,19 +271,19 @@ mod tests { fn variable() { assert_eq!( graphql_vars! {"key": @var}, - vec![("key".to_owned(), IV::variable("var"))] + vec![("key".into(), IV::variable("var"))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": @array}, - vec![("key".to_owned(), IV::variable("array"))] + vec![("key".into(), IV::variable("array"))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": @object}, - vec![("key".to_owned(), IV::variable("object"))] + vec![("key".into(), IV::variable("object"))] .into_iter() .collect::(), ); @@ -297,68 +295,65 @@ mod tests { assert_eq!( graphql_vars! {"key": []}, - vec![("key".to_owned(), IV::list(vec![]))] + vec![("key".into(), IV::list(vec![]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [null]}, - vec![("key".to_owned(), IV::list(vec![IV::Null]))] + vec![("key".into(), IV::list(vec![IV::Null]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [1]}, - vec![("key".to_owned(), IV::list(vec![IV::scalar(1)]))] + vec![("key".into(), IV::list(vec![IV::scalar(1)]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [1 + 2]}, - vec![("key".to_owned(), IV::list(vec![IV::scalar(3)]))] + vec![("key".into(), IV::list(vec![IV::scalar(3)]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [(val)]}, - vec![("key".to_owned(), IV::list(vec![IV::scalar(42)]))] + vec![("key".into(), IV::list(vec![IV::scalar(42)]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [ENUM]}, - vec![("key".to_owned(), IV::list(vec![IV::enum_value("ENUM")]))] + vec![("key".into(), IV::list(vec![IV::enum_value("ENUM")]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [lowercase]}, - vec![( - "key".to_owned(), - IV::list(vec![IV::enum_value("lowercase")]) - )] - .into_iter() - .collect::(), + vec![("key".into(), IV::list(vec![IV::enum_value("lowercase")]))] + .into_iter() + .collect::(), ); assert_eq!( graphql_vars! {"key": [@var]}, - vec![("key".to_owned(), IV::list(vec![IV::variable("var")]))] + vec![("key".into(), IV::list(vec![IV::variable("var")]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [@array]}, - vec![("key".to_owned(), IV::list(vec![IV::variable("array")]))] + vec![("key".into(), IV::list(vec![IV::variable("array")]))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": [@object]}, - vec![("key".to_owned(), IV::list(vec![IV::variable("object")]))] + vec![("key".into(), IV::list(vec![IV::variable("object")]))] .into_iter() .collect::(), ); @@ -366,7 +361,7 @@ mod tests { assert_eq!( graphql_vars! {"key": [1, [2], 3]}, vec![( - "key".to_owned(), + "key".into(), IV::list(vec![ IV::scalar(1), IV::list(vec![IV::scalar(2)]), @@ -379,7 +374,7 @@ mod tests { assert_eq!( graphql_vars! {"key": [1, [2 + 3], 3]}, vec![( - "key".to_owned(), + "key".into(), IV::list(vec![ IV::scalar(1), IV::list(vec![IV::scalar(5)]), @@ -392,7 +387,7 @@ mod tests { assert_eq!( graphql_vars! {"key": [1, [ENUM], (val)]}, vec![( - "key".to_owned(), + "key".into(), IV::list(vec![ IV::scalar(1), IV::list(vec![IV::enum_value("ENUM")]), @@ -405,7 +400,7 @@ mod tests { assert_eq!( graphql_vars! {"key": [1 + 2, [(val)], @val]}, vec![( - "key".to_owned(), + "key".into(), IV::list(vec![ IV::scalar(3), IV::list(vec![IV::scalar(42)]), @@ -418,7 +413,7 @@ mod tests { assert_eq!( graphql_vars! {"key": [1, [@val], ENUM]}, vec![( - "key".to_owned(), + "key".into(), IV::list(vec![ IV::scalar(1), IV::list(vec![IV::variable("val")]), @@ -436,14 +431,14 @@ mod tests { assert_eq!( graphql_vars! {"key": {}}, - vec![("key".to_owned(), IV::object(IndexMap::::new()))] + vec![("key".into(), IV::object(IndexMap::::new()))] .into_iter() .collect::(), ); assert_eq!( graphql_vars! {"key": {"key": null}}, - vec![("key".to_owned(), IV::object(indexmap! {"key" => IV::Null}))] + vec![("key".into(), IV::object(indexmap! {"key" => IV::Null}))] .into_iter() .collect::(), ); @@ -451,7 +446,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": 123}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::scalar(123)}), )] .into_iter() @@ -459,17 +454,14 @@ mod tests { ); assert_eq!( graphql_vars! {"key": {"key": 1 + 2}}, - vec![( - "key".to_owned(), - IV::object(indexmap! {"key" => IV::scalar(3)}), - )] - .into_iter() - .collect::(), + vec![("key".into(), IV::object(indexmap! {"key" => IV::scalar(3)}),)] + .into_iter() + .collect::(), ); assert_eq!( graphql_vars! {"key": {"key": (val)}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::scalar(42)}), )] .into_iter() @@ -479,7 +471,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": []}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::list(vec![])}), )] .into_iter() @@ -488,7 +480,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": [null]}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::list(vec![IV::Null])}), )] .into_iter() @@ -497,7 +489,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": [1]}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(1)])}), )] .into_iter() @@ -506,7 +498,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": [1 + 2]}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(3)])}), )] .into_iter() @@ -515,7 +507,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": [(val)]}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::list(vec![IV::scalar(42)])}), )] .into_iter() @@ -524,7 +516,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": ENUM}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::enum_value("ENUM")}), )] .into_iter() @@ -533,7 +525,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": lowercase}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::enum_value("lowercase")}), )] .into_iter() @@ -542,7 +534,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": @val}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::variable("val")}), )] .into_iter() @@ -551,7 +543,7 @@ mod tests { assert_eq!( graphql_vars! {"key": {"key": @array}}, vec![( - "key".to_owned(), + "key".into(), IV::object(indexmap! {"key" => IV::variable("array")}), )] .into_iter() @@ -576,7 +568,7 @@ mod tests { }, vec![ ( - "inner".to_owned(), + "inner".into(), IV::object(indexmap! { "key1" => IV::scalar(42), "key2" => IV::scalar("val"), @@ -602,7 +594,7 @@ mod tests { ]), }), ), - ("more".to_owned(), IV::variable("var")), + ("more".into(), IV::variable("var")), ] .into_iter() .collect::(), diff --git a/juniper/src/macros/helper/mod.rs b/juniper/src/macros/helper/mod.rs index f6565e03..e3e31926 100644 --- a/juniper/src/macros/helper/mod.rs +++ b/juniper/src/macros/helper/mod.rs @@ -41,8 +41,7 @@ where /// [`GraphQLType::name`]: crate::GraphQLType::name pub fn err_unnamed_type(name: &str) -> FieldError { FieldError::from(format!( - "Expected `{}` type to implement `GraphQLType::name`", - name, + "Expected `{name}` type to implement `GraphQLType::name`", )) } diff --git a/juniper/src/parser/lexer.rs b/juniper/src/parser/lexer.rs index be76e6ea..3dd4a0e5 100644 --- a/juniper/src/parser/lexer.rs +++ b/juniper/src/parser/lexer.rs @@ -239,7 +239,7 @@ impl<'a> Lexer<'a> { c if escaped => { return Err(Spanning::zero_width( &old_pos, - LexerError::UnknownEscapeSequence(format!("\\{}", c)), + LexerError::UnknownEscapeSequence(format!("\\{c}")), )); } '\\' => escaped = true, @@ -305,14 +305,14 @@ impl<'a> Lexer<'a> { if len != 4 { return Err(Spanning::zero_width( start_pos, - LexerError::UnknownEscapeSequence("\\u".to_owned() + escape), + LexerError::UnknownEscapeSequence(format!("\\u{escape}")), )); } let code_point = u32::from_str_radix(escape, 16).map_err(|_| { Spanning::zero_width( start_pos, - LexerError::UnknownEscapeSequence("\\u".to_owned() + escape), + LexerError::UnknownEscapeSequence(format!("\\u{escape}")), ) })?; @@ -485,9 +485,9 @@ impl<'a> Iterator for Lexer<'a> { impl<'a> fmt::Display for Token<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Token::Name(name) => write!(f, "{}", name), + Token::Name(name) => write!(f, "{name}"), Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => { - write!(f, "{}", s) + write!(f, "{s}") } Token::Scalar(ScalarToken::String(s)) => { write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) @@ -529,15 +529,15 @@ fn is_number_start(c: char) -> bool { impl fmt::Display for LexerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - LexerError::UnknownCharacter(c) => write!(f, "Unknown character \"{}\"", c), + LexerError::UnknownCharacter(c) => write!(f, "Unknown character \"{c}\""), LexerError::UnterminatedString => write!(f, "Unterminated string literal"), LexerError::UnknownCharacterInString(c) => { - write!(f, "Unknown character \"{}\" in string literal", c) + write!(f, "Unknown character \"{c}\" in string literal") } LexerError::UnknownEscapeSequence(ref s) => { - write!(f, "Unknown escape sequence \"{}\" in string", s) + write!(f, "Unknown escape sequence \"{s}\" in string") } - LexerError::UnexpectedCharacter(c) => write!(f, "Unexpected character \"{}\"", c), + LexerError::UnexpectedCharacter(c) => write!(f, "Unexpected character \"{c}\""), LexerError::UnexpectedEndOfFile => write!(f, "Unexpected end of input"), LexerError::InvalidNumber => write!(f, "Invalid number literal"), } diff --git a/juniper/src/parser/parser.rs b/juniper/src/parser/parser.rs index 6ee6e758..89ab697b 100644 --- a/juniper/src/parser/parser.rs +++ b/juniper/src/parser/parser.rs @@ -25,7 +25,7 @@ pub enum ParseError { impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::UnexpectedToken(token) => write!(f, "Unexpected \"{}\"", token), + Self::UnexpectedToken(token) => write!(f, "Unexpected \"{token}\""), Self::UnexpectedEndOfFile => write!(f, "Unexpected end of input"), Self::LexerError(e) => e.fmt(f), Self::ExpectedScalarError(e) => e.fmt(f), @@ -53,7 +53,7 @@ impl ParseError { let mut s = String::new(); // PANIC: Unwrapping is OK here, as it may panic only on allocation // error. - write!(s, "{}", token).unwrap(); + write!(s, "{token}").unwrap(); Self::UnexpectedToken(s) } diff --git a/juniper/src/parser/tests/document.rs b/juniper/src/parser/tests/document.rs index 55ae6230..65018a3d 100644 --- a/juniper/src/parser/tests/document.rs +++ b/juniper/src/parser/tests/document.rs @@ -16,7 +16,7 @@ where s, &SchemaType::new::(&(), &(), &()), ) - .expect(&format!("Parse error on input {:#?}", s)) + .expect(&format!("Parse error on input {s:#?}")) } fn parse_document_error(s: &str) -> Spanning { @@ -24,7 +24,7 @@ fn parse_document_error(s: &str) -> Spanning { s, &SchemaType::new::(&(), &(), &()), ) { - Ok(doc) => panic!("*No* parse error on input {:#?} =>\n{:#?}", s, doc), + Ok(doc) => panic!("*No* parse error on input {s:#?} =>\n{doc:#?}"), Err(err) => err, } } diff --git a/juniper/src/parser/tests/lexer.rs b/juniper/src/parser/tests/lexer.rs index a08dbfaa..7b295270 100644 --- a/juniper/src/parser/tests/lexer.rs +++ b/juniper/src/parser/tests/lexer.rs @@ -13,8 +13,8 @@ fn tokenize_to_vec<'a>(s: &'a str) -> Vec>> { break; } } - Some(Err(e)) => panic!("Error in input stream: {:#?} for {:#?}", e, s), - None => panic!("EOF before EndOfFile token in {:#?}", s), + Some(Err(e)) => panic!("Error in input stream: {e:#?} for {s:#?}"), + None => panic!("EOF before EndOfFile token in {s:#?}"), } } @@ -37,13 +37,13 @@ fn tokenize_error(s: &str) -> Spanning { match lexer.next() { Some(Ok(t)) => { if t.item == Token::EndOfFile { - panic!("Tokenizer did not return error for {:#?}", s); + panic!("Tokenizer did not return error for {s:#?}"); } } Some(Err(e)) => { return e; } - None => panic!("Tokenizer did not return error for {:#?}", s), + None => panic!("Tokenizer did not return error for {s:#?}"), } } } @@ -196,7 +196,7 @@ fn strings() { Spanning::start_end( &SourcePosition::new(0, 0, 0), &SourcePosition::new(34, 0, 34), - Token::Scalar(ScalarToken::String(r#"unicode \u1234\u5678\u90AB\uCDEF"#)) + Token::Scalar(ScalarToken::String(r#"unicode \u1234\u5678\u90AB\uCDEF"#)), ) ); } @@ -207,7 +207,7 @@ fn string_errors() { tokenize_error("\""), Spanning::zero_width( &SourcePosition::new(1, 0, 1), - LexerError::UnterminatedString + LexerError::UnterminatedString, ) ); @@ -215,7 +215,7 @@ fn string_errors() { tokenize_error("\"no end quote"), Spanning::zero_width( &SourcePosition::new(13, 0, 13), - LexerError::UnterminatedString + LexerError::UnterminatedString, ) ); @@ -223,7 +223,7 @@ fn string_errors() { tokenize_error("\"contains unescaped \u{0007} control char\""), Spanning::zero_width( &SourcePosition::new(20, 0, 20), - LexerError::UnknownCharacterInString('\u{0007}') + LexerError::UnknownCharacterInString('\u{0007}'), ) ); @@ -231,7 +231,7 @@ fn string_errors() { tokenize_error("\"null-byte is not \u{0000} end of file\""), Spanning::zero_width( &SourcePosition::new(18, 0, 18), - LexerError::UnknownCharacterInString('\u{0000}') + LexerError::UnknownCharacterInString('\u{0000}'), ) ); @@ -239,7 +239,7 @@ fn string_errors() { tokenize_error("\"multi\nline\""), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnterminatedString + LexerError::UnterminatedString, ) ); @@ -247,7 +247,7 @@ fn string_errors() { tokenize_error("\"multi\rline\""), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnterminatedString + LexerError::UnterminatedString, ) ); @@ -255,7 +255,7 @@ fn string_errors() { tokenize_error(r#""bad \z esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\z".to_owned()) + LexerError::UnknownEscapeSequence("\\z".into()), ) ); @@ -263,7 +263,7 @@ fn string_errors() { tokenize_error(r#""bad \x esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\x".to_owned()) + LexerError::UnknownEscapeSequence("\\x".into()), ) ); @@ -271,7 +271,7 @@ fn string_errors() { tokenize_error(r#""bad \u1 esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\u1".to_owned()) + LexerError::UnknownEscapeSequence("\\u1".into()), ) ); @@ -279,7 +279,7 @@ fn string_errors() { tokenize_error(r#""bad \u0XX1 esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\u0XX1".to_owned()) + LexerError::UnknownEscapeSequence("\\u0XX1".into()), ) ); @@ -287,7 +287,7 @@ fn string_errors() { tokenize_error(r#""bad \uXXXX esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\uXXXX".to_owned()) + LexerError::UnknownEscapeSequence("\\uXXXX".into()), ) ); @@ -295,7 +295,7 @@ fn string_errors() { tokenize_error(r#""bad \uFXXX esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\uFXXX".to_owned()) + LexerError::UnknownEscapeSequence("\\uFXXX".into()), ) ); @@ -303,7 +303,7 @@ fn string_errors() { tokenize_error(r#""bad \uXXXF esc""#), Spanning::zero_width( &SourcePosition::new(6, 0, 6), - LexerError::UnknownEscapeSequence("\\uXXXF".to_owned()) + LexerError::UnknownEscapeSequence("\\uXXXF".into()), ) ); @@ -349,9 +349,7 @@ fn numbers() { Token::Scalar(ScalarToken::Float(actual)) => { assert!( expected == actual, - "[expected] {} != {} [actual]", - expected, - actual + "[expected] {expected} != {actual} [actual]", ); } _ => assert!(false), @@ -662,39 +660,32 @@ fn punctuation_error() { #[test] fn display() { - assert_eq!(format!("{}", Token::Name("identifier")), "identifier"); - - assert_eq!(format!("{}", Token::Scalar(ScalarToken::Int("123"))), "123"); - - assert_eq!( - format!("{}", Token::Scalar(ScalarToken::Float("4.5"))), - "4.5" - ); - - assert_eq!( - format!("{}", Token::Scalar(ScalarToken::String("some string"))), - "\"some string\"" - ); - - assert_eq!( - format!( - "{}", - Token::Scalar(ScalarToken::String("string with \\ escape and \" quote")) + for (input, expected) in [ + (Token::Name("identifier"), "identifier"), + (Token::Scalar(ScalarToken::Int("123")), "123"), + (Token::Scalar(ScalarToken::Float("4.5")), "4.5"), + ( + Token::Scalar(ScalarToken::String("some string")), + "\"some string\"", ), - "\"string with \\\\ escape and \\\" quote\"" - ); - - assert_eq!(format!("{}", Token::ExclamationMark), "!"); - assert_eq!(format!("{}", Token::Dollar), "$"); - assert_eq!(format!("{}", Token::ParenOpen), "("); - assert_eq!(format!("{}", Token::ParenClose), ")"); - assert_eq!(format!("{}", Token::BracketOpen), "["); - assert_eq!(format!("{}", Token::BracketClose), "]"); - assert_eq!(format!("{}", Token::CurlyOpen), "{"); - assert_eq!(format!("{}", Token::CurlyClose), "}"); - assert_eq!(format!("{}", Token::Ellipsis), "..."); - assert_eq!(format!("{}", Token::Colon), ":"); - assert_eq!(format!("{}", Token::Equals), "="); - assert_eq!(format!("{}", Token::At), "@"); - assert_eq!(format!("{}", Token::Pipe), "|"); + ( + Token::Scalar(ScalarToken::String("string with \\ escape and \" quote")), + "\"string with \\\\ escape and \\\" quote\"", + ), + (Token::ExclamationMark, "!"), + (Token::Dollar, "$"), + (Token::ParenOpen, "("), + (Token::ParenClose, ")"), + (Token::BracketOpen, "["), + (Token::BracketClose, "]"), + (Token::CurlyOpen, "{"), + (Token::CurlyClose, "}"), + (Token::Ellipsis, "..."), + (Token::Colon, ":"), + (Token::Equals, "="), + (Token::At, "@"), + (Token::Pipe, "|"), + ] { + assert_eq!(input.to_string(), expected); + } } diff --git a/juniper/src/parser/tests/value.rs b/juniper/src/parser/tests/value.rs index 8dbe78bd..e10a4ab3 100644 --- a/juniper/src/parser/tests/value.rs +++ b/juniper/src/parser/tests/value.rs @@ -65,11 +65,11 @@ where S: ScalarValue, { let mut lexer = Lexer::new(s); - let mut parser = Parser::new(&mut lexer).expect(&format!("Lexer error on input {:#?}", s)); + let mut parser = Parser::new(&mut lexer).expect(&format!("Lexer error on input {s:#?}")); let schema = SchemaType::new::, EmptySubscription<()>>(&(), &(), &()); parse_value_literal(&mut parser, false, &schema, Some(meta)) - .expect(&format!("Parse error on input {:#?}", s)) + .expect(&format!("Parse error on input {s:#?}")) } #[test] diff --git a/juniper/src/schema/meta.rs b/juniper/src/schema/meta.rs index a7d81a8a..1c11d853 100644 --- a/juniper/src/schema/meta.rs +++ b/juniper/src/schema/meta.rs @@ -455,7 +455,7 @@ impl<'a, S> ScalarMeta<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -525,7 +525,7 @@ impl<'a, S> ObjectMeta<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -536,7 +536,7 @@ impl<'a, S> ObjectMeta<'a, S> { pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self { self.interface_names = interfaces .iter() - .map(|t| t.innermost_name().to_owned()) + .map(|t| t.innermost_name().into()) .collect(); self } @@ -568,7 +568,7 @@ impl<'a, S> EnumMeta<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -598,7 +598,7 @@ impl<'a, S> InterfaceMeta<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -609,7 +609,7 @@ impl<'a, S> InterfaceMeta<'a, S> { pub fn interfaces(mut self, interfaces: &[Type<'a>]) -> Self { self.interface_names = interfaces .iter() - .map(|t| t.innermost_name().to_owned()) + .map(|t| t.innermost_name().into()) .collect(); self } @@ -627,10 +627,7 @@ impl<'a> UnionMeta<'a> { Self { name, description: None, - of_type_names: of_types - .iter() - .map(|t| t.innermost_name().to_owned()) - .collect(), + of_type_names: of_types.iter().map(|t| t.innermost_name().into()).collect(), } } @@ -639,7 +636,7 @@ impl<'a> UnionMeta<'a> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -671,7 +668,7 @@ impl<'a, S> InputObjectMeta<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -687,7 +684,7 @@ impl<'a, S> Field<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -712,7 +709,7 @@ impl<'a, S> Field<'a, S> { /// Overwrites any previously set deprecation reason. #[must_use] pub fn deprecated(mut self, reason: Option<&str>) -> Self { - self.deprecation_status = DeprecationStatus::Deprecated(reason.map(ToOwned::to_owned)); + self.deprecation_status = DeprecationStatus::Deprecated(reason.map(Into::into)); self } } @@ -721,7 +718,7 @@ impl<'a, S> Argument<'a, S> { /// Builds a new [`Argument`] of the given [`Type`] with the given `name`. pub fn new(name: &str, arg_type: Type<'a>) -> Self { Self { - name: name.to_owned(), + name: name.into(), description: None, arg_type, default_value: None, @@ -733,7 +730,7 @@ impl<'a, S> Argument<'a, S> { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -751,7 +748,7 @@ impl EnumValue { /// Constructs a new [`EnumValue`] with the provided `name`. pub fn new(name: &str) -> Self { Self { - name: name.to_owned(), + name: name.into(), description: None, deprecation_status: DeprecationStatus::Current, } @@ -762,7 +759,7 @@ impl EnumValue { /// Overwrites any previously set description. #[must_use] pub fn description(mut self, description: &str) -> Self { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } @@ -771,7 +768,7 @@ impl EnumValue { /// Overwrites any previously set deprecation reason. #[must_use] pub fn deprecated(mut self, reason: Option<&str>) -> Self { - self.deprecation_status = DeprecationStatus::Deprecated(reason.map(ToOwned::to_owned)); + self.deprecation_status = DeprecationStatus::Deprecated(reason.map(Into::into)); self } } diff --git a/juniper/src/schema/model.rs b/juniper/src/schema/model.rs index 5544fbbd..e7cba411 100644 --- a/juniper/src/schema/model.rs +++ b/juniper/src/schema/model.rs @@ -167,8 +167,7 @@ where /// [GraphQL Schema Language](https://graphql.org/learn/schema/#type-language) /// format. pub fn as_schema_language(&self) -> String { - let doc = self.as_parser_document(); - format!("{}", doc) + self.as_parser_document().to_string() } #[cfg(feature = "graphql-parser")] @@ -210,17 +209,14 @@ impl<'a, S> SchemaType<'a, S> { registry.get_type::>(&()); - directives.insert("skip".to_owned(), DirectiveType::new_skip(&mut registry)); + directives.insert("skip".into(), DirectiveType::new_skip(&mut registry)); + directives.insert("include".into(), DirectiveType::new_include(&mut registry)); directives.insert( - "include".to_owned(), - DirectiveType::new_include(&mut registry), - ); - directives.insert( - "deprecated".to_owned(), + "deprecated".into(), DirectiveType::new_deprecated(&mut registry), ); directives.insert( - "specifiedBy".to_owned(), + "specifiedBy".into(), DirectiveType::new_specified_by(&mut registry), ); @@ -243,7 +239,7 @@ impl<'a, S> SchemaType<'a, S> { for meta_type in registry.types.values() { if let MetaType::Placeholder(PlaceholderMeta { ref of_type }) = *meta_type { - panic!("Type {:?} is still a placeholder type", of_type); + panic!("Type {of_type:?} is still a placeholder type"); } } SchemaType { @@ -508,9 +504,9 @@ where locations: &[DirectiveLocation], arguments: &[Argument<'a, S>], is_repeatable: bool, - ) -> DirectiveType<'a, S> { - DirectiveType { - name: name.to_owned(), + ) -> Self { + Self { + name: name.into(), description: None, locations: locations.to_vec(), arguments: arguments.to_vec(), @@ -578,7 +574,7 @@ where } pub fn description(mut self, description: &str) -> DirectiveType<'a, S> { - self.description = Some(description.to_owned()); + self.description = Some(description.into()); self } } @@ -605,8 +601,8 @@ impl<'a, S> fmt::Display for TypeType<'a, S> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Concrete(t) => f.write_str(t.name().unwrap()), - Self::List(i, _) => write!(f, "[{}]", i), - Self::NonNull(i) => write!(f, "{}!", i), + Self::List(i, _) => write!(f, "[{i}]"), + Self::NonNull(i) => write!(f, "{i}!"), } } } @@ -644,10 +640,7 @@ mod test { "#, ) .unwrap(); - assert_eq!( - format!("{}", ast), - format!("{}", schema.as_parser_document()), - ); + assert_eq!(ast.to_string(), schema.as_parser_document().to_string()); } } @@ -691,10 +684,10 @@ mod test { } /// This is whatever's description. fn whatever() -> String { - "foo".to_string() + "foo".into() } fn arr(stuff: Vec) -> Option<&'static str> { - (!stuff.is_empty()).then(|| "stuff") + (!stuff.is_empty()).then_some("stuff") } fn fruit() -> Fruit { Fruit::Apple @@ -754,7 +747,7 @@ mod test { "#, ) .unwrap(); - assert_eq!(format!("{}", ast), schema.as_schema_language()); + assert_eq!(ast.to_string(), schema.as_schema_language()); } } } diff --git a/juniper/src/schema/schema.rs b/juniper/src/schema/schema.rs index 09f10bbd..bf48ea37 100644 --- a/juniper/src/schema/schema.rs +++ b/juniper/src/schema/schema.rs @@ -288,16 +288,16 @@ impl<'a, S: ScalarValue + 'a> TypeType<'a, S> { .iter() .filter_map(|&ct| { if let MetaType::Object(ObjectMeta { - ref name, - ref interface_names, + name, + interface_names, .. - }) = *ct + }) = ct { - if interface_names.contains(&iface_name.to_string()) { - context.type_by_name(name) - } else { - None - } + interface_names + .iter() + .any(|name| name == iface_name) + .then(|| context.type_by_name(name)) + .flatten() } else { None } diff --git a/juniper/src/schema/translate/graphql_parser.rs b/juniper/src/schema/translate/graphql_parser.rs index 5532c0fb..6051965b 100644 --- a/juniper/src/schema/translate/graphql_parser.rs +++ b/juniper/src/schema/translate/graphql_parser.rs @@ -285,15 +285,11 @@ where DeprecationStatus::Current => None, DeprecationStatus::Deprecated(reason) => Some(ExternalDirective { position: Pos::default(), - name: From::from("deprecated"), - arguments: if let Some(reason) = reason { - vec![( - From::from("reason"), - ExternalValue::String(reason.to_string()), - )] - } else { - vec![] - }, + name: "deprecated".into(), + arguments: reason + .as_ref() + .map(|rsn| vec![(From::from("reason"), ExternalValue::String(rsn.into()))]) + .unwrap_or_default(), }), } } diff --git a/juniper/src/tests/fixtures/starwars/schema.rs b/juniper/src/tests/fixtures/starwars/schema.rs index d9c795de..d89af6bc 100644 --- a/juniper/src/tests/fixtures/starwars/schema.rs +++ b/juniper/src/tests/fixtures/starwars/schema.rs @@ -93,12 +93,12 @@ impl Human { home_planet: Option<&str>, ) -> Self { Self { - id: id.to_owned(), - name: name.to_owned(), - friend_ids: friend_ids.iter().copied().map(ToOwned::to_owned).collect(), + id: id.into(), + name: name.into(), + friend_ids: friend_ids.iter().copied().map(Into::into).collect(), appears_in: appears_in.to_vec(), - secret_backstory: secret_backstory.map(ToOwned::to_owned), - home_planet: home_planet.map(|p| p.to_owned()), + secret_backstory: secret_backstory.map(Into::into), + home_planet: home_planet.map(Into::into), } } } @@ -153,12 +153,12 @@ impl Droid { primary_function: Option<&str>, ) -> Self { Self { - id: id.to_owned(), - name: name.to_owned(), - friend_ids: friend_ids.iter().copied().map(ToOwned::to_owned).collect(), + id: id.into(), + name: name.into(), + friend_ids: friend_ids.iter().copied().map(Into::into).collect(), appears_in: appears_in.to_vec(), - secret_backstory: secret_backstory.map(ToOwned::to_owned), - primary_function: primary_function.map(ToOwned::to_owned), + secret_backstory: secret_backstory.map(Into::into), + primary_function: primary_function.map(Into::into), } } } @@ -192,7 +192,7 @@ impl Droid { } } -#[derive(Default, Clone)] +#[derive(Clone, Default)] pub struct Database { humans: HashMap, droids: HashMap, @@ -206,7 +206,7 @@ impl Database { let mut droids = HashMap::new(); humans.insert( - "1000".to_owned(), + "1000".into(), Human::new( "1000", "Luke Skywalker", @@ -218,7 +218,7 @@ impl Database { ); humans.insert( - "1001".to_owned(), + "1001".into(), Human::new( "1001", "Darth Vader", @@ -230,7 +230,7 @@ impl Database { ); humans.insert( - "1002".to_owned(), + "1002".into(), Human::new( "1002", "Han Solo", @@ -242,7 +242,7 @@ impl Database { ); humans.insert( - "1003".to_owned(), + "1003".into(), Human::new( "1003", "Leia Organa", @@ -254,7 +254,7 @@ impl Database { ); humans.insert( - "1004".to_owned(), + "1004".into(), Human::new( "1004", "Wilhuff Tarkin", @@ -266,7 +266,7 @@ impl Database { ); droids.insert( - "2000".to_owned(), + "2000".into(), Droid::new( "2000", "C-3PO", @@ -278,7 +278,7 @@ impl Database { ); droids.insert( - "2001".to_owned(), + "2001".into(), Droid::new( "2001", "R2-D2", diff --git a/juniper/src/tests/subscriptions.rs b/juniper/src/tests/subscriptions.rs index 6ba01a76..8c73486b 100644 --- a/juniper/src/tests/subscriptions.rs +++ b/juniper/src/tests/subscriptions.rs @@ -1,4 +1,4 @@ -use std::{iter, iter::FromIterator as _, pin::Pin}; +use std::{iter, pin::Pin}; use futures::{stream, StreamExt as _}; @@ -48,9 +48,9 @@ impl MySubscription { async fn async_human() -> HumanStream { Box::pin(stream::once(async { Human { - id: "stream id".to_string(), - name: "stream name".to_string(), - home_planet: "stream home planet".to_string(), + id: "stream id".into(), + name: "stream name".into(), + home_planet: "stream home planet".into(), } })) } @@ -78,7 +78,7 @@ impl MySubscription { Human { id, name, - home_planet: "default home planet".to_string(), + home_planet: "default home planet".into(), } })) } @@ -154,10 +154,10 @@ fn returns_requested_object() { id name } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter( @@ -182,10 +182,9 @@ fn returns_error() { id name } - }"# - .to_string(); + }"#; - let response = create_and_execute(query); + let response = create_and_execute(query.into()); assert!(response.is_err()); @@ -206,10 +205,10 @@ fn can_access_context() { humanWithContext { id } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( @@ -234,10 +233,10 @@ fn resolves_typed_inline_fragments() { id } } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( @@ -262,10 +261,10 @@ fn resolves_nontyped_inline_fragments() { id } } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( @@ -289,10 +288,10 @@ fn can_access_arguments() { id name } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( @@ -317,10 +316,10 @@ fn type_alias() { id name } - }"# - .to_string(); + }"#; - let (names, collected_values) = create_and_execute(query).expect("Got error from stream"); + let (names, collected_values) = + create_and_execute(query.into()).expect("Got error from stream"); let mut iterator_count = 0; let expected_values = vec![vec![Ok(Value::Object(Object::from_iter(iter::from_fn( diff --git a/juniper/src/tests/type_info_tests.rs b/juniper/src/tests/type_info_tests.rs index 61e7662b..6b43a7ef 100644 --- a/juniper/src/tests/type_info_tests.rs +++ b/juniper/src/tests/type_info_tests.rs @@ -75,15 +75,15 @@ fn test_node() { baz }"#; let node_info = NodeTypeInfo { - name: "MyNode".to_string(), - attribute_names: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()], + name: "MyNode".into(), + attribute_names: vec!["foo".into(), "bar".into(), "baz".into()], }; let mut node = Node { attributes: IndexMap::new(), }; - node.attributes.insert("foo".to_string(), "1".to_string()); - node.attributes.insert("bar".to_string(), "2".to_string()); - node.attributes.insert("baz".to_string(), "3".to_string()); + node.attributes.insert("foo".into(), "1".into()); + node.attributes.insert("bar".into(), "2".into()); + node.attributes.insert("baz".into(), "3".into()); let schema: RootNode<_, _, _> = RootNode::new_with_info( node, EmptyMutation::new(), diff --git a/juniper/src/types/async_await.rs b/juniper/src/types/async_await.rs index ebb948ca..562bff7c 100644 --- a/juniper/src/types/async_await.rs +++ b/juniper/src/types/async_await.rs @@ -226,7 +226,7 @@ where panic!( "Field {} not found on type {:?}", f.name.item, - meta_type.name() + meta_type.name(), ) }); diff --git a/juniper/src/types/base.rs b/juniper/src/types/base.rs index b46315b7..9d54fee0 100644 --- a/juniper/src/types/base.rs +++ b/juniper/src/types/base.rs @@ -377,7 +377,7 @@ where /// // schema in `meta()` above, or a validation failed because of a this library bug. /// // /// // In either of those two cases, the only reasonable way out is to panic the thread. -/// _ => panic!("Field {} not found on type User", field_name), +/// _ => panic!("Field {field_name} not found on type User"), /// } /// } /// } @@ -452,7 +452,7 @@ where panic!( "Field {} not found on type {:?}", f.name.item, - meta_type.name() + meta_type.name(), ) }); diff --git a/juniper/src/types/containers.rs b/juniper/src/types/containers.rs index ab5383a4..108f0e02 100644 --- a/juniper/src/types/containers.rs +++ b/juniper/src/types/containers.rs @@ -522,12 +522,11 @@ where fn into_field_error(self) -> FieldError { const ERROR_PREFIX: &str = "Failed to convert into exact-size array"; match self { - Self::Null => format!("{}: Value cannot be `null`", ERROR_PREFIX).into(), - Self::WrongCount { actual, expected } => format!( - "{}: wrong elements count: {} instead of {}", - ERROR_PREFIX, actual, expected - ) - .into(), + Self::Null => format!("{ERROR_PREFIX}: Value cannot be `null`").into(), + Self::WrongCount { actual, expected } => { + format!("{ERROR_PREFIX}: wrong elements count: {actual} instead of {expected}",) + .into() + } Self::Item(s) => s.into_field_error(), } } diff --git a/juniper/src/types/name.rs b/juniper/src/types/name.rs index eae555d9..fbf5304d 100644 --- a/juniper/src/types/name.rs +++ b/juniper/src/types/name.rs @@ -50,11 +50,10 @@ impl FromStr for Name { type Err = NameParseError; fn from_str(s: &str) -> Result { if Name::is_valid(s) { - Ok(Name(s.to_string())) + Ok(Name(s.into())) } else { Err(NameParseError(format!( - "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{}\" does not", - s + "Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"{s}\" does not", ))) } } diff --git a/juniper/src/types/nullable.rs b/juniper/src/types/nullable.rs index 7e8d01cc..20f16708 100644 --- a/juniper/src/types/nullable.rs +++ b/juniper/src/types/nullable.rs @@ -32,12 +32,16 @@ use crate::{ pub enum Nullable { /// No value ImplicitNull, + /// No value, explicitly specified to be null ExplicitNull, + /// Some value `T` Some(T), } +// Implemented manually to omit redundant `T: Default` trait bound, imposed by +// `#[derive(Default)]`. impl Default for Nullable { fn default() -> Self { Self::ImplicitNull diff --git a/juniper/src/types/scalars.rs b/juniper/src/types/scalars.rs index 3f3422e3..54efa392 100644 --- a/juniper/src/types/scalars.rs +++ b/juniper/src/types/scalars.rs @@ -37,7 +37,7 @@ impl ID { .map(str::to_owned) .or_else(|| v.as_int_value().as_ref().map(ToString::to_string)) .map(Self) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } } @@ -81,7 +81,7 @@ mod impl_string_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_string_value() .map(str::to_owned) - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -120,7 +120,7 @@ mod impl_string_scalar { } Some(s) => { return Err(ParseError::LexerError(LexerError::UnknownEscapeSequence( - format!("\\{}", s), + format!("\\{s}"), ))) } None => return Err(ParseError::LexerError(LexerError::UnterminatedString)), @@ -149,19 +149,16 @@ where .and_then(|c1| { char_iter .next() - .map(|c2| format!("{}{}", c1, c2)) + .map(|c2| format!("{c1}{c2}")) .ok_or_else(|| { - ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{}", c1))) + ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{c1}"))) }) }) .and_then(|mut s| { char_iter .next() .ok_or_else(|| { - ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( - "\\u{}", - s.clone() - ))) + ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{s}"))) }) .map(|c2| { s.push(c2); @@ -172,10 +169,7 @@ where char_iter .next() .ok_or_else(|| { - ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( - "\\u{}", - s.clone() - ))) + ParseError::LexerError(LexerError::UnknownEscapeSequence(format!("\\u{s}"))) }) .map(|c2| { s.push(c2); @@ -184,14 +178,12 @@ where })?; let code_point = u32::from_str_radix(&escaped_code_point, 16).map_err(|_| { ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( - "\\u{}", - escaped_code_point + "\\u{escaped_code_point}", ))) })?; char::from_u32(code_point).ok_or_else(|| { ParseError::LexerError(LexerError::UnknownEscapeSequence(format!( - "\\u{}", - escaped_code_point + "\\u{escaped_code_point}", ))) }) } @@ -282,7 +274,7 @@ mod impl_boolean_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_scalar_value() .and_then(ScalarValue::as_bool) - .ok_or_else(|| format!("Expected `Boolean`, found: {}", v)) + .ok_or_else(|| format!("Expected `Boolean`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -303,7 +295,7 @@ mod impl_int_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() - .ok_or_else(|| format!("Expected `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `Int`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -329,7 +321,7 @@ mod impl_float_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_float_value() - .ok_or_else(|| format!("Expected `Float`, found: {}", v)) + .ok_or_else(|| format!("Expected `Float`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -401,8 +393,9 @@ where { } +// Implemented manually to omit redundant `T: Default` trait bound, imposed by +// `#[derive(Default)]`. impl Default for EmptyMutation { - #[inline] fn default() -> Self { Self::new() } @@ -461,8 +454,9 @@ where { } +// Implemented manually to omit redundant `T: Default` trait bound, imposed by +// `#[derive(Default)]`. impl Default for EmptySubscription { - #[inline] fn default() -> Self { Self::new() } @@ -499,8 +493,8 @@ mod tests { #[test] fn test_id_display() { - let id = ID(String::from("foo")); - assert_eq!(format!("{}", id), "foo"); + let id = ID("foo".into()); + assert_eq!(id.to_string(), "foo"); } #[test] @@ -508,7 +502,7 @@ mod tests { fn parse_string(s: &str, expected: &str) { let s = >::from_str(ScalarToken::String(s)); - assert!(s.is_ok(), "A parsing error occurred: {:?}", s); + assert!(s.is_ok(), "A parsing error occurred: {s:?}"); let s: Option = s.unwrap().into(); assert!(s.is_some(), "No string returned"); assert_eq!(s.unwrap(), expected); @@ -527,7 +521,7 @@ mod tests { #[test] fn parse_f64_from_int() { - for (v, expected) in &[ + for (v, expected) in [ ("0", 0), ("128", 128), ("1601942400", 1601942400), @@ -538,14 +532,14 @@ mod tests { assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err()); let n: Option = n.unwrap().into(); - assert!(n.is_some(), "No f64 returned"); - assert_eq!(n.unwrap(), f64::from(*expected)); + assert!(n.is_some(), "No `f64` returned"); + assert_eq!(n.unwrap(), f64::from(expected)); } } #[test] fn parse_f64_from_float() { - for (v, expected) in &[ + for (v, expected) in [ ("0.", 0.), ("1.2", 1.2), ("1601942400.", 1601942400.), @@ -556,8 +550,8 @@ mod tests { assert!(n.is_ok(), "A parsing error occurred: {:?}", n.unwrap_err()); let n: Option = n.unwrap().into(); - assert!(n.is_some(), "No f64 returned"); - assert_eq!(n.unwrap(), *expected); + assert!(n.is_some(), "No `f64` returned"); + assert_eq!(n.unwrap(), expected); } } diff --git a/juniper/src/validation/context.rs b/juniper/src/validation/context.rs index d90e7362..c96c0491 100644 --- a/juniper/src/validation/context.rs +++ b/juniper/src/validation/context.rs @@ -30,9 +30,9 @@ pub struct ValidatorContext<'a, S: Debug + 'a> { impl RuleError { #[doc(hidden)] - pub fn new(message: &str, locations: &[SourcePosition]) -> RuleError { - RuleError { - message: message.to_owned(), + pub fn new(message: &str, locations: &[SourcePosition]) -> Self { + Self { + message: message.into(), locations: locations.to_vec(), } } @@ -53,14 +53,15 @@ impl RuleError { impl fmt::Display for RuleError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // this is fine since all `RuleError`s should have at least one source position + // This is fine since all `RuleError`s should have at least one source + // position. let locations = self .locations .iter() - .map(|location| format!("{}", location)) + .map(ToString::to_string) .collect::>() .join(", "); - write!(f, "{}. At {}", self.message, locations) + write!(f, "{}. At {locations}", self.message) } } diff --git a/juniper/src/validation/input_value.rs b/juniper/src/validation/input_value.rs index b6238172..780a0ab3 100644 --- a/juniper/src/validation/input_value.rs +++ b/juniper/src/validation/input_value.rs @@ -99,7 +99,7 @@ where var_name, var_pos, &path, - &format!(r#"Expected "{}", found null"#, meta_type), + format!(r#"Expected "{meta_type}", found null"#), )); } else { errors.append(&mut unify_value( @@ -121,10 +121,10 @@ where var_name, var_pos, &path, - &format!( - "Expected list of {} elements, found {} elements", - expected, - l.len() + format!( + "Expected list of {expected} elements, \ + found {} elements", + l.len(), ), )); } @@ -168,11 +168,11 @@ where var_name, var_pos, &path, - &format!( - "Expected input of type `{}`. Got: `{}`. \ + format!( + "Expected input of type `{}`. \ + Got: `{value}`. \ Details: {}", iom.name, - value, e.message(), ), )); @@ -205,10 +205,9 @@ where var_name, var_pos, path, - &format!( - "Expected input scalar `{}`. Got: `{}`. Details: {}", + format!( + "Expected input scalar `{}`. Got: `{value}`. Details: {}", meta.name, - value, e.message(), ), )]; @@ -219,13 +218,13 @@ where var_name, var_pos, path, - &format!(r#"Expected "{}", found list"#, meta.name), + format!(r#"Expected "{}", found list"#, meta.name), )), InputValue::Object(_) => errors.push(unification_error( var_name, var_pos, path, - &format!(r#"Expected "{}", found object"#, meta.name), + format!(r#"Expected "{}", found object"#, meta.name), )), _ => (), } @@ -244,27 +243,27 @@ where { let mut errors: Vec = vec![]; - match *value { + match value { // TODO: avoid this bad duplicate as_str() call. (value system refactor) - InputValue::Scalar(ref scalar) if scalar.as_str().is_some() => { + InputValue::Scalar(scalar) if scalar.as_str().is_some() => { if let Some(name) = scalar.as_str() { if !meta.values.iter().any(|ev| ev.name == *name) { errors.push(unification_error( var_name, var_pos, path, - &format!(r#"Invalid value for enum "{}""#, meta.name), + format!(r#"Invalid value for enum "{}""#, meta.name), )) } } } - InputValue::Enum(ref name) => { + InputValue::Enum(name) => { if !meta.values.iter().any(|ev| &ev.name == name) { errors.push(unification_error( var_name, var_pos, path, - &format!(r#"Invalid value for enum "{}""#, meta.name), + format!(r#"Invalid value for enum "{}""#, meta.name), )) } } @@ -272,7 +271,7 @@ where var_name, var_pos, path, - &format!(r#"Expected "{}", found not a string or enum"#, meta.name), + format!(r#"Expected "{}", found not a string or enum"#, meta.name), )), } errors @@ -318,7 +317,7 @@ where var_name, var_pos, &Path::ObjectField(&input_field.name, path), - &format!(r#"Expected "{}", found null"#, input_field.arg_type), + format!(r#"Expected "{}", found null"#, input_field.arg_type), )); } } @@ -336,7 +335,7 @@ where var_name, var_pos, path, - &format!(r#"Expected "{}", found not an object"#, meta.name), + format!(r#"Expected "{}", found not an object"#, meta.name), )); } errors @@ -349,17 +348,14 @@ where v.map_or(true, InputValue::is_null) } -fn unification_error<'a>( - var_name: &str, +fn unification_error( + var_name: impl fmt::Display, var_pos: &SourcePosition, - path: &Path<'a>, - message: &str, + path: &Path<'_>, + message: impl fmt::Display, ) -> RuleError { RuleError::new( - &format!( - r#"Variable "${}" got invalid value. {}{}."#, - var_name, path, message, - ), + &format!(r#"Variable "${var_name}" got invalid value. {path}{message}."#), &[*var_pos], ) } @@ -368,8 +364,8 @@ impl<'a> fmt::Display for Path<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Path::Root => write!(f, ""), - Path::ArrayElement(idx, prev) => write!(f, "{}In element #{}: ", prev, idx), - Path::ObjectField(name, prev) => write!(f, r#"{}In field "{}": "#, prev, name), + Path::ArrayElement(idx, prev) => write!(f, "{prev}In element #{idx}: "), + Path::ObjectField(name, prev) => write!(f, r#"{prev}In field "{name}": "#), } } } diff --git a/juniper/src/validation/rules/arguments_of_correct_type.rs b/juniper/src/validation/rules/arguments_of_correct_type.rs index 495ca4f7..8230267d 100644 --- a/juniper/src/validation/rules/arguments_of_correct_type.rs +++ b/juniper/src/validation/rules/arguments_of_correct_type.rs @@ -1,3 +1,5 @@ +use std::fmt; + use crate::{ ast::{Directive, Field, InputValue}, parser::Spanning, @@ -6,13 +8,12 @@ use crate::{ validation::{ValidatorContext, Visitor}, value::ScalarValue, }; -use std::fmt::Debug; -pub struct ArgumentsOfCorrectType<'a, S: Debug + 'a> { +pub struct ArgumentsOfCorrectType<'a, S: fmt::Debug + 'a> { current_args: Option<&'a Vec>>, } -pub fn factory<'a, S: Debug>() -> ArgumentsOfCorrectType<'a, S> { +pub fn factory<'a, S: fmt::Debug>() -> ArgumentsOfCorrectType<'a, S> { ArgumentsOfCorrectType { current_args: None } } @@ -59,7 +60,7 @@ where if !is_valid_literal_value(ctx.schema, &meta_type, &arg_value.item) { ctx.report_error( - &error_message(arg_name.item, &format!("{}", argument_meta.arg_type)), + &error_message(arg_name.item, &argument_meta.arg_type), &[arg_value.start], ); } @@ -67,11 +68,8 @@ where } } -fn error_message(arg_name: &str, type_name: &str) -> String { - format!( - "Invalid value for argument \"{}\", expected type \"{}\"", - arg_name, type_name - ) +fn error_message(arg_name: impl fmt::Display, type_name: impl fmt::Display) -> String { + format!("Invalid value for argument \"{arg_name}\", expected type \"{type_name}\"",) } #[cfg(test)] diff --git a/juniper/src/validation/rules/default_values_of_correct_type.rs b/juniper/src/validation/rules/default_values_of_correct_type.rs index 8ef4f98b..2d15f854 100644 --- a/juniper/src/validation/rules/default_values_of_correct_type.rs +++ b/juniper/src/validation/rules/default_values_of_correct_type.rs @@ -1,3 +1,5 @@ +use std::fmt; + use crate::{ ast::VariableDefinition, parser::Spanning, @@ -29,7 +31,7 @@ where { if var_def.var_type.item.is_non_null() { ctx.report_error( - &non_null_error_message(var_name.item, &format!("{}", var_def.var_type.item)), + &non_null_error_message(var_name.item, &var_def.var_type.item), &[*start], ) } else { @@ -37,7 +39,7 @@ where if !is_valid_literal_value(ctx.schema, &meta_type, var_value) { ctx.report_error( - &type_error_message(var_name.item, &format!("{}", var_def.var_type.item)), + &type_error_message(var_name.item, &var_def.var_type.item), &[*start], ); } @@ -46,17 +48,14 @@ where } } -fn type_error_message(arg_name: &str, type_name: &str) -> String { - format!( - "Invalid default value for argument \"{}\", expected type \"{}\"", - arg_name, type_name - ) +fn type_error_message(arg_name: impl fmt::Display, type_name: impl fmt::Display) -> String { + format!("Invalid default value for argument \"{arg_name}\", expected type \"{type_name}\"") } -fn non_null_error_message(arg_name: &str, type_name: &str) -> String { +fn non_null_error_message(arg_name: impl fmt::Display, type_name: impl fmt::Display) -> String { format!( - "Argument \"{}\" has type \"{}\" and is not nullable, so it can't have a default value", - arg_name, type_name + "Argument \"{arg_name}\" has type \"{type_name}\" and is not nullable, \ + so it can't have a default value", ) } diff --git a/juniper/src/validation/rules/fields_on_correct_type.rs b/juniper/src/validation/rules/fields_on_correct_type.rs index ad90cb25..b195df45 100644 --- a/juniper/src/validation/rules/fields_on_correct_type.rs +++ b/juniper/src/validation/rules/fields_on_correct_type.rs @@ -69,7 +69,7 @@ where } fn error_message(field: &str, type_name: &str) -> String { - format!(r#"Unknown field "{}" on type "{}""#, field, type_name) + format!(r#"Unknown field "{field}" on type "{type_name}""#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/fragments_on_composite_types.rs b/juniper/src/validation/rules/fragments_on_composite_types.rs index 1d2ca75b..927f46de 100644 --- a/juniper/src/validation/rules/fragments_on_composite_types.rs +++ b/juniper/src/validation/rules/fragments_on_composite_types.rs @@ -59,15 +59,9 @@ where fn error_message(fragment_name: Option<&str>, on_type: &str) -> String { if let Some(name) = fragment_name { - format!( - r#"Fragment "{}" cannot condition non composite type "{}"#, - name, on_type - ) + format!(r#"Fragment "{name}" cannot condition non composite type "{on_type}"#) } else { - format!( - r#"Fragment cannot condition on non composite type "{}""#, - on_type - ) + format!(r#"Fragment cannot condition on non composite type "{on_type}""#) } } diff --git a/juniper/src/validation/rules/known_argument_names.rs b/juniper/src/validation/rules/known_argument_names.rs index 6e579977..d652caf3 100644 --- a/juniper/src/validation/rules/known_argument_names.rs +++ b/juniper/src/validation/rules/known_argument_names.rs @@ -91,17 +91,11 @@ where } fn field_error_message(arg_name: &str, field_name: &str, type_name: &str) -> String { - format!( - r#"Unknown argument "{}" on field "{}" of type "{}""#, - arg_name, field_name, type_name - ) + format!(r#"Unknown argument "{arg_name}" on field "{field_name}" of type "{type_name}""#) } fn directive_error_message(arg_name: &str, directive_name: &str) -> String { - format!( - r#"Unknown argument "{}" on directive "{}""#, - arg_name, directive_name - ) + format!(r#"Unknown argument "{arg_name}" on directive "{directive_name}""#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/known_directives.rs b/juniper/src/validation/rules/known_directives.rs index 291e17db..9a2b9f5b 100644 --- a/juniper/src/validation/rules/known_directives.rs +++ b/juniper/src/validation/rules/known_directives.rs @@ -154,14 +154,11 @@ where } fn unknown_error_message(directive_name: &str) -> String { - format!(r#"Unknown directive "{}""#, directive_name) + format!(r#"Unknown directive "{directive_name}""#) } fn misplaced_error_message(directive_name: &str, location: &DirectiveLocation) -> String { - format!( - r#"Directive "{}" may not be used on {}"#, - directive_name, location - ) + format!(r#"Directive "{directive_name}" may not be used on {location}"#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/known_fragment_names.rs b/juniper/src/validation/rules/known_fragment_names.rs index 8795de4a..ac4b7b19 100644 --- a/juniper/src/validation/rules/known_fragment_names.rs +++ b/juniper/src/validation/rules/known_fragment_names.rs @@ -28,7 +28,7 @@ where } fn error_message(frag_name: &str) -> String { - format!(r#"Unknown fragment: "{}""#, frag_name) + format!(r#"Unknown fragment: "{frag_name}""#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/known_type_names.rs b/juniper/src/validation/rules/known_type_names.rs index b5b2c936..4f2dffc2 100644 --- a/juniper/src/validation/rules/known_type_names.rs +++ b/juniper/src/validation/rules/known_type_names.rs @@ -56,7 +56,7 @@ fn validate_type<'a, S: Debug>( } fn error_message(type_name: &str) -> String { - format!(r#"Unknown type "{}""#, type_name) + format!(r#"Unknown type "{type_name}""#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/no_fragment_cycles.rs b/juniper/src/validation/rules/no_fragment_cycles.rs index c5489e08..3a6782a7 100644 --- a/juniper/src/validation/rules/no_fragment_cycles.rs +++ b/juniper/src/validation/rules/no_fragment_cycles.rs @@ -126,7 +126,7 @@ impl<'a> CycleDetector<'a> { } fn error_message(frag_name: &str) -> String { - format!(r#"Cannot spread fragment "{}""#, frag_name) + format!(r#"Cannot spread fragment "{frag_name}""#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/no_undefined_variables.rs b/juniper/src/validation/rules/no_undefined_variables.rs index 8f13f191..18287c49 100644 --- a/juniper/src/validation/rules/no_undefined_variables.rs +++ b/juniper/src/validation/rules/no_undefined_variables.rs @@ -151,12 +151,9 @@ where fn error_message(var_name: &str, op_name: Option<&str>) -> String { if let Some(op_name) = op_name { - format!( - r#"Variable "${}" is not defined by operation "{}""#, - var_name, op_name - ) + format!(r#"Variable "${var_name}" is not defined by operation "{op_name}""#) } else { - format!(r#"Variable "${}" is not defined"#, var_name) + format!(r#"Variable "${var_name}" is not defined"#) } } diff --git a/juniper/src/validation/rules/no_unused_fragments.rs b/juniper/src/validation/rules/no_unused_fragments.rs index 97b2bcf8..38a360b5 100644 --- a/juniper/src/validation/rules/no_unused_fragments.rs +++ b/juniper/src/validation/rules/no_unused_fragments.rs @@ -104,7 +104,7 @@ where } fn error_message(frag_name: &str) -> String { - format!(r#"Fragment "{}" is never used"#, frag_name) + format!(r#"Fragment "{frag_name}" is never used"#) } #[cfg(test)] diff --git a/juniper/src/validation/rules/no_unused_variables.rs b/juniper/src/validation/rules/no_unused_variables.rs index 35e5f933..811acde5 100644 --- a/juniper/src/validation/rules/no_unused_variables.rs +++ b/juniper/src/validation/rules/no_unused_variables.rs @@ -142,12 +142,9 @@ where fn error_message(var_name: &str, op_name: Option<&str>) -> String { if let Some(op_name) = op_name { - format!( - r#"Variable "${}" is not used by operation "{}""#, - var_name, op_name - ) + format!(r#"Variable "${var_name}" is not used by operation "{op_name}""#) } else { - format!(r#"Variable "${}" is not used"#, var_name) + format!(r#"Variable "${var_name}" is not used"#) } } diff --git a/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs b/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs index 1b13f393..5a9260b1 100644 --- a/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs +++ b/juniper/src/validation/rules/overlapping_fields_can_be_merged.rs @@ -376,10 +376,9 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> { if name1 != name2 { return Some(Conflict( ConflictReason( - response_name.to_owned(), + response_name.into(), ConflictReasonMessage::Message(format!( - "{} and {} are different fields", - name1, name2 + "{name1} and {name2} are different fields", )), ), vec![ast1.start], @@ -390,8 +389,8 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> { if !self.is_same_arguments(&ast1.item.arguments, &ast2.item.arguments) { return Some(Conflict( ConflictReason( - response_name.to_owned(), - ConflictReasonMessage::Message("they have differing arguments".to_owned()), + response_name.into(), + ConflictReasonMessage::Message("they have differing arguments".into()), ), vec![ast1.start], vec![ast2.start], @@ -406,10 +405,9 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> { if self.is_type_conflict(ctx, t1, t2) { return Some(Conflict( ConflictReason( - response_name.to_owned(), + response_name.into(), ConflictReasonMessage::Message(format!( - "they return conflicting types {} and {}", - t1, t2 + "they return conflicting types {t1} and {t2}", )), ), vec![ast1.start], @@ -513,7 +511,7 @@ impl<'a, S: Debug> OverlappingFieldsCanBeMerged<'a, S> { Some(Conflict( ConflictReason( - response_name.to_owned(), + response_name.into(), ConflictReasonMessage::Nested(conflicts.iter().map(|c| c.0.clone()).collect()), ), vec![*pos1] @@ -722,10 +720,8 @@ where fn error_message(reason_name: &str, reason: &ConflictReasonMessage) -> String { let suffix = "Use different aliases on the fields to fetch both if this was intentional"; format!( - r#"Fields "{}" conflict because {}. {}"#, - reason_name, + r#"Fields "{reason_name}" conflict because {}. {suffix}"#, format_reason(reason), - suffix ) } @@ -736,9 +732,8 @@ fn format_reason(reason: &ConflictReasonMessage) -> String { .iter() .map(|&ConflictReason(ref name, ref subreason)| { format!( - r#"subfields "{}" conflict because {}"#, - name, - format_reason(subreason) + r#"subfields "{name}" conflict because {}"#, + format_reason(subreason), ) }) .collect::>() @@ -872,7 +867,7 @@ mod tests { &[RuleError::new( &error_message( "fido", - &Message("name and nickname are different fields".to_owned()), + &Message("name and nickname are different fields".into()), ), &[ SourcePosition::new(78, 2, 12), @@ -912,7 +907,7 @@ mod tests { &[RuleError::new( &error_message( "name", - &Message("nickname and name are different fields".to_owned()), + &Message("nickname and name are different fields".into()), ), &[ SourcePosition::new(71, 2, 12), @@ -935,7 +930,7 @@ mod tests { &[RuleError::new( &error_message( "doesKnowCommand", - &Message("they have differing arguments".to_owned()), + &Message("they have differing arguments".into()), ), &[ SourcePosition::new(57, 2, 12), @@ -958,7 +953,7 @@ mod tests { &[RuleError::new( &error_message( "doesKnowCommand", - &Message("they have differing arguments".to_owned()), + &Message("they have differing arguments".into()), ), &[ SourcePosition::new(57, 2, 12), @@ -981,7 +976,7 @@ mod tests { &[RuleError::new( &error_message( "doesKnowCommand", - &Message("they have differing arguments".to_owned()), + &Message("they have differing arguments".into()), ), &[ SourcePosition::new(57, 2, 12), @@ -1025,10 +1020,7 @@ mod tests { } "#, &[RuleError::new( - &error_message( - "x", - &Message("name and barks are different fields".to_owned()), - ), + &error_message("x", &Message("name and barks are different fields".into())), &[ SourcePosition::new(101, 6, 12), SourcePosition::new(163, 9, 12), @@ -1066,10 +1058,7 @@ mod tests { "#, &[ RuleError::new( - &error_message( - "x", - &Message("name and barks are different fields".to_owned()), - ), + &error_message("x", &Message("name and barks are different fields".into())), &[ SourcePosition::new(235, 13, 14), SourcePosition::new(311, 17, 12), @@ -1078,7 +1067,7 @@ mod tests { RuleError::new( &error_message( "x", - &Message("name and nickname are different fields".to_owned()), + &Message("name and nickname are different fields".into()), ), &[ SourcePosition::new(235, 13, 14), @@ -1088,7 +1077,7 @@ mod tests { RuleError::new( &error_message( "x", - &Message("barks and nickname are different fields".to_owned()), + &Message("barks and nickname are different fields".into()), ), &[ SourcePosition::new(311, 17, 12), @@ -1117,8 +1106,8 @@ mod tests { &error_message( "dog", &Nested(vec![ConflictReason( - "x".to_owned(), - Message("name and barks are different fields".to_owned()), + "x".into(), + Message("name and barks are different fields".into()), )]), ), &[ @@ -1152,12 +1141,12 @@ mod tests { "dog", &Nested(vec![ ConflictReason( - "x".to_owned(), - Message("barks and nickname are different fields".to_owned()), + "x".into(), + Message("barks and nickname are different fields".into()), ), ConflictReason( - "y".to_owned(), - Message("name and barkVolume are different fields".to_owned()), + "y".into(), + Message("name and barkVolume are different fields".into()), ), ]), ), @@ -1195,10 +1184,10 @@ mod tests { &error_message( "human", &Nested(vec![ConflictReason( - "relatives".to_owned(), + "relatives".into(), Nested(vec![ConflictReason( - "x".to_owned(), - Message("name and iq are different fields".to_owned()), + "x".into(), + Message("name and iq are different fields".into()), )]), )]), ), @@ -1239,8 +1228,8 @@ mod tests { &error_message( "relatives", &Nested(vec![ConflictReason( - "x".to_owned(), - Message("iq and name are different fields".to_owned()), + "x".into(), + Message("iq and name are different fields".into()), )]), ), &[ @@ -1286,8 +1275,8 @@ mod tests { &error_message( "relatives", &Nested(vec![ConflictReason( - "x".to_owned(), - Message("iq and name are different fields".to_owned()), + "x".into(), + Message("iq and name are different fields".into()), )]), ), &[ @@ -1333,12 +1322,12 @@ mod tests { "dog", &Nested(vec![ ConflictReason( - "x".to_owned(), - Message("name and barks are different fields".to_owned()), + "x".into(), + Message("name and barks are different fields".into()), ), ConflictReason( - "y".to_owned(), - Message("barkVolume and nickname are different fields".to_owned()), + "y".into(), + Message("barkVolume and nickname are different fields".into()), ), ]), ), @@ -1794,7 +1783,7 @@ mod tests { &[RuleError::new( &error_message( "scalar", - &Message("they return conflicting types Int and String!".to_owned()), + &Message("they return conflicting types Int and String!".into()), ), &[ SourcePosition::new(88, 4, 18), @@ -1858,7 +1847,7 @@ mod tests { &[RuleError::new( &error_message( "scalar", - &Message("they return conflicting types Int and String".to_owned()), + &Message("they return conflicting types Int and String".into()), ), &[ SourcePosition::new(89, 4, 18), @@ -1922,8 +1911,8 @@ mod tests { &error_message( "other", &Nested(vec![ConflictReason( - "otherField".to_owned(), - Message("otherField and unrelatedField are different fields".to_owned()), + "otherField".into(), + Message("otherField and unrelatedField are different fields".into()), )]), ), &[ @@ -1957,7 +1946,7 @@ mod tests { &[RuleError::new( &error_message( "scalar", - &Message("they return conflicting types String! and String".to_owned()), + &Message("they return conflicting types String! and String".into()), ), &[ SourcePosition::new(100, 4, 18), @@ -1992,7 +1981,7 @@ mod tests { &[RuleError::new( &error_message( "box", - &Message("they return conflicting types [StringBox] and StringBox".to_owned()), + &Message("they return conflicting types [StringBox] and StringBox".into()), ), &[ SourcePosition::new(89, 4, 18), @@ -2024,7 +2013,7 @@ mod tests { &[RuleError::new( &error_message( "box", - &Message("they return conflicting types StringBox and [StringBox]".to_owned()), + &Message("they return conflicting types StringBox and [StringBox]".into()), ), &[ SourcePosition::new(89, 4, 18), @@ -2060,7 +2049,7 @@ mod tests { &[RuleError::new( &error_message( "val", - &Message("scalar and unrelatedField are different fields".to_owned()), + &Message("scalar and unrelatedField are different fields".into()), ), &[ SourcePosition::new(126, 5, 20), @@ -2096,8 +2085,8 @@ mod tests { &error_message( "box", &Nested(vec![ConflictReason( - "scalar".to_owned(), - Message("they return conflicting types String and Int".to_owned()), + "scalar".into(), + Message("they return conflicting types String and Int".into()), )]), ), &[ @@ -2227,10 +2216,10 @@ mod tests { &error_message( "edges", &Nested(vec![ConflictReason( - "node".to_owned(), + "node".into(), Nested(vec![ConflictReason( - "id".to_owned(), - Message("name and id are different fields".to_owned()), + "id".into(), + Message("name and id are different fields".into()), )]), )]), ), @@ -2278,7 +2267,7 @@ mod tests { #[test] fn error_message_contains_hint_for_alias_conflict() { assert_eq!( - &error_message("x", &Message("a and b are different fields".to_owned())), + &error_message("x", &Message("a and b are different fields".into())), "Fields \"x\" conflict because a and b are different fields. Use \ different aliases on the fields to fetch both if this \ was intentional" diff --git a/juniper/src/validation/rules/possible_fragment_spreads.rs b/juniper/src/validation/rules/possible_fragment_spreads.rs index 53ef05a3..c9e11f6f 100644 --- a/juniper/src/validation/rules/possible_fragment_spreads.rs +++ b/juniper/src/validation/rules/possible_fragment_spreads.rs @@ -119,15 +119,13 @@ where fn error_message(frag_name: Option<&str>, parent_type_name: &str, frag_type: &str) -> String { if let Some(frag_name) = frag_name { format!( - "Fragment \"{}\" cannot be spread here as objects of type \ - \"{}\" can never be of type \"{}\"", - frag_name, parent_type_name, frag_type + "Fragment \"{frag_name}\" cannot be spread here as objects of type \ + \"{parent_type_name}\" can never be of type \"{frag_type}\"", ) } else { format!( - "Fragment cannot be spread here as objects of type \"{}\" \ - can never be of type \"{}\"", - parent_type_name, frag_type + "Fragment cannot be spread here as objects of type \ + \"{parent_type_name}\" can never be of type \"{frag_type}\"", ) } } diff --git a/juniper/src/validation/rules/provided_non_null_arguments.rs b/juniper/src/validation/rules/provided_non_null_arguments.rs index eb76c150..35672e18 100644 --- a/juniper/src/validation/rules/provided_non_null_arguments.rs +++ b/juniper/src/validation/rules/provided_non_null_arguments.rs @@ -1,3 +1,5 @@ +use std::fmt; + use crate::{ ast::{Directive, Field}, parser::Spanning, @@ -35,11 +37,7 @@ where .is_none() { ctx.report_error( - &field_error_message( - field_name, - &meta_arg.name, - &format!("{}", meta_arg.arg_type), - ), + &field_error_message(field_name, &meta_arg.name, &meta_arg.arg_type), &[field.start], ); } @@ -72,7 +70,7 @@ where &directive_error_message( directive_name, &meta_arg.name, - &format!("{}", meta_arg.arg_type), + &meta_arg.arg_type, ), &[directive.start], ); @@ -82,17 +80,23 @@ where } } -fn field_error_message(field_name: &str, arg_name: &str, type_name: &str) -> String { +fn field_error_message( + field_name: impl fmt::Display, + arg_name: impl fmt::Display, + type_name: impl fmt::Display, +) -> String { format!( - r#"Field "{}" argument "{}" of type "{}" is required but not provided"#, - field_name, arg_name, type_name + r#"Field "{field_name}" argument "{arg_name}" of type "{type_name}" is required but not provided"#, ) } -fn directive_error_message(directive_name: &str, arg_name: &str, type_name: &str) -> String { +fn directive_error_message( + directive_name: impl fmt::Display, + arg_name: impl fmt::Display, + type_name: impl fmt::Display, +) -> String { format!( - r#"Directive "@{}" argument "{}" of type "{}" is required but not provided"#, - directive_name, arg_name, type_name + r#"Directive "@{directive_name}" argument "{arg_name}" of type "{type_name}" is required but not provided"#, ) } diff --git a/juniper/src/validation/rules/scalar_leafs.rs b/juniper/src/validation/rules/scalar_leafs.rs index fe5ac777..00a92dad 100644 --- a/juniper/src/validation/rules/scalar_leafs.rs +++ b/juniper/src/validation/rules/scalar_leafs.rs @@ -1,3 +1,5 @@ +use std::fmt; + use crate::{ ast::Field, parser::Spanning, @@ -23,11 +25,11 @@ where { match (field_type.is_leaf(), &field.item.selection_set) { (true, &Some(_)) => Some(RuleError::new( - &no_allowed_error_message(field_name, &format!("{}", field_type_literal)), + &no_allowed_error_message(field_name, field_type_literal), &[field.start], )), (false, &None) => Some(RuleError::new( - &required_error_message(field_name, &format!("{}", field_type_literal)), + &required_error_message(field_name, field_type_literal), &[field.start], )), _ => None, @@ -42,17 +44,15 @@ where } } -fn no_allowed_error_message(field_name: &str, type_name: &str) -> String { +fn no_allowed_error_message(field_name: impl fmt::Display, type_name: impl fmt::Display) -> String { format!( - r#"Field "{}" must not have a selection since type {} has no subfields"#, - field_name, type_name + r#"Field "{field_name}" must not have a selection since type {type_name} has no subfields"#, ) } -fn required_error_message(field_name: &str, type_name: &str) -> String { +fn required_error_message(field_name: impl fmt::Display, type_name: impl fmt::Display) -> String { format!( - r#"Field "{}" of type "{}" must have a selection of subfields. Did you mean "{} {{ ... }}"?"#, - field_name, type_name, field_name + r#"Field "{field_name}" of type "{type_name}" must have a selection of subfields. Did you mean "{field_name} {{ ... }}"?"#, ) } diff --git a/juniper/src/validation/rules/unique_argument_names.rs b/juniper/src/validation/rules/unique_argument_names.rs index 0b6ae6d6..697e0a27 100644 --- a/juniper/src/validation/rules/unique_argument_names.rs +++ b/juniper/src/validation/rules/unique_argument_names.rs @@ -46,7 +46,7 @@ where } fn error_message(arg_name: &str) -> String { - format!("There can only be one argument named \"{}\"", arg_name) + format!("There can only be one argument named \"{arg_name}\"") } #[cfg(test)] diff --git a/juniper/src/validation/rules/unique_fragment_names.rs b/juniper/src/validation/rules/unique_fragment_names.rs index 2bcbb440..f54e46d1 100644 --- a/juniper/src/validation/rules/unique_fragment_names.rs +++ b/juniper/src/validation/rules/unique_fragment_names.rs @@ -41,7 +41,7 @@ where } fn duplicate_message(frag_name: &str) -> String { - format!("There can only be one fragment named {}", frag_name) + format!("There can only be one fragment named {frag_name}") } #[cfg(test)] diff --git a/juniper/src/validation/rules/unique_input_field_names.rs b/juniper/src/validation/rules/unique_input_field_names.rs index db507502..7108c767 100644 --- a/juniper/src/validation/rules/unique_input_field_names.rs +++ b/juniper/src/validation/rules/unique_input_field_names.rs @@ -53,7 +53,7 @@ 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) + format!("There can only be one input field named \"{field_name}\"") } #[cfg(test)] diff --git a/juniper/src/validation/rules/unique_operation_names.rs b/juniper/src/validation/rules/unique_operation_names.rs index 4d7e56f1..8f693696 100644 --- a/juniper/src/validation/rules/unique_operation_names.rs +++ b/juniper/src/validation/rules/unique_operation_names.rs @@ -40,7 +40,7 @@ where } fn error_message(op_name: &str) -> String { - format!("There can only be one operation named {}", op_name) + format!("There can only be one operation named {op_name}") } #[cfg(test)] diff --git a/juniper/src/validation/rules/unique_variable_names.rs b/juniper/src/validation/rules/unique_variable_names.rs index 0c32706b..738e634b 100644 --- a/juniper/src/validation/rules/unique_variable_names.rs +++ b/juniper/src/validation/rules/unique_variable_names.rs @@ -46,7 +46,7 @@ where } fn error_message(var_name: &str) -> String { - format!("There can only be one variable named {}", var_name) + format!("There can only be one variable named {var_name}") } #[cfg(test)] diff --git a/juniper/src/validation/rules/variables_are_input_types.rs b/juniper/src/validation/rules/variables_are_input_types.rs index 0336b618..168119d6 100644 --- a/juniper/src/validation/rules/variables_are_input_types.rs +++ b/juniper/src/validation/rules/variables_are_input_types.rs @@ -1,3 +1,5 @@ +use std::fmt; + use crate::{ ast::VariableDefinition, parser::Spanning, @@ -26,7 +28,7 @@ where { if !var_type.is_input() { ctx.report_error( - &error_message(var_name.item, &format!("{}", var_def.var_type.item)), + &error_message(var_name.item, &var_def.var_type.item), &[var_def.var_type.start], ); } @@ -34,11 +36,8 @@ where } } -fn error_message(var_name: &str, type_name: &str) -> String { - format!( - "Variable \"{}\" cannot be of non-input type \"{}\"", - var_name, type_name - ) +fn error_message(var_name: impl fmt::Display, type_name: impl fmt::Display) -> String { + format!("Variable \"{var_name}\" cannot be of non-input type \"{type_name}\"") } #[cfg(test)] diff --git a/juniper/src/validation/rules/variables_in_allowed_position.rs b/juniper/src/validation/rules/variables_in_allowed_position.rs index 1f3dff59..550b47a8 100644 --- a/juniper/src/validation/rules/variables_in_allowed_position.rs +++ b/juniper/src/validation/rules/variables_in_allowed_position.rs @@ -1,7 +1,7 @@ use std::{ borrow::Cow, collections::{HashMap, HashSet}, - fmt::Debug, + fmt, }; use crate::{ @@ -17,7 +17,7 @@ pub enum Scope<'a> { Fragment(&'a str), } -pub struct VariableInAllowedPosition<'a, S: Debug + 'a> { +pub struct VariableInAllowedPosition<'a, S: fmt::Debug + 'a> { spreads: HashMap, HashSet<&'a str>>, variable_usages: HashMap, Vec<(Spanning<&'a String>, Type<'a>)>>, #[allow(clippy::type_complexity)] @@ -25,7 +25,7 @@ pub struct VariableInAllowedPosition<'a, S: Debug + 'a> { current_scope: Option>, } -pub fn factory<'a, S: Debug>() -> VariableInAllowedPosition<'a, S> { +pub fn factory<'a, S: fmt::Debug>() -> VariableInAllowedPosition<'a, S> { VariableInAllowedPosition { spreads: HashMap::new(), variable_usages: HashMap::new(), @@ -34,7 +34,7 @@ pub fn factory<'a, S: Debug>() -> VariableInAllowedPosition<'a, S> { } } -impl<'a, S: Debug> VariableInAllowedPosition<'a, S> { +impl<'a, S: fmt::Debug> VariableInAllowedPosition<'a, S> { fn collect_incorrect_usages( &self, from: &Scope<'a>, @@ -66,11 +66,7 @@ impl<'a, S: Debug> VariableInAllowedPosition<'a, S> { if !ctx.schema.is_subtype(&expected_type, var_type) { ctx.report_error( - &error_message( - var_name.item, - &format!("{}", expected_type), - &format!("{}", var_type), - ), + &error_message(var_name.item, expected_type, var_type), &[var_def_name.start, var_name.start], ); } @@ -157,10 +153,13 @@ where } } -fn error_message(var_name: &str, type_name: &str, expected_type_name: &str) -> String { +fn error_message( + var_name: impl fmt::Display, + type_name: impl fmt::Display, + expected_type_name: impl fmt::Display, +) -> String { format!( - "Variable \"{}\" of type \"{}\" used in position expecting type \"{}\"", - var_name, type_name, expected_type_name + "Variable \"{var_name}\" of type \"{type_name}\" used in position expecting type \"{expected_type_name}\"", ) } diff --git a/juniper/src/validation/test_harness.rs b/juniper/src/validation/test_harness.rs index 1772b639..492e4564 100644 --- a/juniper/src/validation/test_harness.rs +++ b/juniper/src/validation/test_harness.rs @@ -920,7 +920,7 @@ where )); let doc = - parse_document_source(q, &root.schema).expect(&format!("Parse error on input {:#?}", q)); + parse_document_source(q, &root.schema).expect(&format!("Parse error on input {q:#?}")); let mut ctx = ValidatorContext::new(unsafe { mem::transmute(&root.schema) }, &doc); visit_fn(&mut ctx, unsafe { mem::transmute(doc.as_slice()) }); diff --git a/juniper/src/value/mod.rs b/juniper/src/value/mod.rs index e3457c8e..6a160807 100644 --- a/juniper/src/value/mod.rs +++ b/juniper/src/value/mod.rs @@ -196,15 +196,15 @@ impl fmt::Display for Value { Self::Null => write!(f, "null"), Self::Scalar(s) => { if let Some(string) = s.as_string() { - write!(f, "\"{}\"", string) + write!(f, "\"{string}\"") } else { - write!(f, "{}", s) + write!(f, "{s}") } } Self::List(list) => { write!(f, "[")?; for (idx, item) in list.iter().enumerate() { - write!(f, "{}", item)?; + write!(f, "{item}")?; if idx < list.len() - 1 { write!(f, ", ")?; } @@ -216,7 +216,7 @@ impl fmt::Display for Value { Self::Object(obj) => { write!(f, "{{")?; for (idx, (key, value)) in obj.iter().enumerate() { - write!(f, "\"{}\": {}", key, value)?; + write!(f, "\"{key}\": {value}")?; if idx < obj.field_count() - 1 { write!(f, ", ")?; @@ -287,52 +287,52 @@ mod tests { #[test] fn display_null() { let s: Value = graphql_value!(null); - assert_eq!("null", format!("{}", s)); + assert_eq!(s.to_string(), "null"); } #[test] fn display_int() { let s: Value = graphql_value!(123); - assert_eq!("123", format!("{}", s)); + assert_eq!(s.to_string(), "123"); } #[test] fn display_float() { let s: Value = graphql_value!(123.456); - assert_eq!("123.456", format!("{}", s)); + assert_eq!(s.to_string(), "123.456"); } #[test] fn display_string() { let s: Value = graphql_value!("foo"); - assert_eq!("\"foo\"", format!("{}", s)); + assert_eq!(s.to_string(), "\"foo\""); } #[test] fn display_bool() { let s: Value = graphql_value!(false); - assert_eq!("false", format!("{}", s)); + assert_eq!(s.to_string(), "false"); let s: Value = graphql_value!(true); - assert_eq!("true", format!("{}", s)); + assert_eq!(s.to_string(), "true"); } #[test] fn display_list() { let s: Value = graphql_value!([1, null, "foo"]); - assert_eq!("[1, null, \"foo\"]", format!("{}", s)); + assert_eq!(s.to_string(), "[1, null, \"foo\"]"); } #[test] fn display_list_one_element() { let s: Value = graphql_value!([1]); - assert_eq!("[1]", format!("{}", s)); + assert_eq!(s.to_string(), "[1]"); } #[test] fn display_list_empty() { let s: Value = graphql_value!([]); - assert_eq!("[]", format!("{}", s)); + assert_eq!(s.to_string(), "[]"); } #[test] @@ -343,8 +343,8 @@ mod tests { "string": "foo", }); assert_eq!( + s.to_string(), r#"{"int": 1, "null": null, "string": "foo"}"#, - format!("{}", s) ); } @@ -353,12 +353,12 @@ mod tests { let s: Value = graphql_value!({ "int": 1, }); - assert_eq!(r#"{"int": 1}"#, format!("{}", s)); + assert_eq!(s.to_string(), r#"{"int": 1}"#); } #[test] fn display_object_empty() { let s: Value = graphql_value!({}); - assert_eq!(r#"{}"#, format!("{}", s)); + assert_eq!(s.to_string(), r#"{}"#); } } diff --git a/juniper/src/value/object.rs b/juniper/src/value/object.rs index 909abe3f..4e3deb41 100644 --- a/juniper/src/value/object.rs +++ b/juniper/src/value/object.rs @@ -1,4 +1,4 @@ -use std::{iter::FromIterator, mem}; +use std::mem; use super::Value; use indexmap::map::{IndexMap, IntoIter}; diff --git a/juniper/src/value/scalar.rs b/juniper/src/value/scalar.rs index fa1dd441..f93e7bbf 100644 --- a/juniper/src/value/scalar.rs +++ b/juniper/src/value/scalar.rs @@ -34,7 +34,7 @@ pub trait ParseScalarValue { /// integers. /// /// ```rust -/// # use std::{fmt, convert::TryInto as _}; +/// # use std::fmt; /// # /// # use serde::{de, Deserialize, Deserializer, Serialize}; /// # use juniper::ScalarValue; diff --git a/juniper_actix/Cargo.toml b/juniper_actix/Cargo.toml index 72127db6..17c91837 100644 --- a/juniper_actix/Cargo.toml +++ b/juniper_actix/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_actix" version = "0.5.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "`juniper` GraphQL integration with `actix-web`." license = "BSD-2-Clause" authors = ["Jordao Rosario "] diff --git a/juniper_actix/examples/actix_server.rs b/juniper_actix/examples/actix_server.rs index 5a13b79a..ab27373d 100644 --- a/juniper_actix/examples/actix_server.rs +++ b/juniper_actix/examples/actix_server.rs @@ -21,7 +21,7 @@ pub struct User { name: String, } -#[derive(Default, Clone)] +#[derive(Clone, Default)] pub struct Database { ///this could be a database connection users: HashMap, @@ -33,28 +33,28 @@ impl Database { 1, User { id: 1, - name: "Aron".to_string(), + name: "Aron".into(), }, ); users.insert( 2, User { id: 2, - name: "Bea".to_string(), + name: "Bea".into(), }, ); users.insert( 3, User { id: 3, - name: "Carl".to_string(), + name: "Carl".into(), }, ); users.insert( 4, User { id: 4, - name: "Dora".to_string(), + name: "Dora".into(), }, ); Database { users } diff --git a/juniper_actix/src/lib.rs b/juniper_actix/src/lib.rs index c88c1b00..3c6192e6 100644 --- a/juniper_actix/src/lib.rs +++ b/juniper_actix/src/lib.rs @@ -368,7 +368,7 @@ pub mod subscriptions { Err(e) => { let reason = ws::CloseReason { code: ws::CloseCode::Error, - description: Some(format!("error serializing response: {}", e)), + description: Some(format!("error serializing response: {e}")), }; // TODO: trace @@ -389,7 +389,7 @@ pub mod subscriptions { #[derive(Debug)] struct Message(ws::Message); - impl std::convert::TryFrom for ClientMessage { + impl TryFrom for ClientMessage { type Error = Error; fn try_from(msg: Message) -> Result { @@ -416,7 +416,7 @@ pub mod subscriptions { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Serde(e) => write!(f, "serde error: {}", e), + Self::Serde(e) => write!(f, "serde error: {e}"), Self::UnexpectedClientMessage => { write!(f, "unexpected message received from client") } @@ -712,7 +712,7 @@ mod tests { self.make_request( TestRequest::post() .append_header(("content-type", "application/json")) - .set_payload(body.to_string()) + .set_payload(body.to_owned()) .uri(url), ) } @@ -721,7 +721,7 @@ mod tests { self.make_request( TestRequest::post() .append_header(("content-type", "application/graphql")) - .set_payload(body.to_string()) + .set_payload(body.to_owned()) .uri(url), ) } @@ -735,7 +735,7 @@ mod tests { .unwrap() .to_str() .unwrap() - .to_string(); + .into(); let body = take_response_body_string(resp).await; TestResponse { status_code: status_code as i32, @@ -797,29 +797,28 @@ mod subscription_tests { framed .send(ws::Message::Text(body.to_owned().into())) .await - .map_err(|e| anyhow::anyhow!("WS error: {:?}", e))?; + .map_err(|e| anyhow::anyhow!("WS error: {e:?}"))?; } WsIntegrationMessage::Expect(body, message_timeout) => { let frame = timeout(Duration::from_millis(*message_timeout), framed.next()) .await .map_err(|_| anyhow::anyhow!("Timed-out waiting for message"))? .ok_or_else(|| anyhow::anyhow!("Empty message received"))? - .map_err(|e| anyhow::anyhow!("WS error: {:?}", e))?; + .map_err(|e| anyhow::anyhow!("WS error: {e:?}"))?; match frame { ws::Frame::Text(ref bytes) => { let expected_value = serde_json::from_str::(body) - .map_err(|e| anyhow::anyhow!("Serde error: {:?}", e))?; + .map_err(|e| anyhow::anyhow!("Serde error: {e:?}"))?; let value: serde_json::Value = serde_json::from_slice(bytes) - .map_err(|e| anyhow::anyhow!("Serde error: {:?}", e))?; + .map_err(|e| anyhow::anyhow!("Serde error: {e:?}"))?; if value != expected_value { return Err(anyhow::anyhow!( - "Expected message: {}. Received message: {}", - expected_value, - value, + "Expected message: {expected_value}. \ + Received message: {value}", )); } } diff --git a/juniper_codegen/Cargo.toml b/juniper_codegen/Cargo.toml index 79ba4d63..ef78a0a2 100644 --- a/juniper_codegen/Cargo.toml +++ b/juniper_codegen/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_codegen" version = "0.16.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "Code generation for `juniper` crate." license = "BSD-2-Clause" authors = [ diff --git a/juniper_codegen/src/common/default.rs b/juniper_codegen/src/common/default.rs index 2354345a..a2d00f45 100644 --- a/juniper_codegen/src/common/default.rs +++ b/juniper_codegen/src/common/default.rs @@ -15,9 +15,10 @@ use crate::common::parse::ParseBufferExt as _; /// Representation of a [GraphQL default value][0] for code generation. /// /// [0]: https://spec.graphql.org/October2021#DefaultValue -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub(crate) enum Value { /// [`Default`] implementation should be used. + #[default] Default, /// Explicit [`Expr`]ession to be used as the [default value][0]. @@ -27,12 +28,6 @@ pub(crate) enum Value { Expr(Box), } -impl Default for Value { - fn default() -> Self { - Self::Default - } -} - impl From> for Value { fn from(opt: Option) -> Self { match opt { diff --git a/juniper_codegen/src/common/description.rs b/juniper_codegen/src/common/description.rs index 6b9533e6..cd8d739e 100644 --- a/juniper_codegen/src/common/description.rs +++ b/juniper_codegen/src/common/description.rs @@ -150,7 +150,7 @@ mod concatenate_test { /// Forms a [`Vec`] of [`String`]s out of the provided [`str`]s /// [`Iterator`]. fn to_strings<'i>(source: impl IntoIterator) -> Vec { - source.into_iter().map(ToOwned::to_owned).collect() + source.into_iter().map(Into::into).collect() } #[test] diff --git a/juniper_codegen/src/common/diagnostic.rs b/juniper_codegen/src/common/diagnostic.rs index 1d5ebc9c..d99bb504 100644 --- a/juniper_codegen/src/common/diagnostic.rs +++ b/juniper_codegen/src/common/diagnostic.rs @@ -45,22 +45,22 @@ impl fmt::Display for Scope { Self::ScalarValueDerive => "built-in scalars", Self::UnionAttr | Self::UnionDerive => "union", }; - write!(f, "GraphQL {}", name) + write!(f, "GraphQL {name}") } } impl Scope { fn spec_link(&self) -> String { - format!("{}{}", SPEC_URL, self.spec_section()) + format!("{SPEC_URL}{}", self.spec_section()) } pub(crate) fn custom>(&self, span: Span, msg: S) -> Diagnostic { - Diagnostic::spanned(span, Level::Error, format!("{} {}", self, msg.as_ref())) + Diagnostic::spanned(span, Level::Error, format!("{self} {}", msg.as_ref())) .note(self.spec_link()) } pub(crate) fn error(&self, err: syn::Error) -> Diagnostic { - Diagnostic::spanned(err.span(), Level::Error, format!("{} {}", self, err)) + Diagnostic::spanned(err.span(), Level::Error, format!("{self} {err}")) .note(self.spec_link()) } @@ -69,7 +69,7 @@ impl Scope { } pub(crate) fn custom_error>(&self, span: Span, msg: S) -> syn::Error { - syn::Error::new(span, format!("{} {}", self, msg.as_ref())) + syn::Error::new(span, format!("{self} {}", msg.as_ref())) } pub(crate) fn no_double_underscore(&self, field: Span) { @@ -81,7 +81,7 @@ impl Scope { system." .into(), ) - .note(format!("{}#sec-Schema", SPEC_URL)) + .note(format!("{SPEC_URL}#sec-Schema")) .emit(); } } diff --git a/juniper_codegen/src/common/field/arg.rs b/juniper_codegen/src/common/field/arg.rs index 1874c8ae..6de46111 100644 --- a/juniper_codegen/src/common/field/arg.rs +++ b/juniper_codegen/src/common/field/arg.rs @@ -195,10 +195,7 @@ impl Attr { fn err_disallowed(span: &S, arg: &str) -> syn::Error { syn::Error::new( span.span(), - format!( - "attribute argument `#[graphql({} = ...)]` is not allowed here", - arg, - ), + format!("attribute argument `#[graphql({arg} = ...)]` is not allowed here",), ) } } @@ -312,7 +309,7 @@ impl OnMethod { quote! { .arg::<#ty>(#name, info) } }; - Some(quote! { .argument(registry#method#description) }) + Some(quote! { .argument(registry #method #description) }) } /// Returns generated code for the [`GraphQLValue::resolve_field`] method, @@ -329,7 +326,7 @@ impl OnMethod { match self { Self::Regular(arg) => { let (name, ty) = (&arg.name, &arg.ty); - let err_text = format!("Missing argument `{}`: {{}}", &name); + let err_text = format!("Missing argument `{name}`: {{}}"); let arg = quote! { args.get::<#ty>(#name).and_then(|opt| opt.map_or_else(|| { diff --git a/juniper_codegen/src/common/field/mod.rs b/juniper_codegen/src/common/field/mod.rs index 4ed6d79c..8e8cd297 100644 --- a/juniper_codegen/src/common/field/mod.rs +++ b/juniper_codegen/src/common/field/mod.rs @@ -227,7 +227,7 @@ impl Definition { ty_name: &str, ) -> TokenStream { quote! { - return Err(::juniper::FieldError::from(format!( + return Err(::juniper::FieldError::from(::std::format!( "Field `{}` not found on type `{}`", field, >::name(info) @@ -350,7 +350,7 @@ impl Definition { let stream = ::juniper::futures::StreamExt::then(res, move |res| { let executor = executor.clone(); let res2: ::juniper::FieldResult<_, #scalar> = - ::juniper::IntoResolvable::into(res, executor.context()); + ::juniper::IntoResolvable::into_resolvable(res, executor.context()); async move { let ex = executor.as_executor(); match res2 { diff --git a/juniper_codegen/src/common/gen.rs b/juniper_codegen/src/common/gen.rs index eccd52c7..a0b5e731 100644 --- a/juniper_codegen/src/common/gen.rs +++ b/juniper_codegen/src/common/gen.rs @@ -11,7 +11,7 @@ use quote::quote; /// [1]: https://spec.graphql.org/October2021#sec-Types pub(crate) fn sync_resolving_code() -> TokenStream { quote! { - ::juniper::IntoResolvable::into(res, executor.context()) + ::juniper::IntoResolvable::into_resolvable(res, executor.context()) .and_then(|res| match res { Some((ctx, r)) => executor.replaced_context(ctx).resolve_with_ctx(info, &r), None => Ok(::juniper::Value::null()), @@ -35,7 +35,7 @@ pub(crate) fn async_resolving_code(ty: Option<&syn::Type>) -> TokenStream { quote! { Box::pin(::juniper::futures::FutureExt::then(fut, move |res #ty| async move { - match ::juniper::IntoResolvable::into(res, executor.context())? { + match ::juniper::IntoResolvable::into_resolvable(res, executor.context())? { Some((ctx, r)) => { let subexec = executor.replaced_context(ctx); subexec.resolve_with_ctx_async(info, &r).await diff --git a/juniper_codegen/src/common/parse/attr.rs b/juniper_codegen/src/common/parse/attr.rs index 03ba8d73..8b3eceec 100644 --- a/juniper_codegen/src/common/parse/attr.rs +++ b/juniper_codegen/src/common/parse/attr.rs @@ -49,7 +49,7 @@ pub(crate) mod err { pub(crate) fn unknown_arg(span: S, name: &str) -> syn::Error { syn::Error::new( span.as_span(), - format!("unknown `{}` attribute argument", name), + format!("unknown `{name}` attribute argument"), ) } diff --git a/juniper_codegen/src/common/parse/mod.rs b/juniper_codegen/src/common/parse/mod.rs index eaa946d9..53781675 100644 --- a/juniper_codegen/src/common/parse/mod.rs +++ b/juniper_codegen/src/common/parse/mod.rs @@ -4,11 +4,7 @@ pub(crate) mod attr; pub(crate) mod downcaster; -use std::{ - any::TypeId, - iter::{self, FromIterator as _}, - mem, -}; +use std::{any::TypeId, iter, mem}; use proc_macro2::Span; use quote::quote; diff --git a/juniper_codegen/src/common/rename.rs b/juniper_codegen/src/common/rename.rs index 2eda94bc..d7c0cac9 100644 --- a/juniper_codegen/src/common/rename.rs +++ b/juniper_codegen/src/common/rename.rs @@ -1,7 +1,7 @@ //! Common functions, definitions and extensions for parsing and code generation //! of `#[graphql(rename_all = ...)]` attribute. -use std::{convert::TryFrom, str::FromStr}; +use std::str::FromStr; use syn::parse::{Parse, ParseStream}; @@ -25,7 +25,7 @@ impl Policy { /// Applies this [`Policy`] to the given `name`. pub(crate) fn apply(&self, name: &str) -> String { match self { - Self::None => name.to_owned(), + Self::None => name.into(), Self::CamelCase => to_camel_case(name), Self::ScreamingSnakeCase => to_upper_snake_case(name), } diff --git a/juniper_codegen/src/graphql_enum/mod.rs b/juniper_codegen/src/graphql_enum/mod.rs index 949c7b8d..c14356f6 100644 --- a/juniper_codegen/src/graphql_enum/mod.rs +++ b/juniper_codegen/src/graphql_enum/mod.rs @@ -4,8 +4,6 @@ pub(crate) mod derive; -use std::convert::TryInto as _; - use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ @@ -407,13 +405,13 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::IsInputType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::marker::IsInputType<#scalar> + for #ident #ty_generics #where_clause {} #[automatically_derived] - impl#impl_generics ::juniper::marker::IsOutputType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::marker::IsOutputType<#scalar> + for #ident #ty_generics #where_clause {} } } @@ -448,8 +446,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLType<#scalar> + for #ident #ty_generics #where_clause { fn name(_ : &Self::TypeInfo) -> Option<&'static str> { @@ -464,7 +462,7 @@ impl Definition { { let variants = [#( #variants_meta ),*]; - registry.build_enum_type::<#ident#ty_generics>(info, &variants) + registry.build_enum_type::<#ident #ty_generics>(info, &variants) #description .into_meta() } @@ -504,8 +502,8 @@ impl Definition { }); quote! { - impl#impl_generics ::juniper::GraphQLValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLValue<#scalar> + for #ident #ty_generics #where_clause { type Context = #context; @@ -544,8 +542,8 @@ impl Definition { let (_, ty_generics, _) = self.generics.split_for_impl(); quote! { - impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLValueAsync<#scalar> + for #ident #ty_generics #where_clause { fn resolve_async<'__a>( @@ -584,8 +582,8 @@ impl Definition { }); quote! { - impl#impl_generics ::juniper::FromInputValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::FromInputValue<#scalar> + for #ident #ty_generics #where_clause { type Error = ::std::string::String; @@ -631,8 +629,8 @@ impl Definition { }); quote! { - impl#impl_generics ::juniper::ToInputValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::ToInputValue<#scalar> + for #ident #ty_generics #where_clause { fn to_input_value(&self) -> ::juniper::InputValue<#scalar> { @@ -662,23 +660,23 @@ impl Definition { let (_, ty_generics, _) = self.generics.split_for_impl(); quote! { - impl#impl_generics ::juniper::macros::reflect::BaseType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseType<#scalar> + for #ident #ty_generics #where_clause { const NAME: ::juniper::macros::reflect::Type = #name; } - impl#impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> + for #ident #ty_generics #where_clause { const NAMES: ::juniper::macros::reflect::Types = &[>::NAME]; } - impl#impl_generics ::juniper::macros::reflect::WrappedType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::WrappedType<#scalar> + for #ident #ty_generics #where_clause { const VALUE: ::juniper::macros::reflect::WrappedValue = 1; @@ -718,14 +716,14 @@ impl Definition { let mut generics = self.generics.clone(); for lt in generics.lifetimes_mut() { let ident = lt.lifetime.ident.unraw(); - lt.lifetime.ident = format_ident!("__fa__{}", ident); + lt.lifetime.ident = format_ident!("__fa__{ident}"); } let lifetimes = generics.lifetimes().map(|lt| <.lifetime); let ident = &self.ident; let (_, ty_generics, _) = generics.split_for_impl(); - quote! { for<#( #lifetimes ),*> #ident#ty_generics } + quote! { for<#( #lifetimes ),*> #ident #ty_generics } } else { quote! { Self } }; diff --git a/juniper_codegen/src/graphql_input_object/mod.rs b/juniper_codegen/src/graphql_input_object/mod.rs index 6e0f18ae..93c21d6f 100644 --- a/juniper_codegen/src/graphql_input_object/mod.rs +++ b/juniper_codegen/src/graphql_input_object/mod.rs @@ -4,8 +4,6 @@ pub(crate) mod derive; -use std::convert::TryInto as _; - use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; use syn::{ @@ -431,8 +429,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::IsInputType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::marker::IsInputType<#scalar> + for #ident #ty_generics #where_clause { fn mark() { @@ -471,14 +469,14 @@ impl Definition { }; let description = &f.description; - quote! { registry#arg#description } + quote! { registry #arg #description } }) }); quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLType<#scalar> + for #ident #ty_generics #where_clause { fn name(_: &Self::TypeInfo) -> Option<&'static str> { @@ -494,7 +492,7 @@ impl Definition { { let fields = [#( #fields ),*]; registry - .build_input_object_type::<#ident#ty_generics>(info, &fields) + .build_input_object_type::<#ident #ty_generics>(info, &fields) #description .into_meta() } @@ -519,8 +517,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLValue<#scalar> + for #ident #ty_generics #where_clause { type Context = #context; @@ -550,8 +548,8 @@ impl Definition { quote! { #[allow(non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::GraphQLValueAsync<#scalar> + for #ident #ty_generics #where_clause {} } } @@ -610,8 +608,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::FromInputValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::FromInputValue<#scalar> + for #ident #ty_generics #where_clause { type Error = ::juniper::FieldError<#scalar>; @@ -660,8 +658,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::ToInputValue<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::ToInputValue<#scalar> + for #ident #ty_generics #where_clause { fn to_input_value(&self) -> ::juniper::InputValue<#scalar> { @@ -694,23 +692,23 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseType<#scalar> + for #ident #ty_generics #where_clause { const NAME: ::juniper::macros::reflect::Type = #name; } - impl#impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> + for #ident #ty_generics #where_clause { const NAMES: ::juniper::macros::reflect::Types = &[>::NAME]; } - impl#impl_generics ::juniper::macros::reflect::WrappedType<#scalar> - for #ident#ty_generics + impl #impl_generics ::juniper::macros::reflect::WrappedType<#scalar> + for #ident #ty_generics #where_clause { const VALUE: ::juniper::macros::reflect::WrappedValue = 1; @@ -751,14 +749,14 @@ impl Definition { let mut generics = self.generics.clone(); for lt in generics.lifetimes_mut() { let ident = lt.lifetime.ident.unraw(); - lt.lifetime.ident = format_ident!("__fa__{}", ident); + lt.lifetime.ident = format_ident!("__fa__{ident}"); } let lifetimes = generics.lifetimes().map(|lt| <.lifetime); let ident = &self.ident; let (_, ty_generics, _) = generics.split_for_impl(); - quote! { for<#( #lifetimes ),*> #ident#ty_generics } + quote! { for<#( #lifetimes ),*> #ident #ty_generics } } else { quote! { Self } }; diff --git a/juniper_codegen/src/graphql_interface/attr.rs b/juniper_codegen/src/graphql_interface/attr.rs index e1d1f44d..634a1419 100644 --- a/juniper_codegen/src/graphql_interface/attr.rs +++ b/juniper_codegen/src/graphql_interface/attr.rs @@ -132,7 +132,7 @@ fn expand_on_trait( .map(SpanContainer::into_inner) .collect(), suppress_dead_code: None, - src_intra_doc_link: format!("trait@{}", trait_ident).into_boxed_str(), + src_intra_doc_link: format!("trait@{trait_ident}").into_boxed_str(), }; Ok(quote! { @@ -313,7 +313,7 @@ fn expand_on_derive_input( .map(SpanContainer::into_inner) .collect(), suppress_dead_code: None, - src_intra_doc_link: format!("struct@{}", struct_ident).into_boxed_str(), + src_intra_doc_link: format!("struct@{struct_ident}").into_boxed_str(), }; Ok(quote! { diff --git a/juniper_codegen/src/graphql_interface/derive.rs b/juniper_codegen/src/graphql_interface/derive.rs index 09d1851d..25bc096b 100644 --- a/juniper_codegen/src/graphql_interface/derive.rs +++ b/juniper_codegen/src/graphql_interface/derive.rs @@ -105,7 +105,7 @@ pub fn expand(input: TokenStream) -> syn::Result { .map(SpanContainer::into_inner) .collect(), suppress_dead_code: Some((ast.ident.clone(), data.fields.clone())), - src_intra_doc_link: format!("struct@{}", struct_ident).into_boxed_str(), + src_intra_doc_link: format!("struct@{struct_ident}").into_boxed_str(), } .into_token_stream()) } diff --git a/juniper_codegen/src/graphql_interface/mod.rs b/juniper_codegen/src/graphql_interface/mod.rs index 885dc9eb..afb856e1 100644 --- a/juniper_codegen/src/graphql_interface/mod.rs +++ b/juniper_codegen/src/graphql_interface/mod.rs @@ -5,7 +5,7 @@ pub mod attr; pub mod derive; -use std::{collections::HashSet, convert::TryInto as _}; +use std::collections::HashSet; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned, ToTokens}; @@ -39,10 +39,10 @@ fn enum_idents( ) -> (syn::Ident, syn::Ident) { let enum_alias_ident = alias_ident .cloned() - .unwrap_or_else(|| format_ident!("{}Value", trait_ident.to_string())); + .unwrap_or_else(|| format_ident!("{trait_ident}Value")); let enum_ident = alias_ident.map_or_else( - || format_ident!("{}ValueEnum", trait_ident.to_string()), - |c| format_ident!("{}Enum", c.to_string()), + || format_ident!("{trait_ident}ValueEnum"), + |c| format_ident!("{c}Enum"), ); (enum_ident, enum_alias_ident) } @@ -382,7 +382,7 @@ impl Definition { let alias_ident = &self.enum_alias_ident; let variant_gens_pars = (0..self.implemented_for.len()).map::(|id| { - let par = format_ident!("__I{}", id); + let par = format_ident!("__I{id}"); parse_quote! { #par } }); let variants_idents = self @@ -474,8 +474,8 @@ impl Definition { .map(|(ty, ident)| { quote! { #[automatically_derived] - impl#interface_impl_gens ::std::convert::From<#ty> - for #alias_ident#interface_ty_gens + impl #interface_impl_gens ::std::convert::From<#ty> + for #alias_ident #interface_ty_gens #interface_where_clause { fn from(v: #ty) -> Self { @@ -489,14 +489,14 @@ impl Definition { #[automatically_derived] #[derive(Clone, Copy, Debug)] #[doc = #enum_doc] - #vis enum #enum_ident#enum_gens { + #vis enum #enum_ident #enum_gens { #( #[doc(hidden)] #variants_idents(#variant_gens_pars), )* #( #[doc(hidden)] #phantom_variant, )* } #[automatically_derived] #[doc = #enum_alias_doc] - #vis type #alias_ident#enum_alias_gens = + #vis type #alias_ident #enum_alias_gens = #enum_ident<#( #enum_to_alias_gens ),*>; #( #from_impls )* @@ -523,7 +523,7 @@ impl Definition { quote! {{ const SUPPRESS_DEAD_CODE: () = { - let none = Option::<#ident#const_gens>::None; + let none = Option::<#ident #const_gens>::None; match none { Some(unreachable) => { #( let _ = unreachable.#fields; )* @@ -580,8 +580,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::GraphQLInterface<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::marker::GraphQLInterface<#scalar> + for #ty #ty_generics #where_clause { fn mark() { @@ -637,7 +637,7 @@ impl Definition { quote_spanned! { const_impl_for.span() => ::juniper::assert_transitive_impls!( #const_scalar, - #ty#ty_const_generics, + #ty #ty_const_generics, #const_impl_for, #( #const_implements ),* ); @@ -646,8 +646,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::IsOutputType<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::marker::IsOutputType<#scalar> + for #ty #ty_generics #where_clause { fn mark() { @@ -655,12 +655,12 @@ impl Definition { #( #is_output )* ::juniper::assert_interfaces_impls!( #const_scalar, - #ty#ty_const_generics, + #ty #ty_const_generics, #( #const_impl_for ),* ); ::juniper::assert_implemented_for!( #const_scalar, - #ty#ty_const_generics, + #ty #ty_const_generics, #( #const_implements ),* ); #( #transitive_checks )* @@ -711,8 +711,8 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLType<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::GraphQLType<#scalar> + for #ty #ty_generics #where_clause { fn name(_ : &Self::TypeInfo) -> Option<&'static str> { @@ -731,7 +731,7 @@ impl Definition { let fields = [ #( #fields_meta, )* ]; - registry.build_interface_type::<#ty#ty_generics>(info, &fields) + registry.build_interface_type::<#ty #ty_generics>(info, &fields) #description #impl_interfaces .into_meta() @@ -778,7 +778,7 @@ impl Definition { quote! { #[allow(deprecated)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty#ty_generics + impl #impl_generics ::juniper::GraphQLValue<#scalar> for #ty #ty_generics #where_clause { type Context = #context; @@ -856,7 +856,7 @@ impl Definition { quote! { #[allow(deprecated, non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty#ty_generics + impl #impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty #ty_generics #where_clause { fn resolve_field_async<'b>( @@ -908,16 +908,16 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseType<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseType<#scalar> + for #ty #ty_generics #where_clause { const NAME: ::juniper::macros::reflect::Type = #name; } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> + for #ty #ty_generics #where_clause { const NAMES: ::juniper::macros::reflect::Types = &[ @@ -927,8 +927,8 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::Implements<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::macros::reflect::Implements<#scalar> + for #ty #ty_generics #where_clause { const NAMES: ::juniper::macros::reflect::Types = @@ -936,16 +936,16 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::WrappedType<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::macros::reflect::WrappedType<#scalar> + for #ty #ty_generics #where_clause { const VALUE: ::juniper::macros::reflect::WrappedValue = 1; } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::Fields<#scalar> - for #ty#ty_generics + impl #impl_generics ::juniper::macros::reflect::Fields<#scalar> + for #ty #ty_generics #where_clause { const NAMES: ::juniper::macros::reflect::Names = &[#(#fields),*]; @@ -987,10 +987,10 @@ impl Definition { quote! { #[allow(non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::FieldMeta< + impl #impl_generics ::juniper::macros::reflect::FieldMeta< #scalar, { ::juniper::macros::reflect::fnv1a128(#field_name) } - > for #ty#ty_generics #where_clause { + > for #ty #ty_generics #where_clause { type Context = #context; type TypeInfo = (); const TYPE: ::juniper::macros::reflect::Type = @@ -1061,10 +1061,10 @@ impl Definition { quote_spanned! { field.ident.span() => #[allow(non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::Field< + impl #impl_generics ::juniper::macros::reflect::Field< #scalar, { ::juniper::macros::reflect::fnv1a128(#field_name) } - > for #ty#ty_generics #where_clause { + > for #ty #ty_generics #where_clause { fn call( &self, info: &Self::TypeInfo, @@ -1074,7 +1074,7 @@ impl Definition { match self { #( #ty::#implemented_for_idents(v) => { ::juniper::assert_field!( - #ty#const_ty_generics, + #ty #const_ty_generics, #const_implemented_for, #const_scalar, #field_name, @@ -1141,10 +1141,10 @@ impl Definition { quote_spanned! { field.ident.span() => #[allow(non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::AsyncField< + impl #impl_generics ::juniper::macros::reflect::AsyncField< #scalar, { ::juniper::macros::reflect::fnv1a128(#field_name) } - > for #ty#ty_generics #where_clause { + > for #ty #ty_generics #where_clause { fn call<'b>( &'b self, info: &'b Self::TypeInfo, @@ -1154,7 +1154,7 @@ impl Definition { match self { #( #ty::#implemented_for_idents(v) => { ::juniper::assert_field!( - #ty#const_ty_generics, + #ty #const_ty_generics, #const_implemented_for, #const_scalar, #field_name, @@ -1346,14 +1346,14 @@ impl Definition { let mut generics = self.generics.clone(); for lt in generics.lifetimes_mut() { let ident = lt.lifetime.ident.unraw(); - lt.lifetime.ident = format_ident!("__fa__{}", ident); + lt.lifetime.ident = format_ident!("__fa__{ident}"); } let lifetimes = generics.lifetimes().map(|lt| <.lifetime); let ty = &self.enum_alias_ident; let (_, ty_generics, _) = generics.split_for_impl(); - quote! { for<#( #lifetimes ),*> #ty#ty_generics } + quote! { for<#( #lifetimes ),*> #ty #ty_generics } } else { quote! { Self } }; diff --git a/juniper_codegen/src/graphql_object/attr.rs b/juniper_codegen/src/graphql_object/attr.rs index 0c4c7c05..37b47d16 100644 --- a/juniper_codegen/src/graphql_object/attr.rs +++ b/juniper_codegen/src/graphql_object/attr.rs @@ -188,7 +188,7 @@ fn parse_field( } syn::FnArg::Typed(arg) => { if let syn::Pat::Ident(a) = &*arg.pat { - if a.ident.to_string().as_str() == "self" { + if a.ident == "self" { return err_invalid_method_receiver(arg); } } diff --git a/juniper_codegen/src/graphql_object/derive.rs b/juniper_codegen/src/graphql_object/derive.rs index f4e75b4e..189ed261 100644 --- a/juniper_codegen/src/graphql_object/derive.rs +++ b/juniper_codegen/src/graphql_object/derive.rs @@ -34,7 +34,7 @@ fn expand_struct(ast: syn::DeriveInput) -> syn::Result> { let struct_ident = ast.ident; let (_, struct_generics, _) = ast.generics.split_for_impl(); - let ty = parse_quote! { #struct_ident#struct_generics }; + let ty = parse_quote! { #struct_ident #struct_generics }; let name = attr .name diff --git a/juniper_codegen/src/graphql_object/mod.rs b/juniper_codegen/src/graphql_object/mod.rs index df4d3a32..facc7300 100644 --- a/juniper_codegen/src/graphql_object/mod.rs +++ b/juniper_codegen/src/graphql_object/mod.rs @@ -5,7 +5,7 @@ pub mod attr; pub mod derive; -use std::{any::TypeId, collections::HashSet, convert::TryInto as _, marker::PhantomData}; +use std::{any::TypeId, collections::HashSet, marker::PhantomData}; use proc_macro2::TokenStream; use quote::{format_ident, quote, ToTokens}; @@ -299,7 +299,7 @@ impl Definition { let mut ty = self.ty.clone(); ty.lifetimes_iter_mut(&mut |lt| { let ident = lt.ident.unraw(); - lt.ident = format_ident!("__fa__{}", ident); + lt.ident = format_ident!("__fa__{ident}"); lifetimes.push(lt.clone()); }); @@ -346,7 +346,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty #where_clause { fn mark() { #( #fields_marks )* @@ -375,7 +375,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseType<#scalar> + impl #impl_generics ::juniper::macros::reflect::BaseType<#scalar> for #ty #where_clause { @@ -383,7 +383,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> + impl #impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> for #ty #where_clause { @@ -392,7 +392,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::Implements<#scalar> + impl #impl_generics ::juniper::macros::reflect::Implements<#scalar> for #ty #where_clause { @@ -401,7 +401,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::WrappedType<#scalar> + impl #impl_generics ::juniper::macros::reflect::WrappedType<#scalar> for #ty #where_clause { @@ -409,7 +409,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::Fields<#scalar> + impl #impl_generics ::juniper::macros::reflect::Fields<#scalar> for #ty #where_clause { @@ -437,7 +437,7 @@ impl Definition { let fields_meta = self .fields .iter() - .map(|f| f.method_meta_tokens(extract_stream_type.then(|| scalar))); + .map(|f| f.method_meta_tokens(extract_stream_type.then_some(scalar))); // Sorting is required to preserve/guarantee the order of interfaces registered in schema. let mut interface_tys: Vec<_> = self.interfaces.iter().collect(); @@ -455,7 +455,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::GraphQLType<#scalar> for #ty #where_clause { fn name(_ : &Self::TypeInfo) -> Option<&'static str> { Some(#name) @@ -536,7 +536,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::GraphQLObject<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::marker::GraphQLObject<#scalar> for #ty #where_clause { fn mark() { #( <#interface_tys as ::juniper::marker::GraphQLInterface<#scalar>>::mark(); )* @@ -778,7 +778,7 @@ impl Definition { quote! { #[allow(deprecated)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::GraphQLValue<#scalar> for #ty #where_clause { type Context = #context; type TypeInfo = (); @@ -805,7 +805,7 @@ impl Definition { _: &Self::Context, _: &Self::TypeInfo, ) -> String { - #name.to_string() + #name.into() } } } @@ -842,7 +842,7 @@ impl Definition { quote! { #[allow(deprecated, non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty #where_clause { fn resolve_field_async<'b>( &'b self, diff --git a/juniper_codegen/src/graphql_scalar/mod.rs b/juniper_codegen/src/graphql_scalar/mod.rs index d0758e75..2280d9c2 100644 --- a/juniper_codegen/src/graphql_scalar/mod.rs +++ b/juniper_codegen/src/graphql_scalar/mod.rs @@ -119,7 +119,7 @@ impl Parse for Attr { input.parse::()?; let lit = input.parse::()?; let url = lit.value().parse::().map_err(|err| { - syn::Error::new(lit.span(), format!("Invalid URL: {}", err)) + syn::Error::new(lit.span(), format!("Invalid URL: {err}")) })?; out.specified_by_url .replace(SpanContainer::new(ident.span(), Some(lit.span()), url)) @@ -343,11 +343,11 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::marker::IsInputType<#scalar> for #ty + impl #impl_gens ::juniper::marker::IsInputType<#scalar> for #ty #where_clause { } #[automatically_derived] - impl#impl_gens ::juniper::marker::IsOutputType<#scalar> for #ty + impl #impl_gens ::juniper::marker::IsOutputType<#scalar> for #ty #where_clause { } } } @@ -372,7 +372,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::GraphQLType<#scalar> for #ty + impl #impl_gens ::juniper::GraphQLType<#scalar> for #ty #where_clause { fn name(_: &Self::TypeInfo) -> Option<&'static str> { @@ -410,7 +410,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::GraphQLValue<#scalar> for #ty + impl #impl_gens ::juniper::GraphQLValue<#scalar> for #ty #where_clause { type Context = (); @@ -445,7 +445,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::GraphQLValueAsync<#scalar> for #ty + impl #impl_gens ::juniper::GraphQLValueAsync<#scalar> for #ty #where_clause { fn resolve_async<'b>( @@ -477,7 +477,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::ToInputValue<#scalar> for #ty + impl #impl_gens ::juniper::ToInputValue<#scalar> for #ty #where_clause { fn to_input_value(&self) -> ::juniper::InputValue<#scalar> { @@ -502,7 +502,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::FromInputValue<#scalar> for #ty + impl #impl_gens ::juniper::FromInputValue<#scalar> for #ty #where_clause { type Error = ::juniper::executor::FieldError<#scalar>; @@ -530,7 +530,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::ParseScalarValue<#scalar> for #ty + impl #impl_gens ::juniper::ParseScalarValue<#scalar> for #ty #where_clause { fn from_str( @@ -558,14 +558,14 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::macros::reflect::BaseType<#scalar> for #ty + impl #impl_gens ::juniper::macros::reflect::BaseType<#scalar> for #ty #where_clause { const NAME: ::juniper::macros::reflect::Type = #name; } #[automatically_derived] - impl#impl_gens ::juniper::macros::reflect::BaseSubTypes<#scalar> for #ty + impl #impl_gens ::juniper::macros::reflect::BaseSubTypes<#scalar> for #ty #where_clause { const NAMES: ::juniper::macros::reflect::Types = @@ -573,7 +573,7 @@ impl Definition { } #[automatically_derived] - impl#impl_gens ::juniper::macros::reflect::WrappedType<#scalar> for #ty + impl #impl_gens ::juniper::macros::reflect::WrappedType<#scalar> for #ty #where_clause { const VALUE: ::juniper::macros::reflect::WrappedValue = 1; @@ -597,7 +597,7 @@ impl Definition { TypeOrIdent::Type(ty) => ty.into_token_stream(), TypeOrIdent::Ident(ident) => { let (_, ty_gen, _) = self.generics.split_for_impl(); - quote! { #ident#ty_gen } + quote! { #ident #ty_gen } } }; @@ -635,7 +635,7 @@ impl Definition { } TypeOrIdent::Ident(ident) => { let (_, ty_gens, _) = generics.split_for_impl(); - quote! { #ident#ty_gens } + quote! { #ident #ty_gens } } }; diff --git a/juniper_codegen/src/graphql_subscription/mod.rs b/juniper_codegen/src/graphql_subscription/mod.rs index a326e52d..c8d2fb42 100644 --- a/juniper_codegen/src/graphql_subscription/mod.rs +++ b/juniper_codegen/src/graphql_subscription/mod.rs @@ -44,7 +44,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::GraphQLValue<#scalar> for #ty #where_clause { type Context = #context; type TypeInfo = (); @@ -70,7 +70,7 @@ impl Definition { _: &Self::Context, _: &Self::TypeInfo, ) -> String { - #name.to_string() + #name.into() } } } @@ -109,7 +109,7 @@ impl Definition { quote! { #[allow(deprecated)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLSubscriptionValue<#scalar> for #ty #where_clause + impl #impl_generics ::juniper::GraphQLSubscriptionValue<#scalar> for #ty #where_clause { fn resolve_field_into_stream< 's, 'i, 'fi, 'args, 'e, 'ref_e, 'res, 'f, diff --git a/juniper_codegen/src/graphql_union/attr.rs b/juniper_codegen/src/graphql_union/attr.rs index 733cfc99..006ad226 100644 --- a/juniper_codegen/src/graphql_union/attr.rs +++ b/juniper_codegen/src/graphql_union/attr.rs @@ -173,10 +173,9 @@ fn parse_variant_from_trait_method( ERR.custom( method_span, format!( - "trait method `{}` conflicts with the external resolver \ - function `{}` declared on the trait to resolve the \ - variant type `{}`", - method_ident, + "trait method `{method_ident}` conflicts with the external \ + resolver function `{}` declared on the trait to resolve \ + the variant type `{}`", other.to_token_stream(), ty.to_token_stream(), ), diff --git a/juniper_codegen/src/graphql_union/mod.rs b/juniper_codegen/src/graphql_union/mod.rs index e49f0fbf..fa585b00 100644 --- a/juniper_codegen/src/graphql_union/mod.rs +++ b/juniper_codegen/src/graphql_union/mod.rs @@ -336,7 +336,7 @@ impl Definition { let (_, ty_generics, _) = self.generics.split_for_impl(); let ty = &self.ty; - let mut ty_full = quote! { #ty#ty_generics }; + let mut ty_full = quote! { #ty #ty_generics }; if self.is_trait_object { ty_full = quote! { dyn #ty_full + '__obj + Send + Sync }; } @@ -368,14 +368,14 @@ impl Definition { let mut generics = self.generics.clone(); for lt in generics.lifetimes_mut() { let ident = lt.lifetime.ident.unraw(); - lt.lifetime.ident = format_ident!("__fa__{}", ident); + lt.lifetime.ident = format_ident!("__fa__{ident}"); } let lifetimes = generics.lifetimes().map(|lt| <.lifetime); let ty = &self.ty; let (_, ty_generics, _) = generics.split_for_impl(); - quote! { for<#( #lifetimes ),*> #ty#ty_generics } + quote! { for<#( #lifetimes ),*> #ty #ty_generics } } else { quote! { Self } }; @@ -418,7 +418,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::GraphQLUnion<#scalar> for #ty_full #where_clause + impl #impl_generics ::juniper::marker::GraphQLUnion<#scalar> for #ty_full #where_clause { fn mark() { #all_variants_unique @@ -443,7 +443,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty_full #where_clause + impl #impl_generics ::juniper::marker::IsOutputType<#scalar> for #ty_full #where_clause { fn mark() { #( <#variant_tys as ::juniper::marker::IsOutputType<#scalar>>::mark(); )* @@ -470,7 +470,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLType<#scalar> for #ty_full #where_clause + impl #impl_generics ::juniper::GraphQLType<#scalar> for #ty_full #where_clause { fn name(_ : &Self::TypeInfo) -> Option<&'static str> { Some(#name) @@ -519,7 +519,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValue<#scalar> for #ty_full #where_clause + impl #impl_generics ::juniper::GraphQLValue<#scalar> for #ty_full #where_clause { type Context = #context; type TypeInfo = (); @@ -534,7 +534,7 @@ impl Definition { info: &Self::TypeInfo, ) -> String { #( #match_variant_names )* - panic!( + ::std::panic!( "GraphQL union `{}` cannot be resolved into any of its \ variants in its current state", #name, @@ -550,7 +550,7 @@ impl Definition { ) -> ::juniper::ExecutionResult<#scalar> { let context = executor.context(); #( #variant_resolvers )* - return Err(::juniper::FieldError::from(format!( + return Err(::juniper::FieldError::from(::std::format!( "Concrete type `{}` is not handled by instance \ resolvers on GraphQL union `{}`", type_name, #name, @@ -581,7 +581,7 @@ impl Definition { quote! { #[allow(non_snake_case)] #[automatically_derived] - impl#impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty_full #where_clause + impl #impl_generics ::juniper::GraphQLValueAsync<#scalar> for #ty_full #where_clause { fn resolve_into_type_async<'b>( &'b self, @@ -592,7 +592,7 @@ impl Definition { ) -> ::juniper::BoxFuture<'b, ::juniper::ExecutionResult<#scalar>> { let context = executor.context(); #( #variant_async_resolvers )* - return ::juniper::macros::helper::err_fut(format!( + return ::juniper::macros::helper::err_fut(::std::format!( "Concrete type `{}` is not handled by instance \ resolvers on GraphQL union `{}`", type_name, #name, @@ -618,7 +618,7 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseType<#scalar> + impl #impl_generics ::juniper::macros::reflect::BaseType<#scalar> for #ty #where_clause { @@ -626,7 +626,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> + impl #impl_generics ::juniper::macros::reflect::BaseSubTypes<#scalar> for #ty #where_clause { @@ -637,7 +637,7 @@ impl Definition { } #[automatically_derived] - impl#impl_generics ::juniper::macros::reflect::WrappedType<#scalar> + impl #impl_generics ::juniper::macros::reflect::WrappedType<#scalar> for #ty #where_clause { diff --git a/juniper_codegen/src/lib.rs b/juniper_codegen/src/lib.rs index d77a21b5..d88488c3 100644 --- a/juniper_codegen/src/lib.rs +++ b/juniper_codegen/src/lib.rs @@ -440,18 +440,17 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// ) -> Result { /// // ^^^^^^ must implement `IntoFieldError` /// input.as_string_value() -/// .ok_or_else(|| format!("Expected `String`, found: {}", input)) +/// .ok_or_else(|| format!("Expected `String`, found: {input}")) /// .and_then(|str| { /// str.strip_prefix("id: ") /// .ok_or_else(|| { /// format!( /// "Expected `UserId` to begin with `id: `, \ -/// found: {}", -/// input, +/// found: {input}", /// ) /// }) /// }) -/// .map(|id| Self(id.to_owned())) +/// .map(|id| Self(id.into())) /// } /// } /// ``` @@ -483,16 +482,16 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// /// fn to_output(v: &StringOrInt) -> Value { /// match v { -/// StringOrInt::String(str) => Value::scalar(str.to_owned()), +/// StringOrInt::String(s) => Value::scalar(s.to_owned()), /// StringOrInt::Int(i) => Value::scalar(*i), /// } /// } /// /// fn from_input(v: &InputValue) -> Result { /// v.as_string_value() -/// .map(|s| StringOrInt::String(s.to_owned())) +/// .map(|s| StringOrInt::String(s.into())) /// .or_else(|| v.as_int_value().map(StringOrInt::Int)) -/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) +/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) /// } /// /// fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -526,16 +525,16 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// /// pub(super) fn to_output(v: &StringOrInt) -> Value { /// match v { -/// StringOrInt::String(str) => Value::scalar(str.to_owned()), +/// StringOrInt::String(s) => Value::scalar(s.to_owned()), /// StringOrInt::Int(i) => Value::scalar(*i), /// } /// } /// /// pub(super) fn from_input(v: &InputValue) -> Result { /// v.as_string_value() -/// .map(|s| StringOrInt::String(s.to_owned())) +/// .map(|s| StringOrInt::String(s.into())) /// .or_else(|| v.as_int_value().map(StringOrInt::Int)) -/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) +/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) /// } /// /// pub(super) fn parse_token(t: ScalarToken<'_>) -> ParseScalarResult { @@ -564,7 +563,7 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// impl StringOrInt { /// fn to_output(&self) -> Value { /// match self { -/// Self::String(str) => Value::scalar(str.to_owned()), +/// Self::String(s) => Value::scalar(s.to_owned()), /// Self::Int(i) => Value::scalar(*i), /// } /// } @@ -574,9 +573,9 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// S: ScalarValue /// { /// v.as_string_value() -/// .map(|s| Self::String(s.to_owned())) +/// .map(|s| Self::String(s.into())) /// .or_else(|| v.as_int_value().map(Self::Int)) -/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) +/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) /// } /// /// fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult @@ -616,7 +615,7 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// S: ScalarValue, /// { /// match v { -/// StringOrInt::String(str) => Value::scalar(str.to_owned()), +/// StringOrInt::String(s) => Value::scalar(s.to_owned()), /// StringOrInt::Int(i) => Value::scalar(*i), /// } /// } @@ -626,9 +625,9 @@ pub fn derive_enum(input: TokenStream) -> TokenStream { /// S: ScalarValue, /// { /// v.as_string_value() -/// .map(|s| StringOrInt::String(s.to_owned())) +/// .map(|s| StringOrInt::String(s.into())) /// .or_else(|| v.as_int_value().map(StringOrInt::Int)) -/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) +/// .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) /// } /// /// // No need in `parse_token()` function. @@ -736,8 +735,8 @@ pub fn derive_scalar(input: TokenStream) -> TokenStream { /// /// pub(super) fn from_input(v: &InputValue) -> Result { /// v.as_string_value() -/// .ok_or_else(|| format!("Expected `String`, found: {}", v)) -/// .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {}", e))) +/// .ok_or_else(|| format!("Expected `String`, found: {v}")) +/// .and_then(|s| s.parse().map_err(|e| format!("Failed to parse `Date`: {e}"))) /// } /// } /// # @@ -766,7 +765,7 @@ pub fn graphql_scalar(attr: TokenStream, body: TokenStream) -> TokenStream { /// methods). /// /// ```rust -/// # use std::{fmt, convert::TryInto as _}; +/// # use std::fmt; /// # /// # use serde::{de, Deserialize, Deserializer, Serialize}; /// # use juniper::ScalarValue; @@ -1129,7 +1128,7 @@ pub fn derive_scalar_value(input: TokenStream) -> TokenStream { /// // You can return `&str` even if trait definition returns `String`. /// fn detailed_info(&self, info_kind: String) -> &str { /// (info_kind == "planet") -/// .then(|| &self.home_planet) +/// .then_some(&self.home_planet) /// .unwrap_or(&self.id) /// } /// } diff --git a/juniper_codegen/src/scalar_value/mod.rs b/juniper_codegen/src/scalar_value/mod.rs index fe9aa6de..e0a0d78b 100644 --- a/juniper_codegen/src/scalar_value/mod.rs +++ b/juniper_codegen/src/scalar_value/mod.rs @@ -1,6 +1,6 @@ //! Code generation for `#[derive(ScalarValue)]` macro. -use std::{collections::HashMap, convert::TryFrom}; +use std::collections::HashMap; use proc_macro2::{Literal, TokenStream}; use quote::{quote, ToTokens, TokenStreamExt as _}; @@ -55,11 +55,11 @@ pub fn expand_derive(input: TokenStream) -> syn::Result { (Method::AsBool, "as_bool"), ] .iter() - .filter_map(|(method, err)| (!methods.contains_key(method)).then(|| err)) + .filter_map(|(method, err)| (!methods.contains_key(method)).then_some(err)) .fold(None, |acc, &method| { Some( - acc.map(|acc| format!("{}, {}", acc, method)) - .unwrap_or_else(|| method.to_owned()), + acc.map(|acc| format!("{acc}, {method}")) + .unwrap_or_else(|| method.into()), ) }) .filter(|_| !attr.allow_missing_attrs); @@ -67,10 +67,9 @@ pub fn expand_derive(input: TokenStream) -> syn::Result { return Err(ERR.custom_error( span, format!( - "missing `#[value({})]` attributes. In case you are sure \ - that it's ok, use `#[value(allow_missing_attributes)]` to \ - suppress this error.", - missing_methods, + "missing `#[value({missing_methods})]` attributes. In case you \ + are sure that it's ok, use `#[value(allow_missing_attributes)]` \ + to suppress this error.", ), )); } @@ -298,10 +297,10 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gens ::juniper::ScalarValue for #ident#ty_gens + impl #impl_gens ::juniper::ScalarValue for #ident #ty_gens #where_clause { - #(#methods)* + #( #methods )* } } } @@ -333,20 +332,20 @@ impl Definition { quote! { #[automatically_derived] - impl#impl_gen ::std::convert::From<#var_ty> for #ty_ident#ty_gen + impl #impl_gen ::std::convert::From<#var_ty> for #ty_ident #ty_gen #where_clause { fn from(v: #var_ty) -> Self { - Self::#var_ident#var_field + Self::#var_ident #var_field } } #[automatically_derived] - impl#impl_gen ::std::convert::From<#ty_ident#ty_gen> for Option<#var_ty> + impl #impl_gen ::std::convert::From<#ty_ident #ty_gen> for Option<#var_ty> #where_clause { - fn from(ty: #ty_ident#ty_gen) -> Self { - if let #ty_ident::#var_ident#var_field = ty { + fn from(ty: #ty_ident #ty_gen) -> Self { + if let #ty_ident::#var_ident #var_field = ty { Some(v) } else { None @@ -355,12 +354,12 @@ impl Definition { } #[automatically_derived] - impl#lf_impl_gen ::std::convert::From<&'___a #ty_ident#ty_gen> for + impl #lf_impl_gen ::std::convert::From<&'___a #ty_ident #ty_gen> for Option<&'___a #var_ty> #where_clause { - fn from(ty: &'___a #ty_ident#ty_gen) -> Self { - if let #ty_ident::#var_ident#var_field = ty { + fn from(ty: &'___a #ty_ident #ty_gen) -> Self { + if let #ty_ident::#var_ident #var_field = ty { Some(v) } else { None @@ -404,17 +403,17 @@ impl Definition { .as_ref() .map_or_else(|| quote! { (v) }, |i| quote! { { #i: v } }); - quote! { Self::#var_ident#var_field => ::std::fmt::Display::fmt(v, f), } + quote! { Self::#var_ident #var_field => ::std::fmt::Display::fmt(v, f), } }); quote! { #[automatically_derived] - impl#impl_gen ::std::fmt::Display for #ident#ty_gen + impl #impl_gen ::std::fmt::Display for #ident #ty_gen #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { - #(#arms)* + #( #arms )* } } } @@ -440,7 +439,7 @@ impl Variant { fn match_arm(&self) -> TokenStream { let (ident, field) = (&self.ident, &self.field.match_arg()); quote! { - Self::#ident#field + Self::#ident #field } } } diff --git a/juniper_graphql_ws/Cargo.toml b/juniper_graphql_ws/Cargo.toml index 3b74f4bb..c8b68806 100644 --- a/juniper_graphql_ws/Cargo.toml +++ b/juniper_graphql_ws/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_graphql_ws" version = "0.4.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "GraphQL over WebSocket Protocol implementation for `juniper` crate." license = "BSD-2-Clause" authors = ["Christopher Brown "] diff --git a/juniper_graphql_ws/src/client_message.rs b/juniper_graphql_ws/src/client_message.rs index c893f6da..767f6969 100644 --- a/juniper_graphql_ws/src/client_message.rs +++ b/juniper_graphql_ws/src/client_message.rs @@ -78,11 +78,11 @@ mod test { assert_eq!( ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "query MyQuery { __typename }".to_string(), + query: "query MyQuery { __typename }".into(), variables: graphql_vars! {"foo": "bar"}, - operation_name: Some("MyQuery".to_string()), + operation_name: Some("MyQuery".into()), }, }, serde_json::from_str( @@ -99,9 +99,9 @@ mod test { assert_eq!( ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "query MyQuery { __typename }".to_string(), + query: "query MyQuery { __typename }".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -115,9 +115,7 @@ mod test { ); assert_eq!( - ClientMessage::Stop { - id: "foo".to_string() - }, + ClientMessage::Stop { id: "foo".into() }, serde_json::from_str(r##"{"type": "stop", "id": "foo"}"##).unwrap(), ); diff --git a/juniper_graphql_ws/src/lib.rs b/juniper_graphql_ws/src/lib.rs index e809c009..d1621a61 100644 --- a/juniper_graphql_ws/src/lib.rs +++ b/juniper_graphql_ws/src/lib.rs @@ -14,13 +14,8 @@ pub use schema::*; mod utils; use std::{ - collections::HashMap, - convert::{Infallible, TryInto}, - error::Error, - marker::PhantomPinned, - pin::Pin, - sync::Arc, - time::Duration, + collections::HashMap, convert::Infallible, error::Error, marker::PhantomPinned, pin::Pin, + sync::Arc, time::Duration, }; use juniper::{ @@ -292,9 +287,10 @@ impl> ConnectionState { } async fn start(id: String, params: ExecutionParams) -> BoxStream<'static, Reaction> { - // TODO: This could be made more efficient if juniper exposed functionality to allow us to - // parse and validate the query, determine whether it's a subscription, and then execute - // it. For now, the query gets parsed and validated twice. + // TODO: This could be made more efficient if `juniper` exposed + // functionality to allow us to parse and validate the query, + // determine whether it's a subscription, and then execute it. + // For now, the query gets parsed and validated twice. let params = Arc::new(params); @@ -707,9 +703,9 @@ mod test { assert_eq!(ServerMessage::ConnectionAck, conn.next().await.unwrap()); conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "{context}".to_string(), + query: "{context}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -719,7 +715,7 @@ mod test { assert_eq!( ServerMessage::Data { - id: "foo".to_string(), + id: "foo".into(), payload: DataPayload { data: graphql_value!({"context": 1}), errors: vec![], @@ -729,9 +725,7 @@ mod test { ); assert_eq!( - ServerMessage::Complete { - id: "foo".to_string(), - }, + ServerMessage::Complete { id: "foo".into() }, conn.next().await.unwrap() ); } @@ -752,9 +746,9 @@ mod test { assert_eq!(ServerMessage::ConnectionAck, conn.next().await.unwrap()); conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "subscription Foo {context}".to_string(), + query: "subscription Foo {context}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -764,7 +758,7 @@ mod test { assert_eq!( ServerMessage::Data { - id: "foo".to_string(), + id: "foo".into(), payload: DataPayload { data: graphql_value!({"context": 1}), errors: vec![], @@ -774,9 +768,9 @@ mod test { ); conn.send(ClientMessage::Start { - id: "bar".to_string(), + id: "bar".into(), payload: StartPayload { - query: "subscription Bar {context}".to_string(), + query: "subscription Bar {context}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -786,7 +780,7 @@ mod test { assert_eq!( ServerMessage::Data { - id: "bar".to_string(), + id: "bar".into(), payload: DataPayload { data: graphql_value!({"context": 1}), errors: vec![], @@ -795,16 +789,12 @@ mod test { conn.next().await.unwrap() ); - conn.send(ClientMessage::Stop { - id: "foo".to_string(), - }) - .await - .unwrap(); + conn.send(ClientMessage::Stop { id: "foo".into() }) + .await + .unwrap(); assert_eq!( - ServerMessage::Complete { - id: "foo".to_string(), - }, + ServerMessage::Complete { id: "foo".into() }, conn.next().await.unwrap() ); } @@ -841,7 +831,7 @@ mod test { assert_eq!( ServerMessage::ConnectionError { payload: ConnectionErrorPayload { - message: "init error".to_string(), + message: "init error".into(), }, }, conn.next().await.unwrap() @@ -866,9 +856,9 @@ mod test { assert_eq!(ServerMessage::ConnectionAck, conn.next().await.unwrap()); conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "subscription Foo {never}".to_string(), + query: "subscription Foo {never}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -877,9 +867,9 @@ mod test { .unwrap(); conn.send(ClientMessage::Start { - id: "bar".to_string(), + id: "bar".into(), payload: StartPayload { - query: "subscription Bar {never}".to_string(), + query: "subscription Bar {never}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -891,7 +881,7 @@ mod test { ServerMessage::Error { id, .. } => { assert_eq!(id, "bar"); } - msg @ _ => panic!("expected error, got: {:?}", msg), + msg @ _ => panic!("expected error, got: {msg:?}"), } } @@ -911,9 +901,9 @@ mod test { assert_eq!(ServerMessage::ConnectionAck, conn.next().await.unwrap()); conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "asd".to_string(), + query: "asd".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -929,10 +919,10 @@ mod test { item: ParseError::UnexpectedToken(token), .. }) => assert_eq!(token, "asd"), - p @ _ => panic!("expected graphql parse error, got: {:?}", p), + p @ _ => panic!("expected graphql parse error, got: {p:?}"), } } - msg @ _ => panic!("expected error, got: {:?}", msg), + msg @ _ => panic!("expected error, got: {msg:?}"), } } @@ -974,9 +964,9 @@ mod test { // If we send the start message before the init is handled, we should still get results. conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "{context}".to_string(), + query: "{context}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -988,7 +978,7 @@ mod test { assert_eq!( ServerMessage::Data { - id: "foo".to_string(), + id: "foo".into(), payload: DataPayload { data: graphql_value!({"context": 1}), errors: vec![], @@ -1014,9 +1004,9 @@ mod test { assert_eq!(ServerMessage::ConnectionAck, conn.next().await.unwrap()); conn.send(ClientMessage::Start { - id: "foo".to_string(), + id: "foo".into(), payload: StartPayload { - query: "subscription Foo {error}".to_string(), + query: "subscription Foo {error}".into(), variables: graphql_vars! {}, operation_name: None, }, @@ -1033,7 +1023,7 @@ mod test { assert_eq!(data, graphql_value!({ "error": null })); assert_eq!(errors.len(), 1); } - msg @ _ => panic!("expected data, got: {:?}", msg), + msg @ _ => panic!("expected data, got: {msg:?}"), } } } diff --git a/juniper_graphql_ws/src/server_message.rs b/juniper_graphql_ws/src/server_message.rs index aedc4620..232ef038 100644 --- a/juniper_graphql_ws/src/server_message.rs +++ b/juniper_graphql_ws/src/server_message.rs @@ -143,7 +143,7 @@ mod test { assert_eq!( serde_json::to_string(&ServerMessage::ConnectionError { payload: ConnectionErrorPayload { - message: "foo".to_string(), + message: "foo".into(), }, }) .unwrap(), @@ -157,7 +157,7 @@ mod test { assert_eq!( serde_json::to_string(&ServerMessage::Data { - id: "foo".to_string(), + id: "foo".into(), payload: DataPayload { data: graphql_value!(null), errors: vec![], @@ -169,7 +169,7 @@ mod test { assert_eq!( serde_json::to_string(&ServerMessage::Error { - id: "foo".to_string(), + id: "foo".into(), payload: GraphQLError::UnknownOperationName.into(), }) .unwrap(), @@ -177,10 +177,7 @@ mod test { ); assert_eq!( - serde_json::to_string(&ServerMessage::Complete { - id: "foo".to_string(), - }) - .unwrap(), + serde_json::to_string(&ServerMessage::Complete { id: "foo".into() }).unwrap(), r##"{"type":"complete","id":"foo"}"##, ); diff --git a/juniper_hyper/Cargo.toml b/juniper_hyper/Cargo.toml index 72ab1f4f..0f2f6bb2 100644 --- a/juniper_hyper/Cargo.toml +++ b/juniper_hyper/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_hyper" version = "0.9.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "`juniper` GraphQL integration with `hyper`." license = "BSD-2-Clause" authors = ["Damir Vandic "] diff --git a/juniper_hyper/examples/hyper_server.rs b/juniper_hyper/examples/hyper_server.rs index 3187451e..afa1d4e0 100644 --- a/juniper_hyper/examples/hyper_server.rs +++ b/juniper_hyper/examples/hyper_server.rs @@ -49,9 +49,9 @@ async fn main() { }); let server = Server::bind(&addr).serve(new_service); - println!("Listening on http://{}", addr); + println!("Listening on http://{addr}"); if let Err(e) = server.await { - eprintln!("server error: {}", e) + eprintln!("server error: {e}") } } diff --git a/juniper_hyper/src/lib.rs b/juniper_hyper/src/lib.rs index ce9204eb..eb8dafe3 100644 --- a/juniper_hyper/src/lib.rs +++ b/juniper_hyper/src/lib.rs @@ -84,7 +84,7 @@ fn parse_get_req( .map(|q| gql_request_from_get(q).map(GraphQLBatchRequest::Single)) .unwrap_or_else(|| { Err(GraphQLRequestError::Invalid( - "'query' parameter is missing".to_string(), + "'query' parameter is missing".into(), )) }) } @@ -144,7 +144,7 @@ pub async fn playground( } fn render_error(err: GraphQLRequestError) -> Response { - let message = format!("{}", err); + let message = err.to_string(); let mut resp = new_response(StatusCode::BAD_REQUEST); *resp.body_mut() = Body::from(message); resp @@ -249,15 +249,14 @@ where match query { Some(query) => Ok(JuniperGraphQLRequest::new(query, operation_name, variables)), None => Err(GraphQLRequestError::Invalid( - "'query' parameter is missing".to_string(), + "'query' parameter is missing".into(), )), } } fn invalid_err(parameter_name: &str) -> GraphQLRequestError { GraphQLRequestError::Invalid(format!( - "'{}' parameter is specified multiple times", - parameter_name + "`{parameter_name}` parameter is specified multiple times", )) } @@ -330,31 +329,31 @@ mod tests { impl http_tests::HttpIntegration for TestHyperIntegration { fn get(&self, url: &str) -> http_tests::TestResponse { - let url = format!("http://127.0.0.1:{}/graphql{}", self.port, url); - make_test_response(reqwest::blocking::get(&url).expect(&format!("failed GET {}", url))) + let url = format!("http://127.0.0.1:{}/graphql{url}", self.port); + make_test_response(reqwest::blocking::get(&url).expect(&format!("failed GET {url}"))) } fn post_json(&self, url: &str, body: &str) -> http_tests::TestResponse { - let url = format!("http://127.0.0.1:{}/graphql{}", self.port, url); + let url = format!("http://127.0.0.1:{}/graphql{url}", self.port); let client = reqwest::blocking::Client::new(); let res = client .post(&url) .header(reqwest::header::CONTENT_TYPE, "application/json") - .body(body.to_string()) + .body(body.to_owned()) .send() - .expect(&format!("failed POST {}", url)); + .expect(&format!("failed POST {url}")); make_test_response(res) } fn post_graphql(&self, url: &str, body: &str) -> http_tests::TestResponse { - let url = format!("http://127.0.0.1:{}/graphql{}", self.port, url); + let url = format!("http://127.0.0.1:{}/graphql{url}", self.port); let client = reqwest::blocking::Client::new(); let res = client .post(&url) .header(reqwest::header::CONTENT_TYPE, "application/graphql") - .body(body.to_string()) + .body(body.to_owned()) .send() - .expect(&format!("failed POST {}", url)); + .expect(&format!("failed POST {url}")); make_test_response(res) } } @@ -362,11 +361,9 @@ mod tests { fn make_test_response(response: ReqwestResponse) -> http_tests::TestResponse { let status_code = response.status().as_u16() as i32; let content_type_header = response.headers().get(reqwest::header::CONTENT_TYPE); - let content_type = if let Some(ct) = content_type_header { - format!("{}", ct.to_str().unwrap()) - } else { - String::default() - }; + let content_type = content_type_header + .map(|ct| ct.to_str().unwrap().into()) + .unwrap_or_default(); let body = response.text().unwrap(); http_tests::TestResponse { @@ -439,7 +436,7 @@ mod tests { }); if let Err(e) = server.await { - eprintln!("server error: {}", e); + eprintln!("server error: {e}"); } } diff --git a/juniper_iron/Cargo.toml b/juniper_iron/Cargo.toml index d4b4b759..82c18f9c 100644 --- a/juniper_iron/Cargo.toml +++ b/juniper_iron/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_iron" version = "0.8.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "`juniper` GraphQL integration with `iron`." license = "BSD-2-Clause" authors = [ diff --git a/juniper_iron/examples/iron_server.rs b/juniper_iron/examples/iron_server.rs index d243b221..218af60b 100644 --- a/juniper_iron/examples/iron_server.rs +++ b/juniper_iron/examples/iron_server.rs @@ -33,7 +33,7 @@ fn main() { chain.link_before(logger_before); chain.link_after(logger_after); - let host = env::var("LISTEN").unwrap_or_else(|_| "0.0.0.0:8080".to_owned()); - println!("GraphQL server started on {}", host); + let host = env::var("LISTEN").unwrap_or_else(|_| "0.0.0.0:8080".into()); + println!("GraphQL server started on {host}"); Iron::new(chain).http(host.as_str()).unwrap(); } diff --git a/juniper_iron/src/lib.rs b/juniper_iron/src/lib.rs index 62764227..b8829614 100644 --- a/juniper_iron/src/lib.rs +++ b/juniper_iron/src/lib.rs @@ -175,8 +175,8 @@ impl GraphiQLHandler { /// relative, so a common value could be `"/graphql"`. pub fn new(graphql_url: &str, subscription_url: Option<&str>) -> GraphiQLHandler { GraphiQLHandler { - graphql_url: graphql_url.to_owned(), - subscription_url: subscription_url.map(|s| s.to_owned()), + graphql_url: graphql_url.into(), + subscription_url: subscription_url.map(Into::into), } } } @@ -188,8 +188,8 @@ impl PlaygroundHandler { /// relative, so a common value could be `"/graphql"`. pub fn new(graphql_url: &str, subscription_url: Option<&str>) -> PlaygroundHandler { PlaygroundHandler { - graphql_url: graphql_url.to_owned(), - subscription_url: subscription_url.map(|s| s.to_owned()), + graphql_url: graphql_url.into(), + subscription_url: subscription_url.map(Into::into), } } } @@ -283,7 +283,7 @@ impl Error for GraphQLIronError { impl From for IronError { fn from(err: GraphQLIronError) -> IronError { - let message = format!("{}", err); + let message = err.to_string(); IronError::new(err, (status::BadRequest, message)) } } @@ -313,17 +313,16 @@ mod tests { // This is ugly but it works. `iron_test` just dumps the path/url in headers // and newer `hyper` doesn't allow unescaped "{" or "}". fn fixup_url(url: &str) -> String { - let url = Url::parse(&format!("http://localhost:3000{}", url)).expect("url to parse"); + let url = Url::parse(&format!("http://localhost:3000{url}")).expect("url to parse"); let path: String = url .path() .iter() - .map(|x| (*x).to_string()) + .map(|x| x.to_string()) .collect::>() .join("/"); format!( - "http://localhost:3000{}?{}", - path, - utf8_percent_encode(url.query().unwrap_or(""), QUERY_ENCODE_SET) + "http://localhost:3000{path}?{}", + utf8_percent_encode(url.query().unwrap_or(""), QUERY_ENCODE_SET), ) } @@ -374,7 +373,7 @@ mod tests { http_tests::TestResponse { status_code: 400, body: None, - content_type: "application/json".to_string(), + content_type: "application/json".into(), } } diff --git a/juniper_rocket/Cargo.toml b/juniper_rocket/Cargo.toml index e3ff1bec..dc275ee3 100644 --- a/juniper_rocket/Cargo.toml +++ b/juniper_rocket/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_rocket" version = "0.9.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "`juniper` GraphQL integration with `rocket`." license = "BSD-2-Clause" authors = [ diff --git a/juniper_rocket/src/lib.rs b/juniper_rocket/src/lib.rs index e6e60bee..fea4e27e 100644 --- a/juniper_rocket/src/lib.rs +++ b/juniper_rocket/src/lib.rs @@ -242,9 +242,9 @@ where fn push_value(ctx: &mut Self::Context, field: ValueField<'f>) { match field.name.key().map(|key| key.as_str()) { - Some("query") => ctx.query(field.value.to_owned()), - Some("operation_name") => ctx.operation_name(field.value.to_owned()), - Some("variables") => ctx.variables(field.value.to_owned()), + Some("query") => ctx.query(field.value.into()), + Some("operation_name") => ctx.operation_name(field.value.into()), + Some("variables") => ctx.variables(field.value.into()), Some(key) => { if ctx.opts.strict { let error = Error::from(ErrorKind::Unknown).with_name(key); @@ -318,13 +318,13 @@ where let mut reader = data.open(limit); let mut body = String::new(); if let Err(e) = reader.read_to_string(&mut body).await { - return Failure((Status::InternalServerError, format!("{:?}", e))); + return Failure((Status::InternalServerError, format!("{e:?}"))); } Success(GraphQLRequest(if is_json { match serde_json::from_str(&body) { Ok(req) => req, - Err(e) => return Failure((Status::BadRequest, format!("{}", e))), + Err(e) => return Failure((Status::BadRequest, e.to_string())), } } else { GraphQLBatchRequest::Single(http::GraphQLRequest::new(body, None, None)) @@ -437,7 +437,7 @@ mod fromform_tests { check_error( "query=test&variables=NOT_JSON", vec![Error::from(ErrorKind::Validation(Cow::Owned( - "expected value at line 1 column 1".to_owned(), + "expected value at line 1 column 1".into(), ))) .with_name("variables")], false, @@ -451,7 +451,7 @@ mod fromform_tests { assert!(result.is_ok()); let variables = ::serde_json::from_str::(r#"{"foo":"bar"}"#).unwrap(); let expected = GraphQLRequest(GraphQLBatchRequest::Single(http::GraphQLRequest::new( - "test".to_string(), + "test".into(), None, Some(variables), ))); @@ -465,7 +465,7 @@ mod fromform_tests { )); let variables = ::serde_json::from_str::(r#"{"foo":"x y&? z"}"#).unwrap(); let expected = GraphQLRequest(GraphQLBatchRequest::Single(http::GraphQLRequest::new( - "test".to_string(), + "test".into(), None, Some(variables), ))); @@ -479,8 +479,8 @@ mod fromform_tests { )); assert!(result.is_ok()); let expected = GraphQLRequest(GraphQLBatchRequest::Single(http::GraphQLRequest::new( - "%foo bar baz&?".to_string(), - Some("test".to_string()), + "%foo bar baz&?".into(), + Some("test".into()), None, ))); assert_eq!(result.unwrap(), expected); diff --git a/juniper_rocket/tests/custom_response_tests.rs b/juniper_rocket/tests/custom_response_tests.rs index 050be566..72893703 100644 --- a/juniper_rocket/tests/custom_response_tests.rs +++ b/juniper_rocket/tests/custom_response_tests.rs @@ -3,5 +3,5 @@ use rocket::http::Status; #[test] fn test_graphql_response_is_public() { - let _ = GraphQLResponse(Status::Unauthorized, "Unauthorized".to_string()); + let _ = GraphQLResponse(Status::Unauthorized, "Unauthorized".into()); } diff --git a/juniper_subscriptions/Cargo.toml b/juniper_subscriptions/Cargo.toml index ddea6d98..8ccf40e5 100644 --- a/juniper_subscriptions/Cargo.toml +++ b/juniper_subscriptions/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_subscriptions" version = "0.17.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "Juniper `SubscriptionCoordinator` and `SubscriptionConnection` implementations." license = "BSD-2-Clause" authors = ["nWacky "] diff --git a/juniper_subscriptions/src/lib.rs b/juniper_subscriptions/src/lib.rs index 6926066d..3d5d77bb 100644 --- a/juniper_subscriptions/src/lib.rs +++ b/juniper_subscriptions/src/lib.rs @@ -3,7 +3,6 @@ #![deny(warnings)] use std::{ - iter::FromIterator, pin::Pin, task::{self, Poll}, }; diff --git a/juniper_warp/Cargo.toml b/juniper_warp/Cargo.toml index b49e379d..bb704a20 100644 --- a/juniper_warp/Cargo.toml +++ b/juniper_warp/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "juniper_warp" version = "0.8.0-dev" -edition = "2018" +edition = "2021" +rust-version = "1.62" description = "`juniper` GraphQL integration with `warp`." license = "BSD-2-Clause" authors = ["Tom Houlé "] diff --git a/juniper_warp/src/lib.rs b/juniper_warp/src/lib.rs index e7686b8d..b30b007b 100644 --- a/juniper_warp/src/lib.rs +++ b/juniper_warp/src/lib.rs @@ -44,7 +44,7 @@ use warp::{body, filters::BoxedFilter, http, hyper::body::Bytes, query, Filter}; /// format!( /// "good morning {}, the app state is {:?}", /// context.1, -/// context.0 +/// context.0, /// ) /// } /// } @@ -108,7 +108,7 @@ where let schema = post_graphql_schema.clone(); async move { let query = str::from_utf8(body.as_ref()) - .map_err(|e| anyhow!("Request body query is not a valid UTF-8 string: {}", e))?; + .map_err(|e| anyhow!("Request body query is not a valid UTF-8 string: {e}"))?; let req = GraphQLRequest::new(query.into(), None, None); let resp = req.execute(&schema, &context).await; @@ -192,7 +192,7 @@ where async move { let res = task::spawn_blocking(move || { let query = str::from_utf8(body.as_ref()) - .map_err(|e| anyhow!("Request body is not a valid UTF-8 string: {}", e))?; + .map_err(|e| anyhow!("Request body is not a valid UTF-8 string: {e}"))?; let req = GraphQLRequest::new(query.into(), None, None); let resp = req.execute_sync(&schema, &context); @@ -359,7 +359,7 @@ pub mod subscriptions { struct Message(warp::ws::Message); - impl std::convert::TryFrom for ClientMessage { + impl TryFrom for ClientMessage { type Error = serde_json::Error; fn try_from(msg: Message) -> serde_json::Result { @@ -381,8 +381,8 @@ pub mod subscriptions { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Warp(e) => write!(f, "warp error: {}", e), - Self::Serde(e) => write!(f, "serde error: {}", e), + Self::Warp(e) => write!(f, "warp error: {e}"), + Self::Serde(e) => write!(f, "serde error: {e}"), } } } @@ -711,7 +711,7 @@ mod tests_http_harness { const QUERY_ENCODE_SET: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>'); - let url = Url::parse(&format!("http://localhost:3000{}", url)).expect("url to parse"); + let url = Url::parse(&format!("http://localhost:3000{url}")).expect("url to parse"); let url: String = utf8_percent_encode(url.query().unwrap_or(""), QUERY_ENCODE_SET) .into_iter() @@ -721,7 +721,7 @@ mod tests_http_harness { self.make_request( warp::test::request() .method("GET") - .path(&format!("/?{}", url)), + .path(&format!("/?{url}")), ) } @@ -756,7 +756,7 @@ mod tests_http_harness { .expect("missing content-type header in warp response") .to_str() .expect("invalid content-type string") - .to_owned(), + .into(), } } diff --git a/tests/codegen/Cargo.toml b/tests/codegen/Cargo.toml index f08b1f1a..e8a62a0a 100644 --- a/tests/codegen/Cargo.toml +++ b/tests/codegen/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "juniper_codegen_tests" version = "0.0.0" -edition = "2018" +edition = "2021" publish = false [dependencies] diff --git a/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.rs b/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.rs index dfe2d7b5..e2ed37ea 100644 --- a/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.rs +++ b/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.rs @@ -7,7 +7,7 @@ pub struct ObjA { #[graphql_object(impl = CharacterValue)] impl ObjA { fn id(&self, is_present: bool) -> &str { - is_present.then(|| self.id.as_str()).unwrap_or("missing") + is_present.then_some(&*self.id).unwrap_or("missing") } } diff --git a/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.stderr b/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.stderr index a1b8ce2f..54af26a8 100644 --- a/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.stderr +++ b/tests/codegen/fail/interface/struct/attr_additional_non_nullable_argument.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 16 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/struct/attr_additional_non_nullable_argument.rs:16:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/struct/attr_additional_non_nullable_argument.rs:16:5 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 16 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/struct/attr_additional_non_nullable_argument.rs:16:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/attr_missing_field.stderr b/tests/codegen/fail/interface/struct/attr_missing_field.stderr index 3c3d2ccb..03cc673f 100644 --- a/tests/codegen/fail/interface/struct/attr_missing_field.stderr +++ b/tests/codegen/fail/interface/struct/attr_missing_field.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/attr_missing_field.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/struct/attr_missing_field.rs:11:5 @@ -337,7 +337,7 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/attr_missing_field.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/struct/attr_missing_field.rs:11:5 @@ -497,7 +497,7 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/attr_missing_field.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/struct/attr_missing_field.rs:11:5 @@ -829,7 +829,7 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/attr_missing_field.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/struct/attr_missing_field.rs:11:5 diff --git a/tests/codegen/fail/interface/struct/attr_missing_for_attr.stderr b/tests/codegen/fail/interface/struct/attr_missing_for_attr.stderr index b7008d17..cf2b405e 100644 --- a/tests/codegen/fail/interface/struct/attr_missing_for_attr.stderr +++ b/tests/codegen/fail/interface/struct/attr_missing_for_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 3 | #[derive(GraphQLObject)] | ^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing implementer reference in interface's `for` attribute.', $DIR/fail/interface/struct/attr_missing_for_attr.rs:3:10 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/attr_missing_impl_attr.stderr b/tests/codegen/fail/interface/struct/attr_missing_impl_attr.stderr index f03491d3..e92ba3d6 100644 --- a/tests/codegen/fail/interface/struct/attr_missing_impl_attr.stderr +++ b/tests/codegen/fail/interface/struct/attr_missing_impl_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 8 | #[graphql_interface(for = ObjA)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing interface reference in implementer's `impl` attribute.', $DIR/fail/interface/struct/attr_missing_impl_attr.rs:8:1 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/attr_missing_transitive_impl.stderr b/tests/codegen/fail/interface/struct/attr_missing_transitive_impl.stderr index 389334dc..a77b0085 100644 --- a/tests/codegen/fail/interface/struct/attr_missing_transitive_impl.stderr +++ b/tests/codegen/fail/interface/struct/attr_missing_transitive_impl.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 8 | #[graphql_interface(impl = Node1Value, for = Node3Value)] | ^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Node2` on `Node3`: missing `impl = ` for transitive interface `Node1` on `Node3`.', $DIR/fail/interface/struct/attr_missing_transitive_impl.rs:8:46 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/attr_non_subtype_return.stderr b/tests/codegen/fail/interface/struct/attr_non_subtype_return.stderr index c5d9903c..67c4553a 100644 --- a/tests/codegen/fail/interface/struct/attr_non_subtype_return.stderr +++ b/tests/codegen/fail/interface/struct/attr_non_subtype_return.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/struct/attr_non_subtype_return.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/struct/attr_non_subtype_return.rs:11:5 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 11 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/struct/attr_non_subtype_return.rs:11:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.rs b/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.rs index 5636cc17..3a7d192c 100644 --- a/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.rs +++ b/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.rs @@ -7,7 +7,7 @@ pub struct ObjA { #[graphql_object(impl = CharacterValue)] impl ObjA { fn id(&self, is_present: bool) -> &str { - is_present.then(|| self.id.as_str()).unwrap_or("missing") + is_present.then_some(&*self.id).unwrap_or("missing") } } diff --git a/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.stderr b/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.stderr index aa1fd8ee..bb58c8f7 100644 --- a/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.stderr +++ b/tests/codegen/fail/interface/struct/derive_additional_non_nullable_argument.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 17 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/struct/derive_additional_non_nullable_argument.rs:17:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/struct/derive_additional_non_nullable_argument.rs:17:5 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 17 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/struct/derive_additional_non_nullable_argument.rs:17:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/derive_missing_field.stderr b/tests/codegen/fail/interface/struct/derive_missing_field.stderr index 086f4ea0..2c164bc0 100644 --- a/tests/codegen/fail/interface/struct/derive_missing_field.stderr +++ b/tests/codegen/fail/interface/struct/derive_missing_field.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/derive_missing_field.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/struct/derive_missing_field.rs:12:5 @@ -337,7 +337,7 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/derive_missing_field.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/struct/derive_missing_field.rs:12:5 @@ -497,7 +497,7 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/derive_missing_field.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/struct/derive_missing_field.rs:12:5 @@ -829,7 +829,7 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/struct/derive_missing_field.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/struct/derive_missing_field.rs:12:5 diff --git a/tests/codegen/fail/interface/struct/derive_missing_for_attr.stderr b/tests/codegen/fail/interface/struct/derive_missing_for_attr.stderr index 9f394b97..2364122c 100644 --- a/tests/codegen/fail/interface/struct/derive_missing_for_attr.stderr +++ b/tests/codegen/fail/interface/struct/derive_missing_for_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 3 | #[derive(GraphQLObject)] | ^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing implementer reference in interface's `for` attribute.', $DIR/fail/interface/struct/derive_missing_for_attr.rs:3:10 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/derive_missing_impl_attr.stderr b/tests/codegen/fail/interface/struct/derive_missing_impl_attr.stderr index e092494a..98bd18dd 100644 --- a/tests/codegen/fail/interface/struct/derive_missing_impl_attr.stderr +++ b/tests/codegen/fail/interface/struct/derive_missing_impl_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 8 | #[derive(GraphQLInterface)] | ^^^^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing interface reference in implementer's `impl` attribute.', $DIR/fail/interface/struct/derive_missing_impl_attr.rs:8:10 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/derive_missing_transitive_impl.stderr b/tests/codegen/fail/interface/struct/derive_missing_transitive_impl.stderr index 278b725f..2b7a8e49 100644 --- a/tests/codegen/fail/interface/struct/derive_missing_transitive_impl.stderr +++ b/tests/codegen/fail/interface/struct/derive_missing_transitive_impl.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 10 | #[graphql(impl = Node1Value, for = Node3Value)] | ^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Node2` on `Node3`: missing `impl = ` for transitive interface `Node1` on `Node3`.', $DIR/fail/interface/struct/derive_missing_transitive_impl.rs:10:36 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/struct/derive_non_subtype_return.stderr b/tests/codegen/fail/interface/struct/derive_non_subtype_return.stderr index b62b6b0f..7de89146 100644 --- a/tests/codegen/fail/interface/struct/derive_non_subtype_return.stderr +++ b/tests/codegen/fail/interface/struct/derive_non_subtype_return.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/struct/derive_non_subtype_return.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/struct/derive_non_subtype_return.rs:12:5 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 12 | id: String, | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/struct/derive_non_subtype_return.rs:12:5 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/additional_non_nullable_argument.rs b/tests/codegen/fail/interface/trait/additional_non_nullable_argument.rs index c69f0f66..d8c4060c 100644 --- a/tests/codegen/fail/interface/trait/additional_non_nullable_argument.rs +++ b/tests/codegen/fail/interface/trait/additional_non_nullable_argument.rs @@ -7,7 +7,7 @@ pub struct ObjA { #[graphql_object(impl = CharacterValue)] impl ObjA { fn id(&self, is_present: bool) -> &str { - is_present.then(|| self.id.as_str()).unwrap_or("missing") + is_present.then_some(&*self.id).unwrap_or("missing") } } diff --git a/tests/codegen/fail/interface/trait/additional_non_nullable_argument.stderr b/tests/codegen/fail/interface/trait/additional_non_nullable_argument.stderr index 4817ef41..a4030c90 100644 --- a/tests/codegen/fail/interface/trait/additional_non_nullable_argument.stderr +++ b/tests/codegen/fail/interface/trait/additional_non_nullable_argument.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/trait/additional_non_nullable_argument.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/trait/additional_non_nullable_argument.rs:16:8 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` isn't present on the interface and so has to be nullable.', $DIR/fail/interface/trait/additional_non_nullable_argument.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/missing_field.stderr b/tests/codegen/fail/interface/trait/missing_field.stderr index e8c94f94..2946f941 100644 --- a/tests/codegen/fail/interface/trait/missing_field.stderr +++ b/tests/codegen/fail/interface/trait/missing_field.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/trait/missing_field.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/trait/missing_field.rs:11:8 @@ -337,7 +337,7 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/trait/missing_field.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/trait/missing_field.rs:11:8 @@ -497,7 +497,7 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/trait/missing_field.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: erroneous constant used --> fail/interface/trait/missing_field.rs:11:8 @@ -829,7 +829,7 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id` isn't implemented on `ObjA`.', $DIR/fail/interface/trait/missing_field.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error: any use of this value will cause an error --> fail/interface/trait/missing_field.rs:11:8 diff --git a/tests/codegen/fail/interface/trait/missing_field_argument.stderr b/tests/codegen/fail/interface/trait/missing_field_argument.stderr index 276222f7..c2f0b857 100644 --- a/tests/codegen/fail/interface/trait/missing_field_argument.stderr +++ b/tests/codegen/fail/interface/trait/missing_field_argument.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self, is_present: bool) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` was expected, but not found.', $DIR/fail/interface/trait/missing_field_argument.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/trait/missing_field_argument.rs:16:8 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self, is_present: bool) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent` of type `Boolean!` was expected, but not found.', $DIR/fail/interface/trait/missing_field_argument.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/missing_for_attr.stderr b/tests/codegen/fail/interface/trait/missing_for_attr.stderr index da011ad9..7df8c5b6 100644 --- a/tests/codegen/fail/interface/trait/missing_for_attr.stderr +++ b/tests/codegen/fail/interface/trait/missing_for_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 3 | #[derive(GraphQLObject)] | ^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing implementer reference in interface's `for` attribute.', $DIR/fail/interface/trait/missing_for_attr.rs:3:10 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/missing_impl_attr.stderr b/tests/codegen/fail/interface/trait/missing_impl_attr.stderr index a82878d6..64973413 100644 --- a/tests/codegen/fail/interface/trait/missing_impl_attr.stderr +++ b/tests/codegen/fail/interface/trait/missing_impl_attr.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 8 | #[graphql_interface(for = ObjA)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: missing interface reference in implementer's `impl` attribute.', $DIR/fail/interface/trait/missing_impl_attr.rs:8:1 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/missing_transitive_impl.stderr b/tests/codegen/fail/interface/trait/missing_transitive_impl.stderr index f120ac36..8655cc68 100644 --- a/tests/codegen/fail/interface/trait/missing_transitive_impl.stderr +++ b/tests/codegen/fail/interface/trait/missing_transitive_impl.stderr @@ -4,4 +4,4 @@ error[E0080]: evaluation of constant value failed 8 | #[graphql_interface(impl = Node1Value, for = Node3Value)] | ^^^^^^^^^^ the evaluated program panicked at 'Failed to implement interface `Node2` on `Node3`: missing `impl = ` for transitive interface `Node1` on `Node3`.', $DIR/fail/interface/trait/missing_transitive_impl.rs:8:46 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/non_subtype_return.stderr b/tests/codegen/fail/interface/trait/non_subtype_return.stderr index 92e123f2..608542e9 100644 --- a/tests/codegen/fail/interface/trait/non_subtype_return.stderr +++ b/tests/codegen/fail/interface/trait/non_subtype_return.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/trait/non_subtype_return.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/trait/non_subtype_return.rs:11:8 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 11 | fn id(&self) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: implementor is expected to return a subtype of interface's return object: `[String!]!` is not a subtype of `String!`.', $DIR/fail/interface/trait/non_subtype_return.rs:11:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/interface/trait/wrong_argument_type.stderr b/tests/codegen/fail/interface/trait/wrong_argument_type.stderr index 3a47b725..3575bacf 100644 --- a/tests/codegen/fail/interface/trait/wrong_argument_type.stderr +++ b/tests/codegen/fail/interface/trait/wrong_argument_type.stderr @@ -4,7 +4,7 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self, is_present: bool) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent`: expected type `Boolean!`, found: `Int!`.', $DIR/fail/interface/trait/wrong_argument_type.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> fail/interface/trait/wrong_argument_type.rs:16:8 @@ -12,4 +12,4 @@ error[E0080]: evaluation of constant value failed 16 | fn id(&self, is_present: bool) -> &str; | ^^ the evaluated program panicked at 'Failed to implement interface `Character` on `ObjA`: Field `id`: Argument `isPresent`: expected type `Boolean!`, found: `Int!`.', $DIR/fail/interface/trait/wrong_argument_type.rs:16:8 | - = note: this error originates in the macro `$crate::panic::panic_2015` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::panic::panic_2021` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/codegen/fail/union/trait_fail_infer_context.stderr b/tests/codegen/fail/union/trait_fail_infer_context.stderr index ab1d3071..35b54f78 100644 --- a/tests/codegen/fail/union/trait_fail_infer_context.stderr +++ b/tests/codegen/fail/union/trait_fail_infer_context.stderr @@ -23,6 +23,6 @@ error[E0308]: mismatched types note: associated function defined here --> $WORKSPACE/juniper/src/executor/mod.rs | - | fn into(self, ctx: &'a C) -> FieldResult, S>; - | ^^^^ + | fn into_resolvable(self, ctx: &'a C) -> FieldResult, S>; + | ^^^^^^^^^^^^^^^ = note: this error originates in the attribute macro `graphql_union` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/integration/Cargo.toml b/tests/integration/Cargo.toml index 2b2c3cc7..8645376e 100644 --- a/tests/integration/Cargo.toml +++ b/tests/integration/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "juniper_integration_tests" version = "0.0.0" -edition = "2018" +edition = "2021" publish = false [dependencies] diff --git a/tests/integration/src/codegen/derive_object_with_raw_idents.rs b/tests/integration/src/codegen/derive_object_with_raw_idents.rs index c1c5dea7..48d6d159 100644 --- a/tests/integration/src/codegen/derive_object_with_raw_idents.rs +++ b/tests/integration/src/codegen/derive_object_with_raw_idents.rs @@ -99,6 +99,6 @@ async fn run_type_info_query(doc: &str) -> Value { assert_eq!(errs, []); - println!("Result: {:#?}", result); + println!("Result: {result:#?}"); result } diff --git a/tests/integration/src/codegen/interface_attr_struct.rs b/tests/integration/src/codegen/interface_attr_struct.rs index 8d0e4f58..5c91b8b7 100644 --- a/tests/integration/src/codegen/interface_attr_struct.rs +++ b/tests/integration/src/codegen/interface_attr_struct.rs @@ -117,13 +117,13 @@ mod trivial { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -188,13 +188,12 @@ mod trivial { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -247,17 +246,16 @@ mod trivial { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -347,13 +345,13 @@ mod explicit_alias { fn character(&self) -> CharacterEnum { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -418,13 +416,12 @@ mod explicit_alias { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -523,13 +520,13 @@ mod trivial_async { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -591,13 +588,12 @@ mod trivial_async { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -650,17 +646,16 @@ mod trivial_async { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -758,13 +753,13 @@ mod fallible_field { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -829,13 +824,12 @@ mod fallible_field { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -928,13 +922,13 @@ mod generic { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -999,13 +993,12 @@ mod generic { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1054,8 +1047,8 @@ mod description_from_doc_comment { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1121,7 +1114,7 @@ mod deprecation_from_attr { } fn b() -> String { - "b".to_owned() + "b".into() } } @@ -1131,8 +1124,8 @@ mod deprecation_from_attr { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1258,7 +1251,7 @@ mod explicit_name_description_and_deprecation { } fn a() -> String { - "a".to_owned() + "a".into() } fn b() -> &'static str { @@ -1272,8 +1265,8 @@ mod explicit_name_description_and_deprecation { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1532,13 +1525,13 @@ mod explicit_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1603,13 +1596,12 @@ mod explicit_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1662,13 +1654,13 @@ mod custom_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1733,13 +1725,12 @@ mod custom_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema_with_scalar::(*root); + let schema = schema_with_scalar::(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1790,13 +1781,13 @@ mod explicit_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1861,13 +1852,12 @@ mod explicit_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1918,13 +1908,13 @@ mod bounded_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1989,13 +1979,12 @@ mod bounded_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2031,8 +2020,8 @@ mod ignored_method { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -2143,13 +2132,13 @@ mod field_return_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2214,13 +2203,12 @@ mod field_return_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2297,14 +2285,14 @@ mod field_return_union_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), key_feature: Knowledge { value: 10 }, } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), strength: 42, } .into(), @@ -2386,14 +2374,12 @@ mod field_return_union_subtyping { } }"#; - for (root, expected_id, expected_val) in &[ + for (root, expected_id, expected_val) in [ (QueryRoot::Human, "human-32", 10), (QueryRoot::Droid, "droid-99", 42), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; - let expected_val = *expected_val; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( @@ -2433,7 +2419,7 @@ mod nullable_argument_subtyping { fn id(&self, is_present: Option) -> &str { is_present .unwrap_or_default() - .then(|| self.id.as_str()) + .then_some(&*self.id) .unwrap_or("missing") } @@ -2453,13 +2439,13 @@ mod nullable_argument_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2524,13 +2510,12 @@ mod nullable_argument_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "missing"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2566,16 +2551,16 @@ mod simple_subtyping { impl QueryRoot { fn node() -> NodeValue { Endpoint { - id: ID::from("1".to_owned()), - url: "2".to_owned(), + id: ID::new("1"), + url: "2".into(), } .into() } fn resource() -> ResourceValue { Endpoint { - id: ID::from("3".to_owned()), - url: "4".to_owned(), + id: ID::new("3"), + url: "4".into(), } .into() } @@ -2586,11 +2571,10 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -2721,14 +2705,13 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ possibleTypes {{ kind name }} }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -2765,14 +2748,13 @@ mod simple_subtyping { ] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ interfaces {{ kind name }} }} }}"#, - name, ); assert_eq!( @@ -2851,8 +2833,8 @@ mod branching_subtyping { Self::Luke => HumanConnection { nodes: vec![Luke { id: ID::new("1"), - home_planet: "earth".to_owned(), - father: "SPOILER".to_owned(), + home_planet: "earth".into(), + father: "SPOILER".into(), } .into()], } @@ -2860,7 +2842,7 @@ mod branching_subtyping { Self::R2D2 => DroidConnection { nodes: vec![R2D2 { id: ID::new("2"), - primary_function: "roll".to_owned(), + primary_function: "roll".into(), charge: 146.0, } .into()], @@ -2875,11 +2857,10 @@ mod branching_subtyping { for name in ["Node", "Connection", "Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot::Luke); diff --git a/tests/integration/src/codegen/interface_attr_trait.rs b/tests/integration/src/codegen/interface_attr_trait.rs index 7892a027..0ee39c8b 100644 --- a/tests/integration/src/codegen/interface_attr_trait.rs +++ b/tests/integration/src/codegen/interface_attr_trait.rs @@ -116,13 +116,13 @@ mod trivial { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -187,13 +187,12 @@ mod trivial { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -246,17 +245,16 @@ mod trivial { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -346,13 +344,13 @@ mod explicit_alias { fn character(&self) -> CharacterEnum { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -417,13 +415,12 @@ mod explicit_alias { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -522,13 +519,13 @@ mod trivial_async { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -593,13 +590,12 @@ mod trivial_async { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -652,17 +648,16 @@ mod trivial_async { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -760,13 +755,13 @@ mod fallible_field { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -831,13 +826,12 @@ mod fallible_field { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -927,13 +921,13 @@ mod generic { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -995,13 +989,12 @@ mod generic { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1074,8 +1067,8 @@ mod argument { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1085,7 +1078,7 @@ mod argument { async fn resolves_id_field() { let schema = schema(QueryRoot); - for (input, expected) in &[ + for (input, expected) in [ ( "{ character { idWide(isNumber: true), idWide2(isNumber: true) } }", "human-32", @@ -1095,10 +1088,8 @@ mod argument { "none", ), ] { - let expected: &str = *expected; - assert_eq!( - execute(*input, None, &schema, &graphql_vars! {}, &()).await, + execute(input, None, &schema, &graphql_vars! {}, &()).await, Ok(( graphql_value!({"character": { "idWide": expected, @@ -1211,7 +1202,7 @@ mod default_argument { fn id( &self, #[graphql(default)] first: String, - #[graphql(default = "second".to_string())] second: String, + #[graphql(default = "second")] second: String, #[graphql(default = "t")] third: String, ) -> String; @@ -1227,7 +1218,7 @@ mod default_argument { } async fn id(&self, first: String, second: String, third: String) -> String { - format!("{}|{}&{}", first, second, third) + format!("{first}|{second}&{third}") } } @@ -1244,7 +1235,7 @@ mod default_argument { async fn resolves_id_field() { let schema = schema(QueryRoot); - for (input, expected) in &[ + for (input, expected) in [ ("{ character { id } }", "|second&t"), (r#"{ character { id(first: "first") } }"#, "first|second&t"), (r#"{ character { id(second: "") } }"#, "|&t"), @@ -1257,10 +1248,8 @@ mod default_argument { "first|&", ), ] { - let expected: &str = *expected; - assert_eq!( - execute(*input, None, &schema, &graphql_vars! {}, &()).await, + execute(input, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected}}), vec![])), ); } @@ -1270,14 +1259,12 @@ mod default_argument { async fn resolves_info_field() { let schema = schema(QueryRoot); - for (input, expected) in &[ + for (input, expected) in [ ("{ character { info } }", 1), ("{ character { info(coord: {x: 2}) } }", 2), ] { - let expected: i32 = *expected; - assert_eq!( - execute(*input, None, &schema, &graphql_vars! {}, &()).await, + execute(input, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"info": expected}}), vec![])), ); } @@ -1358,8 +1345,8 @@ mod description_from_doc_comment { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1425,7 +1412,7 @@ mod deprecation_from_attr { } fn b() -> String { - "b".to_owned() + "b".into() } } @@ -1435,8 +1422,8 @@ mod deprecation_from_attr { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1562,7 +1549,7 @@ mod explicit_name_description_and_deprecation { } fn a() -> String { - "a".to_owned() + "a".into() } fn b() -> &'static str { @@ -1576,8 +1563,8 @@ mod explicit_name_description_and_deprecation { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1854,13 +1841,13 @@ mod explicit_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1925,13 +1912,12 @@ mod explicit_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1984,13 +1970,13 @@ mod custom_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2055,13 +2041,12 @@ mod custom_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema_with_scalar::(*root); + let schema = schema_with_scalar::(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2112,13 +2097,13 @@ mod explicit_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2183,13 +2168,12 @@ mod explicit_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2240,13 +2224,13 @@ mod bounded_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2311,13 +2295,12 @@ mod bounded_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2401,13 +2384,13 @@ mod explicit_custom_context { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2474,15 +2457,12 @@ mod explicit_custom_context { } }"#; - for (root, expected_id, expected_info, expexted_more) in &[ + for (root, expected_id, expected_info, expexted_more) in [ (QueryRoot::Human, "human-32", "earth", "human"), (QueryRoot::Droid, "droid-99", "run", "droid"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; - let expected_info: &str = *expected_info; - let expexted_more: &str = *expexted_more; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &CustomContext).await, Ok(( @@ -2561,11 +2541,11 @@ mod inferred_custom_context_from_field { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - home_planet: "earth".to_string(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - primary_function: "run".to_string(), + primary_function: "run".into(), } .into(), } @@ -2633,15 +2613,13 @@ mod inferred_custom_context_from_field { } }"#; - for (root, expected_id, expected_info) in &[ + for (root, expected_id, expected_info) in [ (QueryRoot::Human, "human-ctx", "earth"), (QueryRoot::Droid, "droid-ctx", "run"), ] { - let schema = schema(*root); - let ctx = CustomContext(expected_id.to_string()); + let schema = schema(root); + let ctx = CustomContext(expected_id.into()); - let expected_id: &str = *expected_id; - let expected_info: &str = *expected_info; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &ctx).await, Ok(( @@ -2725,11 +2703,11 @@ mod executor { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - home_planet: "earth".to_string(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - primary_function: "run".to_string(), + primary_function: "run".into(), } .into(), } @@ -2795,10 +2773,9 @@ mod executor { } }"#; - for (root, expected_info) in &[(QueryRoot::Human, "earth"), (QueryRoot::Droid, "run")] { - let schema = schema(*root); + for (root, expected_info) in [(QueryRoot::Human, "earth"), (QueryRoot::Droid, "run")] { + let schema = schema(root); - let expected_info: &str = *expected_info; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( @@ -2869,8 +2846,8 @@ mod ignored_method { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -2981,13 +2958,13 @@ mod field_return_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -3052,13 +3029,12 @@ mod field_return_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -3136,14 +3112,14 @@ mod field_return_union_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), key_feature: Knowledge { value: 10 }, } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), strength: 42, } .into(), @@ -3225,14 +3201,12 @@ mod field_return_union_subtyping { } }"#; - for (root, expected_id, expected_val) in &[ + for (root, expected_id, expected_val) in [ (QueryRoot::Human, "human-32", 10), (QueryRoot::Droid, "droid-99", 42), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; - let expected_val = *expected_val; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( @@ -3272,7 +3246,7 @@ mod nullable_argument_subtyping { fn id(&self, is_present: Option) -> &str { is_present .unwrap_or_default() - .then(|| self.id.as_str()) + .then_some(&*self.id) .unwrap_or("missing") } @@ -3292,13 +3266,13 @@ mod nullable_argument_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -3363,13 +3337,12 @@ mod nullable_argument_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "missing"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -3405,16 +3378,16 @@ mod simple_subtyping { impl QueryRoot { fn node() -> NodeValue { Endpoint { - id: ID::from("1".to_owned()), - url: "2".to_owned(), + id: ID::new("1"), + url: "2".into(), } .into() } fn resource() -> ResourceValue { Endpoint { - id: ID::from("3".to_owned()), - url: "4".to_owned(), + id: ID::new("3"), + url: "4".into(), } .into() } @@ -3425,11 +3398,10 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -3560,14 +3532,13 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ possibleTypes {{ kind name }} }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -3604,14 +3575,13 @@ mod simple_subtyping { ] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ interfaces {{ kind name }} }} }}"#, - name, ); assert_eq!( @@ -3690,8 +3660,8 @@ mod branching_subtyping { Self::Luke => HumanConnection { nodes: vec![Luke { id: ID::new("1"), - home_planet: "earth".to_owned(), - father: "SPOILER".to_owned(), + home_planet: "earth".into(), + father: "SPOILER".into(), } .into()], } @@ -3699,7 +3669,7 @@ mod branching_subtyping { Self::R2D2 => DroidConnection { nodes: vec![R2D2 { id: ID::new("2"), - primary_function: "roll".to_owned(), + primary_function: "roll".into(), charge: 146.0, } .into()], @@ -3714,11 +3684,10 @@ mod branching_subtyping { for name in ["Node", "Connection", "Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot::Luke); diff --git a/tests/integration/src/codegen/interface_derive.rs b/tests/integration/src/codegen/interface_derive.rs index bbc6a79a..f5a24bf3 100644 --- a/tests/integration/src/codegen/interface_derive.rs +++ b/tests/integration/src/codegen/interface_derive.rs @@ -118,13 +118,13 @@ mod trivial { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -189,13 +189,12 @@ mod trivial { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -248,17 +247,16 @@ mod trivial { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -349,13 +347,13 @@ mod explicit_alias { fn character(&self) -> CharacterEnum { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -420,13 +418,12 @@ mod explicit_alias { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -526,13 +523,13 @@ mod trivial_async { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -597,13 +594,12 @@ mod trivial_async { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -656,17 +652,16 @@ mod trivial_async { async fn registers_itself_in_implementers() { let schema = schema(QueryRoot::Human); - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ interfaces {{ kind name }} }} }}"#, - object, ); assert_eq!( @@ -765,13 +760,13 @@ mod fallible_field { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -836,13 +831,12 @@ mod fallible_field { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -936,13 +930,13 @@ mod generic { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1007,13 +1001,12 @@ mod generic { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1063,8 +1056,8 @@ mod description_from_doc_comment { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1131,7 +1124,7 @@ mod deprecation_from_attr { } fn b() -> String { - "b".to_owned() + "b".into() } } @@ -1141,8 +1134,8 @@ mod deprecation_from_attr { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1269,7 +1262,7 @@ mod explicit_name_description_and_deprecation { } fn a() -> String { - "a".to_owned() + "a".into() } fn b() -> &'static str { @@ -1283,8 +1276,8 @@ mod explicit_name_description_and_deprecation { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -1545,13 +1538,13 @@ mod explicit_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1616,13 +1609,12 @@ mod explicit_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1676,13 +1668,13 @@ mod custom_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1747,13 +1739,12 @@ mod custom_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema_with_scalar::(*root); + let schema = schema_with_scalar::(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1805,13 +1796,13 @@ mod explicit_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -1876,13 +1867,12 @@ mod explicit_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -1934,13 +1924,13 @@ mod bounded_generic_scalar { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2005,13 +1995,12 @@ mod bounded_generic_scalar { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2048,8 +2037,8 @@ mod ignored_method { impl QueryRoot { fn character(&self) -> CharacterValue { Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into() } @@ -2161,13 +2150,13 @@ mod field_return_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2232,13 +2221,12 @@ mod field_return_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "droid-99"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2316,14 +2304,14 @@ mod field_return_union_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), key_feature: Knowledge { value: 10 }, } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), strength: 42, } .into(), @@ -2405,14 +2393,12 @@ mod field_return_union_subtyping { } }"#; - for (root, expected_id, expected_val) in &[ + for (root, expected_id, expected_val) in [ (QueryRoot::Human, "human-32", 10), (QueryRoot::Droid, "droid-99", 42), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; - let expected_val = *expected_val; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok(( @@ -2453,7 +2439,7 @@ mod nullable_argument_subtyping { fn id(&self, is_present: Option) -> &str { is_present .unwrap_or_default() - .then(|| self.id.as_str()) + .then_some(&*self.id) .unwrap_or("missing") } @@ -2473,13 +2459,13 @@ mod nullable_argument_subtyping { fn character(&self) -> CharacterValue { match self { Self::Human => Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), } .into(), Self::Droid => Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), } .into(), } @@ -2544,13 +2530,12 @@ mod nullable_argument_subtyping { } }"#; - for (root, expected_id) in &[ + for (root, expected_id) in [ (QueryRoot::Human, "human-32"), (QueryRoot::Droid, "missing"), ] { - let schema = schema(*root); + let schema = schema(root); - let expected_id: &str = *expected_id; assert_eq!( execute(DOC, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"character": {"id": expected_id}}), vec![])), @@ -2588,16 +2573,16 @@ mod simple_subtyping { impl QueryRoot { fn node() -> NodeValue { Endpoint { - id: ID::from("1".to_owned()), - url: "2".to_owned(), + id: ID::new("1"), + url: "2".into(), } .into() } fn resource() -> ResourceValue { Endpoint { - id: ID::from("3".to_owned()), - url: "4".to_owned(), + id: ID::new("3"), + url: "4".into(), } .into() } @@ -2608,11 +2593,10 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -2743,14 +2727,13 @@ mod simple_subtyping { for name in ["Node", "Resource"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ possibleTypes {{ kind name }} }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -2787,14 +2770,13 @@ mod simple_subtyping { ] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ interfaces {{ kind name }} }} }}"#, - name, ); assert_eq!( @@ -2877,8 +2859,8 @@ mod branching_subtyping { Self::Luke => HumanConnection { nodes: vec![Luke { id: ID::new("1"), - home_planet: "earth".to_owned(), - father: "SPOILER".to_owned(), + home_planet: "earth".into(), + father: "SPOILER".into(), } .into()], } @@ -2886,7 +2868,7 @@ mod branching_subtyping { Self::R2D2 => DroidConnection { nodes: vec![R2D2 { id: ID::new("2"), - primary_function: "roll".to_owned(), + primary_function: "roll".into(), charge: 146.0, } .into()], @@ -2901,11 +2883,10 @@ mod branching_subtyping { for name in ["Node", "Connection", "Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot::Luke); diff --git a/tests/integration/src/codegen/object_attr.rs b/tests/integration/src/codegen/object_attr.rs index 5a10710c..6c3cdd9d 100644 --- a/tests/integration/src/codegen/object_attr.rs +++ b/tests/integration/src/codegen/object_attr.rs @@ -376,7 +376,7 @@ mod fallible_method { impl QueryRoot { fn human() -> Human { Human { - id: "human-32".to_string(), + id: "human-32".into(), } } } @@ -885,22 +885,20 @@ mod nested_generic_lifetime_async { #[tokio::test] async fn uses_type_name_without_type_params() { - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ name }} }}"#, - object, ); let schema = schema(QueryRoot("mars".into())); - let expected_name: &str = *object; assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, - Ok((graphql_value!({"__type": {"name": expected_name}}), vec![])), + Ok((graphql_value!({"__type": {"name": object}}), vec![])), ); } } @@ -918,7 +916,7 @@ mod argument { } async fn home_planet(&self, r#raw_arg: String, r#async: Option) -> String { - format!("{},{:?}", r#raw_arg, r#async) + format!("{raw_arg},{async:?}") } } @@ -1048,7 +1046,7 @@ mod default_argument { #[graphql(default = "second".to_string())] arg2: Option, #[graphql(default = true)] r#arg3: bool, ) -> String { - format!("{}|{:?}&{}", arg1, arg2, r#arg3) + format!("{arg1}|{arg2:?}&{arg3}") } fn info(#[graphql(default = Point { x: 1 })] coord: Point) -> i32 { @@ -1069,7 +1067,7 @@ mod default_argument { async fn resolves_id_field() { let schema = schema(QueryRoot); - for (input, expected, vars) in &[ + for (input, expected, vars) in [ ( "{ human { id } }", r#"0|Some("second")&true"#, @@ -1131,10 +1129,8 @@ mod default_argument { graphql_vars! {}, ), ] { - let expected: &str = *expected; - assert_eq!( - execute(*input, None, &schema, &vars, &(),).await, + execute(input, None, &schema, &vars, &(),).await, Ok((graphql_value!({"human": {"id": expected}}), vec![])), ); } @@ -1144,14 +1140,12 @@ mod default_argument { async fn resolves_info_field() { let schema = schema(QueryRoot); - for (input, expected) in &[ + for (input, expected) in [ ("{ human { info } }", 1), ("{ human { info(coord: { x: 2 }) } }", 2), ] { - let expected: i32 = *expected; - assert_eq!( - execute(*input, None, &schema, &graphql_vars! {}, &()).await, + execute(input, None, &schema, &graphql_vars! {}, &()).await, Ok((graphql_value!({"human": {"info": expected}}), vec![])), ); } diff --git a/tests/integration/src/codegen/object_derive.rs b/tests/integration/src/codegen/object_derive.rs index 126c315a..9b0b86d8 100644 --- a/tests/integration/src/codegen/object_derive.rs +++ b/tests/integration/src/codegen/object_derive.rs @@ -406,22 +406,20 @@ mod nested_generic_lifetime_async { #[tokio::test] async fn uses_type_name_without_type_params() { - for object in &["Human", "Droid"] { + for object in ["Human", "Droid"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{object}") {{ name }} }}"#, - object, ); let schema = schema(QueryRoot("mars".into())); - let expected_name: &str = *object; assert_eq!( execute(&doc, None, &schema, &graphql_vars! {}, &()).await, - Ok((graphql_value!({"__type": {"name": expected_name}}), vec![])), + Ok((graphql_value!({"__type": {"name": object}}), vec![])), ); } } diff --git a/tests/integration/src/codegen/scalar_attr_derive_input.rs b/tests/integration/src/codegen/scalar_attr_derive_input.rs index e2b30a30..dd10bd30 100644 --- a/tests/integration/src/codegen/scalar_attr_derive_input.rs +++ b/tests/integration/src/codegen/scalar_attr_derive_input.rs @@ -29,7 +29,7 @@ mod trivial { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(t: ScalarToken<'_>) -> ParseScalarResult { @@ -237,7 +237,7 @@ mod all_custom_resolvers { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Counter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -312,7 +312,7 @@ mod explicit_name { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -388,7 +388,7 @@ mod delegated_parse_token { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -458,7 +458,7 @@ mod multiple_delegated_parse_token { impl StringOrInt { fn to_output(&self) -> Value { match self { - Self::String(str) => Value::scalar(str.to_owned()), + Self::String(s) => Value::scalar(s.to_owned()), Self::Int(i) => Value::scalar(*i), } } @@ -467,7 +467,7 @@ mod multiple_delegated_parse_token { v.as_string_value() .map(|s| Self::String(s.to_owned())) .or_else(|| v.as_int_value().map(Self::Int)) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } } @@ -533,11 +533,11 @@ mod where_attribute { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTime(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } @@ -599,7 +599,7 @@ mod with_self { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -691,11 +691,11 @@ mod with_module { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTime(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } } @@ -759,7 +759,7 @@ mod description_from_doc_comment { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -835,7 +835,7 @@ mod description_from_attribute { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -911,7 +911,7 @@ mod custom_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -987,7 +987,7 @@ mod generic_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -1062,7 +1062,7 @@ mod bounded_generic_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } diff --git a/tests/integration/src/codegen/scalar_attr_type_alias.rs b/tests/integration/src/codegen/scalar_attr_type_alias.rs index 66e25442..900f0612 100644 --- a/tests/integration/src/codegen/scalar_attr_type_alias.rs +++ b/tests/integration/src/codegen/scalar_attr_type_alias.rs @@ -34,7 +34,7 @@ mod all_custom_resolvers { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -115,7 +115,7 @@ mod explicit_name { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -152,11 +152,10 @@ mod explicit_name { for name in ["CustomCounter", "CustomScalar"] { let doc = format!( r#"{{ - __type(name: "{}") {{ + __type(name: "{name}") {{ kind }} }}"#, - name, ); let schema = schema(QueryRoot); @@ -216,7 +215,7 @@ mod delegated_parse_token { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } struct QueryRoot; @@ -290,7 +289,7 @@ mod multiple_delegated_parse_token { fn to_output(v: &StringOrInt) -> Value { match v { - StringOrInt::String(str) => Value::scalar(str.to_owned()), + StringOrInt::String(s) => Value::scalar(s.to_owned()), StringOrInt::Int(i) => Value::scalar(*i), } } @@ -299,7 +298,7 @@ mod multiple_delegated_parse_token { v.as_string_value() .map(|s| StringOrInt::String(s.to_owned())) .or_else(|| v.as_int_value().map(|i| StringOrInt::Int(i))) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } struct QueryRoot; @@ -366,11 +365,11 @@ mod where_attribute { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTimeScalar(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } @@ -434,7 +433,7 @@ mod with_self { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -528,11 +527,11 @@ mod with_module { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTimeScalar(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } } @@ -600,7 +599,7 @@ mod description_from_doc_comment { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -684,7 +683,7 @@ mod description_from_attribute { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -768,7 +767,7 @@ mod custom_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -852,7 +851,7 @@ mod generic_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -936,7 +935,7 @@ mod bounded_generic_scalar { pub(super) fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(CustomCounter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } diff --git a/tests/integration/src/codegen/scalar_derive.rs b/tests/integration/src/codegen/scalar_derive.rs index 45bd2a81..bdf9791d 100644 --- a/tests/integration/src/codegen/scalar_derive.rs +++ b/tests/integration/src/codegen/scalar_derive.rs @@ -27,7 +27,7 @@ mod trivial { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(t: ScalarToken<'_>) -> ParseScalarResult { @@ -235,7 +235,7 @@ mod all_custom_resolvers { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Counter) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -311,7 +311,7 @@ mod explicit_name { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -388,7 +388,7 @@ mod delegated_parse_token { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -459,7 +459,7 @@ mod multiple_delegated_parse_token { impl StringOrInt { fn to_output(&self) -> Value { match self { - Self::String(str) => Value::scalar(str.to_owned()), + Self::String(s) => Value::scalar(s.to_owned()), Self::Int(i) => Value::scalar(*i), } } @@ -468,7 +468,7 @@ mod multiple_delegated_parse_token { v.as_string_value() .map(|s| Self::String(s.to_owned())) .or_else(|| v.as_int_value().map(Self::Int)) - .ok_or_else(|| format!("Expected `String` or `Int`, found: {}", v)) + .ok_or_else(|| format!("Expected `String` or `Int`, found: {v}")) } } @@ -535,11 +535,11 @@ mod where_attribute { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTime(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } @@ -602,7 +602,7 @@ mod with_self { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -695,11 +695,11 @@ mod with_module { Tz::Offset: fmt::Display, { v.as_string_value() - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) .and_then(|s| { DateTime::parse_from_rfc3339(s) .map(|dt| CustomDateTime(dt.with_timezone(&Tz::from(Utc)))) - .map_err(|e| format!("Failed to parse `CustomDateTime`: {}", e)) + .map_err(|e| format!("Failed to parse `CustomDateTime`: {e}")) }) } } @@ -764,7 +764,7 @@ mod description_from_doc_comment { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -841,7 +841,7 @@ mod description_from_attribute { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -918,7 +918,7 @@ mod custom_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -995,7 +995,7 @@ mod generic_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `Counter`, found: {}", v)) + .ok_or_else(|| format!("Expected `Counter`, found: {v}")) } } @@ -1071,7 +1071,7 @@ mod bounded_generic_scalar { fn from_input(v: &InputValue) -> Result { v.as_int_value() .map(Self) - .ok_or_else(|| format!("Expected `String`, found: {}", v)) + .ok_or_else(|| format!("Expected `String`, found: {v}")) } } diff --git a/tests/integration/src/codegen/subscription_attr.rs b/tests/integration/src/codegen/subscription_attr.rs index 47535fab..94214235 100644 --- a/tests/integration/src/codegen/subscription_attr.rs +++ b/tests/integration/src/codegen/subscription_attr.rs @@ -53,12 +53,12 @@ mod trivial { #[graphql_subscription] impl Human { async fn id() -> Stream<'static, String> { - Box::pin(stream::once(future::ready("human-32".to_owned()))) + Box::pin(stream::once(future::ready("human-32".into()))) } // TODO: Make work for `Stream<'_, String>`. async fn home_planet(&self) -> Stream<'static, String> { - Box::pin(stream::once(future::ready("earth".to_owned()))) + Box::pin(stream::once(future::ready("earth".into()))) } } @@ -227,7 +227,7 @@ mod ignored_method { #[graphql_subscription] impl Human { async fn id() -> Stream<'static, String> { - Box::pin(stream::once(future::ready("human-32".to_owned()))) + Box::pin(stream::once(future::ready("human-32".into()))) } #[allow(dead_code)] @@ -291,7 +291,7 @@ mod fallible_method { #[graphql_subscription] impl Human { async fn id(&self) -> Result, CustomError> { - Ok(Box::pin(stream::once(future::ready("human-32".to_owned())))) + Ok(Box::pin(stream::once(future::ready("human-32".into())))) } async fn home_planet<__S>() -> FieldResult, __S> { @@ -387,10 +387,7 @@ mod argument { r#raw_arg: String, r#async: Option, ) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(format!( - "{},{:?}", - r#raw_arg, r#async - )))) + Box::pin(stream::once(future::ready(format!("{raw_arg},{async:?}")))) } } @@ -524,10 +521,7 @@ mod default_argument { #[graphql(default = "second".to_string())] arg2: String, #[graphql(default = true)] r#arg3: bool, ) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(format!( - "{}|{}&{}", - arg1, arg2, r#arg3 - )))) + Box::pin(stream::once(future::ready(format!("{arg1}|{arg2}&{arg3}")))) } async fn info(#[graphql(default = Point { x: 1 })] coord: Point) -> Stream<'static, i32> { @@ -539,7 +533,7 @@ mod default_argument { async fn resolves_id_field() { let schema = schema(Query, Human); - for (input, expected) in &[ + for (input, expected) in [ ("subscription { id }", "0|second&true"), ("subscription { id(arg1: 1) }", "1|second&true"), (r#"subscription { id(arg2: "") }"#, "0|&true"), @@ -549,10 +543,8 @@ mod default_argument { "1|&false", ), ] { - let expected: &str = *expected; - assert_eq!( - resolve_into_stream(*input, None, &schema, &graphql_vars! {}, &()) + resolve_into_stream(input, None, &schema, &graphql_vars! {}, &()) .then(|s| extract_next(s)) .await, Ok((graphql_value!({ "id": expected }), vec![])), @@ -564,14 +556,12 @@ mod default_argument { async fn resolves_info_field() { let schema = schema(Query, Human); - for (input, expected) in &[ + for (input, expected) in [ ("subscription { info }", 1), ("subscription { info(coord: { x: 2 }) }", 2), ] { - let expected: i32 = *expected; - assert_eq!( - resolve_into_stream(*input, None, &schema, &graphql_vars! {}, &()) + resolve_into_stream(input, None, &schema, &graphql_vars! {}, &()) .then(|s| extract_next(s)) .await, Ok((graphql_value!({ "info": expected }), vec![])), @@ -648,7 +638,7 @@ mod generic { #[graphql_subscription(name = "HumanString")] impl Human { async fn id(&self) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(self.id.to_owned()))) + Box::pin(stream::once(future::ready(self.id.clone()))) } } @@ -735,7 +725,7 @@ mod generic_lifetime { // TODO: Make it work with `Stream<'_, &str>`. async fn planet(&self) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(self.home_planet.to_owned()))) + Box::pin(stream::once(future::ready(self.home_planet.into()))) } } @@ -743,12 +733,12 @@ mod generic_lifetime { impl<'id, 'p> Human<'p, &'id str> { // TODO: Make it work with `Stream<'_, &str>`. async fn id(&self) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(self.id.to_owned()))) + Box::pin(stream::once(future::ready(self.id.into()))) } // TODO: Make it work with `Stream<'_, &str>`. async fn planet(&self) -> Stream<'static, String> { - Box::pin(stream::once(future::ready(self.home_planet.to_owned()))) + Box::pin(stream::once(future::ready(self.home_planet.into()))) } } @@ -1702,7 +1692,7 @@ mod executor { S: ScalarValue, { Box::pin(stream::once(future::ready( - executor.look_ahead().field_name().to_owned(), + executor.look_ahead().field_name().into(), ))) } diff --git a/tests/integration/src/codegen/union_attr.rs b/tests/integration/src/codegen/union_attr.rs index 9f032c4c..51e9da89 100644 --- a/tests/integration/src/codegen/union_attr.rs +++ b/tests/integration/src/codegen/union_attr.rs @@ -113,12 +113,12 @@ mod trivial { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -250,12 +250,12 @@ mod generic { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -343,8 +343,8 @@ mod description_from_doc_comment { impl QueryRoot { fn character(&self) -> Box> { Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -416,8 +416,8 @@ mod explicit_name_and_description { impl QueryRoot { fn character(&self) -> Box> { Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -517,12 +517,12 @@ mod explicit_scalar { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -608,12 +608,12 @@ mod custom_scalar { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -697,12 +697,12 @@ mod explicit_generic_scalar { fn character<__S: ScalarValue>(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -786,12 +786,12 @@ mod bounded_generic_scalar { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; ch @@ -872,12 +872,12 @@ mod explicit_custom_context { fn character(&self, ctx: &CustomContext) -> Box> { let ch: Box> = match ctx { CustomContext::Human => Box::new(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Box::new(DroidCustomContext { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), _ => unimplemented!(), }; @@ -959,12 +959,12 @@ mod inferred_custom_context { fn character(&self, ctx: &CustomContext) -> Box> { let ch: Box> = match ctx { CustomContext::Human => Box::new(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Box::new(DroidCustomContext { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), _ => unimplemented!(), }; @@ -1042,8 +1042,8 @@ mod ignored_method { impl QueryRoot { fn character(&self) -> Box> { Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -1134,12 +1134,12 @@ mod external_resolver { fn character(&self) -> Box> { let ch: Box> = match self { Self::Human => Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Box::new(Droid { - id: "?????".to_string(), - primary_function: "???".to_string(), + id: "?????".into(), + primary_function: "???".into(), }), }; ch @@ -1178,8 +1178,8 @@ mod external_resolver { let schema = schema(QueryRoot::Droid); let db = Database { droid: Some(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; @@ -1250,15 +1250,15 @@ mod full_featured { fn character(&self, ctx: &CustomContext) -> Box> { let ch: Box> = match ctx { CustomContext::Human => Box::new(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Box::new(DroidCustomContext { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), CustomContext::Ewok => Box::new(EwokCustomContext { - id: "ewok-1".to_string(), + id: "ewok-1".into(), funny: true, }), }; diff --git a/tests/integration/src/codegen/union_derive.rs b/tests/integration/src/codegen/union_derive.rs index be6577e2..ffab8d91 100644 --- a/tests/integration/src/codegen/union_derive.rs +++ b/tests/integration/src/codegen/union_derive.rs @@ -97,12 +97,12 @@ mod trivial_enum { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -217,12 +217,12 @@ mod generic_enum { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -317,7 +317,7 @@ mod generic_lifetime_enum { match self { Self::Human => Character::A(LifetimeHuman { id: "human-32" }), Self::Droid => Character::B(GenericDroid { - id: "droid-99".to_string(), + id: "droid-99".into(), _t: PhantomData, }), } @@ -394,8 +394,8 @@ mod description_from_doc_comments { impl QueryRoot { fn character(&self) -> Character { Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -458,8 +458,8 @@ mod explicit_name_and_description { impl QueryRoot { fn character(&self) -> Character { Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -542,12 +542,12 @@ mod explicit_scalar { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -615,12 +615,12 @@ mod custom_scalar { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -688,12 +688,12 @@ mod explicit_generic_scalar { fn character<__S: ScalarValue>(&self) -> Character<__S> { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -759,12 +759,12 @@ mod bounded_generic_scalar { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } @@ -827,12 +827,12 @@ mod custom_context { fn character(&self, ctx: &CustomContext) -> Character { match ctx { CustomContext::Human => Character::A(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Character::B(DroidCustomContext { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), _ => unimplemented!(), } @@ -896,12 +896,12 @@ mod different_context { fn character(&self, ctx: &CustomContext) -> Character { match ctx { CustomContext::Human => Character::A(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Character::B(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), _ => unimplemented!(), } @@ -966,8 +966,8 @@ mod ignored_enum_variants { impl QueryRoot { fn character(&self) -> Character { Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }) } } @@ -1053,8 +1053,8 @@ mod external_resolver_enum { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B, } @@ -1093,8 +1093,8 @@ mod external_resolver_enum { let schema = schema(QueryRoot::Droid); let db = Database { droid: Some(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; @@ -1144,12 +1144,12 @@ mod external_resolver_enum_variant { fn character(&self) -> Character { match self { Self::Human => Character::A(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => Character::B(Droid { - id: "?????".to_string(), - primary_function: "???".to_string(), + id: "?????".into(), + primary_function: "???".into(), }), } } @@ -1187,8 +1187,8 @@ mod external_resolver_enum_variant { let schema = schema(QueryRoot::Droid); let db = Database { droid: Some(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; @@ -1250,15 +1250,15 @@ mod full_featured_enum { fn character(&self, ctx: &CustomContext) -> Character<()> { match ctx { CustomContext::Human => Character::A(HumanCustomContext { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), CustomContext::Droid => Character::B(DroidCustomContext { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), CustomContext::Ewok => Character::C(EwokCustomContext { - id: "ewok-1".to_string(), + id: "ewok-1".into(), funny: true, }), } @@ -1409,7 +1409,7 @@ mod trivial_struct { Self::Human => "human-32", Self::Droid => "droid-99", } - .to_string(), + .into(), } } } @@ -1432,8 +1432,8 @@ mod trivial_struct { let schema = schema(QueryRoot::Human); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), droid: None, }; @@ -1453,8 +1453,8 @@ mod trivial_struct { let db = Database { human: None, droid: Some(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; @@ -1478,8 +1478,8 @@ mod trivial_struct { let schema = schema(QueryRoot::Human); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), droid: None, }; @@ -1501,8 +1501,8 @@ mod trivial_struct { let schema = schema(QueryRoot::Human); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), droid: None, }; @@ -1524,8 +1524,8 @@ mod trivial_struct { let schema = schema(QueryRoot::Human); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), droid: None, }; @@ -1570,7 +1570,7 @@ mod generic_struct { impl QueryRoot { fn character(&self) -> Character { Character { - id: "human-32".to_string(), + id: "human-32".into(), _s: PhantomData, } } @@ -1590,8 +1590,8 @@ mod generic_struct { let schema = schema(QueryRoot); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), }; @@ -1678,7 +1678,7 @@ mod full_featured_struct { Self::Human => "human-32", Self::Droid => "droid-99", } - .to_string(), + .into(), _s: PhantomData, } } @@ -1702,8 +1702,8 @@ mod full_featured_struct { let schema = schema(QueryRoot::Human); let db = Database { human: Some(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), }), droid: None, }; @@ -1723,8 +1723,8 @@ mod full_featured_struct { let db = Database { human: None, droid: Some(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), }), }; @@ -1804,12 +1804,12 @@ mod issue_845 { fn character(&self) -> Character { match self { Self::Human => Character::A(Box::new(Human { - id: "human-32".to_string(), - home_planet: "earth".to_string(), + id: "human-32".into(), + home_planet: "earth".into(), })), Self::Droid => Character::B(Arc::new(Droid { - id: "droid-99".to_string(), - primary_function: "run".to_string(), + id: "droid-99".into(), + primary_function: "run".into(), })), } } diff --git a/tests/integration/src/custom_scalar.rs b/tests/integration/src/custom_scalar.rs index b9acecbc..1d1c26ec 100644 --- a/tests/integration/src/custom_scalar.rs +++ b/tests/integration/src/custom_scalar.rs @@ -1,4 +1,4 @@ -use std::{convert::TryInto as _, fmt, pin::Pin}; +use std::{fmt, pin::Pin}; use futures::{stream, Stream}; use juniper::{ @@ -104,7 +104,7 @@ mod long { pub(super) fn from_input(v: &InputValue) -> Result { v.as_scalar_value::() .copied() - .ok_or_else(|| format!("Expected `MyScalarValue::Long`, found: {}", v)) + .ok_or_else(|| format!("Expected `MyScalarValue::Long`, found: {v}")) } pub(super) fn parse_token(value: ScalarToken<'_>) -> ParseScalarResult { @@ -153,7 +153,7 @@ where assert_eq!(errs, []); - println!("Result: {:?}", result); + println!("Result: {result:?}"); let obj = result.as_object_value().expect("Result is not an object"); diff --git a/tests/integration/src/issue_407.rs b/tests/integration/src/issue_407.rs index 245398c3..a8a4ef13 100644 --- a/tests/integration/src/issue_407.rs +++ b/tests/integration/src/issue_407.rs @@ -31,12 +31,12 @@ struct Droid { impl Query { fn characters() -> Vec { let human = Human { - id: "1".to_string(), - name: "Han Solo".to_string(), + id: "1".into(), + name: "Han Solo".into(), }; let droid = Droid { - id: "2".to_string(), - serial_number: "234532545235".to_string(), + id: "2".into(), + serial_number: "234532545235".into(), }; vec![Into::into(human), Into::into(droid)] } diff --git a/tests/integration/src/issue_798.rs b/tests/integration/src/issue_798.rs index fed322fc..40252406 100644 --- a/tests/integration/src/issue_798.rs +++ b/tests/integration/src/issue_798.rs @@ -42,12 +42,12 @@ impl Query { fn field(&self) -> FieldResult { match self { Self::Human => FieldResult::Human(Human { - id: "human-32".to_owned(), - home_planet: "earth".to_owned(), + id: "human-32".into(), + home_planet: "earth".into(), }), Self::Droid => FieldResult::Droid(Droid { - id: "droid-99".to_owned(), - primary_function: "run".to_owned(), + id: "droid-99".into(), + primary_function: "run".into(), }), } } diff --git a/tests/integration/src/issue_922.rs b/tests/integration/src/issue_922.rs index fd28b45f..1a89a68e 100644 --- a/tests/integration/src/issue_922.rs +++ b/tests/integration/src/issue_922.rs @@ -14,11 +14,11 @@ impl Query { vec![ Into::into(Human { id: 0, - name: "human-32".to_owned(), + name: "human-32".into(), }), Into::into(Droid { id: 1, - name: "R2-D2".to_owned(), + name: "R2-D2".into(), }), ] } diff --git a/tests/integration/src/issue_945.rs b/tests/integration/src/issue_945.rs index 369e660b..42458313 100644 --- a/tests/integration/src/issue_945.rs +++ b/tests/integration/src/issue_945.rs @@ -13,8 +13,8 @@ impl Query { fn artoo() -> Character { Character::Droid(Droid { id: 1, - name: "R2-D2".to_owned(), - sensor_color: "red".to_owned(), + name: "R2-D2".into(), + sensor_color: "red".into(), }) } } diff --git a/tests/integration/src/pre_parse.rs b/tests/integration/src/pre_parse.rs index ec987eca..28415ffc 100644 --- a/tests/integration/src/pre_parse.rs +++ b/tests/integration/src/pre_parse.rs @@ -64,15 +64,10 @@ async fn query_document_can_be_pre_parsed() { let errors = validate_input_values(&graphql_vars! {}, operation, &root_node.schema); assert!(errors.is_empty()); - let (_, errors) = execute_validated_query_async( - &document, - operation, - root_node, - &graphql_vars! {}, - &Context {}, - ) - .await - .unwrap(); + let (_, errors) = + execute_validated_query_async(&document, operation, root_node, &graphql_vars! {}, &Context) + .await + .unwrap(); assert!(errors.len() == 0); } @@ -92,7 +87,7 @@ async fn subscription_document_can_be_pre_parsed() { &operation, &root_node, &graphql_vars! {}, - &Context {}, + &Context, ) .map_ok(|(stream, errors)| juniper_subscriptions::Connection::from_stream(stream, errors)) .await